diff --git a/.branding b/.branding index fdc087ad6b..ab01808d9d 100644 --- a/.branding +++ b/.branding @@ -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 diff --git a/Cargo.lock b/Cargo.lock index b47acff397..f75eda47ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/desktop/src/app.rs b/desktop/src/app.rs index 96cfbb1b56..6b0ea29583 100644 --- a/desktop/src/app.rs +++ b/desktop/src/app.rs @@ -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, @@ -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); diff --git a/desktop/src/event.rs b/desktop/src/event.rs index cbe0f77f3b..87ae4ce8c7 100644 --- a/desktop/src/event.rs +++ b/desktop/src/event.rs @@ -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), ClipboardRead, ClipboardWrite { content: String, diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs index cfff56cd5b..d4e241dd43 100644 --- a/desktop/src/lib.rs +++ b/desktop/src/lib.rs @@ -22,6 +22,7 @@ mod persist; mod preferences; mod render; mod socket; +mod spawner; mod window; pub(crate) mod consts; diff --git a/desktop/src/render/state.rs b/desktop/src/render/state.rs index 3958b8cd3c..c3395c16a4 100644 --- a/desktop/src/render/state.rs +++ b/desktop/src/render/state.rs @@ -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); diff --git a/desktop/src/spawner.rs b/desktop/src/spawner.rs new file mode 100644 index 0000000000..afdfd077fa --- /dev/null +++ b/desktop/src/spawner.rs @@ -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); + } +} diff --git a/desktop/wrapper/src/handle_desktop_wrapper_message.rs b/desktop/wrapper/src/handle_desktop_wrapper_message.rs index df3237623a..5c4bbcc257 100644 --- a/desktop/wrapper/src/handle_desktop_wrapper_message.rs +++ b/desktop/wrapper/src/handle_desktop_wrapper_message.rs @@ -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); diff --git a/desktop/wrapper/src/lib.rs b/desktop/wrapper/src/lib.rs index e84e5e7288..216a3a1be3 100644 --- a/desktop/wrapper/src/lib.rs +++ b/desktop/wrapper/src/lib.rs @@ -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, document_store: Arc, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self { + pub fn new( + random_seed: u64, + resource_storage: Arc, + document_store: Arc, + 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 { @@ -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), - NotRun, } pub fn deserialize_editor_message(data: &[u8]) -> Option { diff --git a/desktop/wrapper/src/message_dispatcher.rs b/desktop/wrapper/src/message_dispatcher.rs index 11ac36c90f..9f35fb3f2d 100644 --- a/desktop/wrapper/src/message_dispatcher.rs +++ b/desktop/wrapper/src/message_dispatcher.rs @@ -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(); diff --git a/desktop/wrapper/src/messages.rs b/desktop/wrapper/src/messages.rs index b3663ea87e..382e662246 100644 --- a/desktop/wrapper/src/messages.rs +++ b/desktop/wrapper/src/messages.rs @@ -79,7 +79,6 @@ pub enum DesktopWrapperMessage { Input(InputMessage), IngestFile { path: PathBuf, content: Vec, action: IngestAction }, SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext }, - PollNodeGraphEvaluation, UpdateMaximized { maximized: bool }, UpdateFullscreen { fullscreen: bool }, LoadPersistedState { state: PersistedState }, diff --git a/document/format/tests/open_create.rs b/document/format/tests/open_create.rs index d58732614d..ae2b8a7ddf 100644 --- a/document/format/tests/open_create.rs +++ b/document/format/tests/open_create.rs @@ -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:?}")); diff --git a/document/format/tests/staging_and_reopen.rs b/document/format/tests/staging_and_reopen.rs index ab6eb51399..87dce9bcae 100644 --- a/document/format/tests/staging_and_reopen.rs +++ b/document/format/tests/staging_and_reopen.rs @@ -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(); diff --git a/document/graph-storage/src/attributes.rs b/document/graph-storage/src/attributes.rs index 5c4d8af165..568508535e 100644 --- a/document/graph-storage/src/attributes.rs +++ b/document/graph-storage/src/attributes.rs @@ -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 { diff --git a/document/graph-storage/src/attributes/attr.rs b/document/graph-storage/src/attributes/attr.rs index 281d916d67..1fa119cf4d 100644 --- a/document/graph-storage/src/attributes/attr.rs +++ b/document/graph-storage/src/attributes/attr.rs @@ -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"; } diff --git a/document/graph-storage/src/crdt.rs b/document/graph-storage/src/crdt.rs index 2c1d308cc2..1e18426dea 100644 --- a/document/graph-storage/src/crdt.rs +++ b/document/graph-storage/src/crdt.rs @@ -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, /// 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, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self { + pub fn new(parent: Option, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec) -> 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, }, + Meta, // Allow for future delta types without a model change Other(Value), } @@ -219,26 +223,13 @@ pub struct AttributeDelta { pub value: Option, } -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; diff --git a/document/graph-storage/src/document.rs b/document/graph-storage/src/document.rs index 9a349c7bd1..7da8ced710 100644 --- a/document/graph-storage/src/document.rs +++ b/document/graph-storage/src/document.rs @@ -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 { - 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(live: &mut HashMap, dead: } /// An addition at `timestamp`: every field written at `timestamp`, live unless a newer removal holds it dead. -fn add_entity(live: &mut HashMap, dead: &mut HashMap>, id: K, mut content: T, timestamp: TimeStamp, force: bool) { - if force { - dead.remove(&id); - live.insert(id, content); - return; - } +fn add_entity(live: &mut HashMap, dead: &mut HashMap>, 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(live: &mut HashMap, dead: &mut HashMap>, id: K, snapshot: T, timestamp: TimeStamp, force: bool) { +fn remove_entity(live: &mut HashMap, dead: &mut HashMap>, 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( 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( 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, } diff --git a/document/graph-storage/src/from_runtime.rs b/document/graph-storage/src/from_runtime.rs index d9593738bf..1f3f54fc1a 100644 --- a/document/graph-storage/src/from_runtime.rs +++ b/document/graph-storage/src/from_runtime.rs @@ -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( 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 Result { - encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default()) -} - fn encode_if_not_default(key: &str, value: &T, default: &T) -> Result { let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) }; diff --git a/document/graph-storage/src/lib.rs b/document/graph-storage/src/lib.rs index 4290a2ad95..10160e0fe9 100644 --- a/document/graph-storage/src/lib.rs +++ b/document/graph-storage/src/lib.rs @@ -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::*; diff --git a/document/graph-storage/src/prior.rs b/document/graph-storage/src/prior.rs new file mode 100644 index 0000000000..1d7b59e6be --- /dev/null +++ b/document/graph-storage/src/prior.rs @@ -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, + }, + AbsentNode { + id: NodeId, + }, + Network { + id: NetworkId, + network: Network, + }, + RemovedNetwork { + id: NetworkId, + tombstone: Tombstone, + }, + AbsentNetwork { + id: NetworkId, + }, + Resource { + id: ResourceId, + resource: ResourceEntry, + }, + RemovedResource { + id: ResourceId, + tombstone: Tombstone, + }, + 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, + }, + PeerUser { + peer: PeerId, + previous: Option, + }, +} + +#[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, + }, + Input { + index: u32, + previous: InputSlot, + }, + InputAttribute { + index: u32, + key: String, + previous: Option, + }, + Inputs { + previous: Vec, + 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, + }, + Exports { + previous: Vec, + }, +} + +/// 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 { + 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(live: &mut HashMap, dead: &mut HashMap>, id: K, content: &T) { + dead.remove(&id); + live.insert(id, content.clone()); +} + +fn put_removed(live: &mut HashMap, dead: &mut HashMap>, id: K, tombstone: &Tombstone) { + live.remove(&id); + dead.insert(id, tombstone.clone()); +} + +fn put_absent(live: &mut HashMap, dead: &mut HashMap>, 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), + } +} diff --git a/document/graph-storage/src/registry.rs b/document/graph-storage/src/registry.rs index 4267a40f17..2ca35ef518 100644 --- a/document/graph-storage/src/registry.rs +++ b/document/graph-storage/src/registry.rs @@ -44,11 +44,13 @@ pub struct Tombstone { 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)) } diff --git a/document/graph-storage/src/resources.rs b/document/graph-storage/src/resources.rs index 8033c3328d..2f65d80a20 100644 --- a/document/graph-storage/src/resources.rs +++ b/document/graph-storage/src/resources.rs @@ -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 { diff --git a/document/graph-storage/src/session.rs b/document/graph-storage/src/session.rs index 9a5112a53a..b387e74c1a 100644 --- a/document/graph-storage/src/session.rs +++ b/document/graph-storage/src/session.rs @@ -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) -> Result, CrdtError> { + self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new()))) + } + + fn stage_ops_with(&mut self, ops: impl IntoIterator) -> Result, CrdtError> { // A batch is staged whole or not at all. - let mut pending: Vec = 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, 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 { + let mut by_author: HashMap> = 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 { 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, CrdtError> { let wanted: HashSet = ids.iter().copied().collect(); let (drained, kept): (Vec, Vec) = 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 { - 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 { + 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 { - 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, + /// 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)] diff --git a/document/graph-storage/src/tests/bookkeeping.rs b/document/graph-storage/src/tests/bookkeeping.rs index f8a86dc7bf..176223a965 100644 --- a/document/graph-storage/src/tests/bookkeeping.rs +++ b/document/graph-storage/src/tests/bookkeeping.rs @@ -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 +} diff --git a/document/graph-storage/src/tests/crdt.rs b/document/graph-storage/src/tests/crdt.rs index 518078736b..4121e3c515 100644 --- a/document/graph-storage/src/tests/crdt.rs +++ b/document/graph-storage/src/tests/crdt.rs @@ -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::>()); + let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::>(), 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 = 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:?}" + ); } } } diff --git a/document/graph-storage/src/tests/round_trip.rs b/document/graph-storage/src/tests/round_trip.rs index be511b4c3b..3d2540082b 100644 --- a/document/graph-storage/src/tests/round_trip.rs +++ b/document/graph-storage/src/tests/round_trip.rs @@ -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, diff --git a/document/graph-storage/src/to_runtime.rs b/document/graph-storage/src/to_runtime.rs index 00fbfb6a7a..b4f121232c 100644 --- a/document/graph-storage/src/to_runtime.rs +++ b/document/graph-storage/src/to_runtime.rs @@ -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(), }) } diff --git a/editor/Cargo.toml b/editor/Cargo.toml index 4806931fc9..ef03f79c11 100644 --- a/editor/Cargo.toml +++ b/editor/Cargo.toml @@ -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 } diff --git a/editor/src/application.rs b/editor/src/application.rs index cd2f2c3f41..3d60214569 100644 --- a/editor/src/application.rs +++ b/editor/src/application.rs @@ -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, - document_store: Arc, - 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>(&mut self, message: T) -> Vec { self.dispatcher.handle_message(message, true); std::mem::take(&mut self.dispatcher.responses) } - - pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque) -> Result<(), String> { - self.dispatcher.poll_node_graph_evaluation(responses) - } -} - -static ENVIRONMENT: OnceLock = 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 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"); diff --git a/editor/src/builder.rs b/editor/src/builder.rs new file mode 100644 index 0000000000..f3bb6fe513 --- /dev/null +++ b/editor/src/builder.rs @@ -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, Arc>; +pub type ReadyRuntimeBuilder = RuntimeBuilder; + +pub struct Builder { + 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 Builder<(), R, S, N> { + pub fn with_editor(self, editor: ReadyEditorBuilder) -> Builder { + Builder { + editor, + runtime: self.runtime, + spawner: self.spawner, + random_seed: self.random_seed, + } + } +} + +impl Builder { + pub fn with_runtime(self, runtime: ReadyRuntimeBuilder) -> Builder { + Builder { + editor: self.editor, + runtime, + spawner: self.spawner, + random_seed: self.random_seed, + } + } +} + +impl Builder { + pub fn with_spawner(self, spawner: impl Spawn + Send + Sync + 'static) -> Builder { + Builder { + editor: self.editor, + runtime: self.runtime, + spawner: Arc::new(spawner), + random_seed: self.random_seed, + } + } +} + +impl Builder { + pub fn with_random_seed(self, random_seed: u64) -> Builder { + Builder { + editor: self.editor, + runtime: self.runtime, + spawner: self.spawner, + random_seed, + } + } +} + +impl Builder { + 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 { + 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 EditorBuilder<(), E, R, D> { + pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> EditorBuilder { + EditorBuilder { + wake: Arc::new(wake), + environment: self.environment, + resource_storage: self.resource_storage, + document_store: self.document_store, + } + } +} + +impl EditorBuilder { + pub fn with_environment(self, environment: Environment) -> EditorBuilder { + EditorBuilder { + wake: self.wake, + environment, + resource_storage: self.resource_storage, + document_store: self.document_store, + } + } +} + +impl EditorBuilder { + pub fn with_resource_storage(self, resource_storage: Arc) -> EditorBuilder, D> { + EditorBuilder { + wake: self.wake, + environment: self.environment, + resource_storage, + document_store: self.document_store, + } + } +} + +impl EditorBuilder { + pub fn with_document_store(self, document_store: Arc) -> EditorBuilder> { + EditorBuilder { + wake: self.wake, + environment: self.environment, + resource_storage: self.resource_storage, + document_store, + } + } +} + +pub struct RuntimeBuilder { + 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 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 { + RuntimeBuilder { + wake: Arc::new(wake), + application_io: self.application_io, + } + } +} + +impl RuntimeBuilder { + pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder { + RuntimeBuilder { wake: self.wake, application_io } + } +} diff --git a/editor/src/consts.rs b/editor/src/consts.rs index 9a510bb805..e69fb64499 100644 --- a/editor/src/consts.rs +++ b/editor/src/consts.rs @@ -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; diff --git a/editor/src/dispatcher.rs b/editor/src/dispatcher.rs index 9a257a9d6d..991d347b19 100644 --- a/editor/src/dispatcher.rs +++ b/editor/src/dispatcher.rs @@ -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>, pub responses: Vec, pub frontend_update_messages: Vec, 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) -> Self { + fn new(environment: Environment, executor: NodeGraphExecutor, document_store: Arc, 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, document_store: Arc) -> Self { - let mut s = Self::default(); + pub fn new( + environment: Environment, + resource_storage: Arc, + document_store: Arc, + 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>(&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) -> 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]) -> String { String::from_iter(queues.iter().enumerate().skip(1).map(|(index, queue)| { diff --git a/editor/src/lib.rs b/editor/src/lib.rs index 56e89e7f4e..1a1cb35c32 100644 --- a/editor/src/lib.rs +++ b/editor/src/lib.rs @@ -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; diff --git a/editor/src/messages/app_window/app_window_message_handler.rs b/editor/src/messages/app_window/app_window_message_handler.rs index e09ad3c19c..dee5f8ea69 100644 --- a/editor/src/messages/app_window/app_window_message_handler.rs +++ b/editor/src/messages/app_window/app_window_message_handler.rs @@ -86,8 +86,8 @@ pub enum AppWindowPlatform { Linux, } -impl From<&Environment> for AppWindowPlatform { - fn from(environment: &Environment) -> Self { +impl From for AppWindowPlatform { + fn from(environment: Environment) -> Self { match (environment.platform, environment.host) { (Platform::Web, _) => AppWindowPlatform::Web, (Platform::Desktop, Host::Linux) => AppWindowPlatform::Linux, diff --git a/editor/src/messages/clipboard/clipboard_message_handler.rs b/editor/src/messages/clipboard/clipboard_message_handler.rs index 333af93eff..5f59efca86 100644 --- a/editor/src/messages/clipboard/clipboard_message_handler.rs +++ b/editor/src/messages/clipboard/clipboard_message_handler.rs @@ -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> 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::>(); + + let copies = chain_nodes_with_dots .iter() .filter_map(|node_id| active_document.network_interface.copy_chain_node(node_id, &[])) .collect::>(); @@ -434,18 +439,27 @@ impl MessageHandler> 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> 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 { Some(HandleId { ty: handle.ty, diff --git a/editor/src/messages/clipboard/utility_types.rs b/editor/src/messages/clipboard/utility_types.rs index 421215d111..fb8689d992 100644 --- a/editor/src/messages/clipboard/utility_types.rs +++ b/editor/src/messages/clipboard/utility_types.rs @@ -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, 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)] diff --git a/editor/src/messages/frontend/frontend_message.rs b/editor/src/messages/frontend/frontend_message.rs index 2ea0dd74c5..3c2be4dd2c 100644 --- a/editor/src/messages/frontend/frontend_message.rs +++ b/editor/src/messages/frontend/frontend_message.rs @@ -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, }, + /// 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, @@ -246,6 +260,9 @@ pub enum FrontendMessage { UpdateDocumentArtwork { svg: String, }, + UpdateRenderStatus { + status: RenderStatus, + }, UpdateImageData { image_data: Vec, }, @@ -291,8 +308,8 @@ pub enum FrontendMessage { UpdateNodeGraphNodes { nodes: Vec, }, - UpdateNodeGraphErrorDiagnostic { - error: Option, + UpdateNodeGraphErrorDiagnostics { + errors: Vec, }, UpdateVisibleNodes { nodes: Vec, @@ -312,6 +329,9 @@ pub enum FrontendMessage { id: NodeId, value: String, }, + ClearNodeThumbnails { + ids: Vec, + }, UpdateOpenDocumentsList { #[serde(rename = "openDocuments")] open_documents: Vec, @@ -319,6 +339,12 @@ pub enum FrontendMessage { UpdateWirePathInProgress { #[serde(rename = "wirePath")] wire_path: Option, + /// 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, diff --git a/editor/src/messages/frontend/utility_types.rs b/editor/src/messages/frontend/utility_types.rs index 27e2791ac8..37ad351ee2 100644 --- a/editor/src/messages/frontend/utility_types.rs +++ b/editor/src/messages/frontend/utility_types.rs @@ -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 { diff --git a/editor/src/messages/future/future_message.rs b/editor/src/messages/future/future_message.rs index 99ccb6052e..612e371314 100644 --- a/editor/src/messages/future/future_message.rs +++ b/editor/src/messages/future/future_message.rs @@ -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, } diff --git a/editor/src/messages/future/future_message_handler.rs b/editor/src/messages/future/future_message_handler.rs index 10731e65ef..cc766c2aa9 100644 --- a/editor/src/messages/future/future_message_handler.rs +++ b/editor/src/messages/future/future_message_handler.rs @@ -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 + Send + 'static>>; #[cfg(target_family = "wasm")] type InnerMessageFuture = Pin + '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; -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, wake: Wake); -} - -#[derive(ExtractField)] -pub struct FutureMessageContext {} - #[derive(ExtractField)] pub struct FutureMessageHandler { - #[cfg_attr(test, expect(dead_code))] - spawner: Arc, + spawner: Spawner, wake: Wake, - #[cfg_attr(test, expect(dead_code))] results_sender: UnboundedSender, results_receiver: UnboundedReceiver, } 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) { - 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 for FutureMessageHandler { - fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque, _context: FutureMessageContext) { +impl MessageHandler for FutureMessageHandler { + fn process_message(&mut self, message: FutureMessage, responses: &mut VecDeque, _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 { - Arc::new(TokioSpawner::default()) -} - -#[cfg(target_family = "wasm")] -fn default_spawner() -> Arc { - 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, -} - -#[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, 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, wake: Wake) { - wasm_bindgen_futures::spawn_local(async move { - let message = future.await; - let _ = results.unbounded_send(message); - wake(); - }); - } -} diff --git a/editor/src/messages/future/mod.rs b/editor/src/messages/future/mod.rs index 912d28c29f..8767de3b6f 100644 --- a/editor/src/messages/future/mod.rs +++ b/editor/src/messages/future/mod.rs @@ -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}; diff --git a/editor/src/messages/input_mapper/input_mapper_message_handler.rs b/editor/src/messages/input_mapper/input_mapper_message_handler.rs index 145b75d073..be58b44e63 100644 --- a/editor/src/messages/input_mapper/input_mapper_message_handler.rs +++ b/editor/src/messages/input_mapper/input_mapper_message_handler.rs @@ -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> 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 { + pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant, environment: Environment) -> Option { 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) diff --git a/editor/src/messages/input_mapper/input_mappings.rs b/editor/src/messages/input_mapper/input_mappings.rs index 2bdb1eb6eb..eecf69e0b7 100644 --- a/editor/src/messages/input_mapper/input_mappings.rs +++ b/editor/src/messages/input_mapper/input_mappings.rs @@ -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 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 }), diff --git a/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs b/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs index 5f70b8df7d..02511b1061 100644 --- a/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs +++ b/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs @@ -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> for KeyMappingMessageHandler { fn process_message(&mut self, message: KeyMappingMessage, responses: &mut VecDeque, 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 { - 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 { + self.mapping_handler.action_input_mapping(action_to_find, environment) } } diff --git a/editor/src/messages/input_mapper/utility_types/keyboard.rs b/editor/src/messages/input_mapper/utility_types/keyboard.rs index 041edb4ca0..1f9e66c2a5 100644 --- a/editor/src/messages/input_mapper/utility_types/keyboard.rs +++ b/editor/src/messages/input_mapper/utility_types/keyboard.rs @@ -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::()); } - 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); -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::(); - - // 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 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 for LabeledKeyOrMouseMotion { #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct LabeledShortcut(pub Vec); -impl From 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()) } } diff --git a/editor/src/messages/input_mapper/utility_types/macros.rs b/editor/src/messages/input_mapper/utility_types/macros.rs index 2d0a5d6cf5..ec5767eeb9 100644 --- a/editor/src/messages/input_mapper/utility_types/macros.rs +++ b/editor/src/messages/input_mapper/utility_types/macros.rs @@ -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),*]), )) }; } diff --git a/editor/src/messages/input_mapper/utility_types/misc.rs b/editor/src/messages/input_mapper/utility_types/misc.rs index 8dcf77369f..6ffda83d1d 100644 --- a/editor/src/messages/input_mapper/utility_types/misc.rs +++ b/editor/src/messages/input_mapper/utility_types/misc.rs @@ -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 { 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) { - 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, 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)); } } diff --git a/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs b/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs index 14a5526a94..ca3fe9fbbc 100644 --- a/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs +++ b/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs @@ -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> for InputPreprocessorMessageHandler { fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque, 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 { - 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 { - 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 { 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 { - 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 { 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 { - 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 { 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 f64 { + self.pointer_down_time + } + fn translate_mouse_event(&mut self, mut new_state: PointerState, allow_first_button_down: bool, responses: &mut VecDeque) { 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) { + fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, environment: Environment, responses: &mut VecDeque) { 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(), }, ); diff --git a/editor/src/messages/layout/layout_message_handler.rs b/editor/src/messages/layout/layout_message_handler.rs index afd26eda4b..0b5c530dcb 100644 --- a/editor/src/messages/layout/layout_message_handler.rs +++ b/editor/src/messages/layout/layout_message_handler.rs @@ -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, } @@ -23,6 +25,7 @@ pub struct LayoutMessageHandler { #[message_handler_data] impl MessageHandler> for LayoutMessageHandler { fn process_message(&mut self, message: LayoutMessage, responses: &mut std::collections::VecDeque, context: LayoutMessageContext) { + let environment = context.environment; let action_input_mapping = &context.action_input_mapping; match message { @@ -36,7 +39,7 @@ impl MessageHandler> 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> 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, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, + 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, layout_target: LayoutTarget, responses: &mut VecDeque, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option) { - diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping)); + fn send_diff( + &self, + mut diff: Vec, + layout_target: LayoutTarget, + responses: &mut VecDeque, + action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, + 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"); diff --git a/editor/src/messages/layout/utility_types/layout_widget.rs b/editor/src/messages/layout/utility_types/layout_widget.rs index 549cb4628d..c964448106 100644 --- a/editor/src/messages/layout/utility_types/layout_widget.rs +++ b/editor/src/messages/layout/utility_types/layout_widget.rs @@ -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, - /// 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, + /// 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) { + pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, 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) { + fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, 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), + } } } diff --git a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs index de110754aa..7c237b0936 100644 --- a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs @@ -331,7 +331,7 @@ pub struct NodeCatalog { // Behavior #[serde(rename = "initialSearchTerm")] - pub intial_search: String, + pub initial_search: String, // Callbacks #[serde(skip)] diff --git a/editor/src/messages/message.rs b/editor/src/messages/message.rs index e3e3e6ec3a..2233f05be9 100644 --- a/editor/src/messages/message.rs +++ b/editor/src/messages/message.rs @@ -47,6 +47,7 @@ pub enum Message { Viewport(ViewportMessage), // Messages + Wake, Batched { messages: Box<[Message]>, }, diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs index 9efc67eba8..1fdd7f506f 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs @@ -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, -} diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs index 4f0c0145a6..3c88e38faf 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs @@ -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, introspected_data: Option>, element_path: Vec, - active_vector_table_tab: VectorTableTab, } #[message_handler_data] @@ -67,7 +65,6 @@ impl MessageHandler> 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> 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, - vector_table_tab: VectorTableTab, } macro_rules! generate_layout_downcast { @@ -219,7 +209,8 @@ fn generate_layout(introspected_data: &Arc, List, List, - List, + List, + List, List, List, List, @@ -273,7 +264,8 @@ fn generate_layout(introspected_data: &Arc, Item, Item, - Item, + Item, + Item, Item, Item, Item, @@ -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 { - 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 { + 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 { + 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 { vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), data))] @@ -1151,6 +1115,7 @@ macro_rules! known_item_types { List, List, List, + List, List>, List>, List, @@ -1170,6 +1135,8 @@ macro_rules! known_item_types { bool, String, Vector, + Path, + BezPath, Raster, Raster, 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 { if let Some(value) = any.downcast_ref::() { return Some(value.to_string()); } + if let Some(value) = any.downcast_ref::() { + return Some(if *value == PointId::UNNAMED { String::new() } else { value.inner().to_string() }); + } + if let Some(value) = any.downcast_ref::() { + return Some(if *value == SegmentId::ZERO { String::new() } else { value.inner().to_string() }); + } + if let Some(value) = any.downcast_ref::() { + return Some(value.to_string()); + } None } diff --git a/editor/src/messages/portfolio/document/document_diff.rs b/editor/src/messages/portfolio/document/document_diff.rs index a128a975d3..3f5f2938b4 100644 --- a/editor/src/messages/portfolio/document/document_diff.rs +++ b/editor/src/messages/portfolio/document/document_diff.rs @@ -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):"); diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index 71e6f041cb..7ef1d4eef9 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -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, }, + /// 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, + layers_missing_details: Vec, + }, 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, }, - UpdateVectorData { - vector_data: HashMap>, - }, // `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>>, + }, #[serde(skip)] UpdateAppearanceAttributes { appearance_attributes: HashMap>, diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 33b8ab8f2a..775760b91f 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -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, + /// 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> for DocumentMes fn process_message(&mut self, message: DocumentMessage, responses: &mut VecDeque, context: DocumentMessageContext) { let DocumentMessageContext { document_id, + environment, ipp, executor, viewport, @@ -263,6 +270,7 @@ impl MessageHandler> 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> 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> 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> 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> 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> 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::>(); + 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> 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> 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> 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> 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) -> Option { // 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) -> Option { // 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::>(); + // 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] diff --git a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs index d5eb57eedc..68860a640c 100644 --- a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs +++ b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs @@ -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, diff --git a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs index 297b8763ab..e03e9745d3 100644 --- a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs +++ b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs @@ -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> for NavigationMessageHandler { fn process_message(&mut self, message: NavigationMessage, responses: &mut VecDeque, context: NavigationMessageContext) { let NavigationMessageContext { + environment, network_interface, breadcrumb_network_path, ipp, @@ -189,7 +191,7 @@ impl MessageHandler> 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> 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, .. }) { diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index 437e329de7..604695e0a7 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -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 { 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)] diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs index 0a6c87069c..b3d7021c6f 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs @@ -42,7 +42,6 @@ pub(super) fn post_process_nodes(custom: Vec) -> HashMap fields, description, inspector, - context_features, output_fields, .. } = metadata; @@ -90,7 +89,6 @@ pub(super) fn post_process_nodes(custom: Vec) -> 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() diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs index c418323ec1..be24bc17c2 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs @@ -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, + }, 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, }, 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, + }, UpdateNewNodeGraph, UpdateTypes { #[serde(skip)] @@ -301,6 +339,9 @@ pub enum NodeGraphMessage { #[serde(skip)] node_graph_errors: GraphErrors, }, + UpdateEvaluationErrors { + errors: Vec, + }, UpdateActionButtons, UpdateGraphBarRight, UpdateInSelectedNetwork, diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs index 9da6c7da2f..5d765a73f3 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs @@ -1,18 +1,17 @@ use super::node_inspector; use super::utility_types::{BoxSelection, ContextMenuInformation, DragStart, FrontendNode}; -use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; +use crate::consts::{DOUBLE_CLICK_ALLOWED_TRAVEL, DOUBLE_CLICK_MILLISECONDS, GRID_SIZE, NODE_GLIDE_TIME_CONSTANT_MILLISECONDS, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual}; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::document_message_handler::navigation_controls; use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext; -use crate::messages::portfolio::document::node_graph::document_node_definitions::{ - DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type, -}; -use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic}; +use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type}; +use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic}; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; +use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::network_interface::{ - self, FlowType, ImportOrExport, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionCheckpoint, type_feeds_connector, + self, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionCheckpoint, }; use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry}; use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire}; @@ -44,6 +43,7 @@ pub struct NodeGraphMessageContext<'a> { pub inspector_collapsed_sections: &'a mut Vec, pub inspector_expanded_input_chains: &'a mut Vec<(NodeId, Option)>, pub layers_panel_expanded_chains: &'a mut Vec, + pub layers_in_view: &'a mut LayersInView, pub ipp: &'a InputPreprocessorMessageHandler, pub graph_view_overlay_open: bool, pub graph_fade_artwork_percentage: f64, @@ -62,15 +62,26 @@ pub struct NodeGraphMessageHandler { widgets: [LayoutGroup; 2], /// Used to add a transaction for the first node move when dragging. begin_dragging: bool, - /// Track if nodes were duplicated during the current drag via Alt-drag. - pub duplicated_in_drag: bool, - /// Used to prevent entering a nested network if the node is dragged after double clicking + /// Whether the current drag added the nodes it drags, as duplicates from an Alt-drag or as a redirect dot from a double-press, which shaking keeps rather than undoing to before the drag. + pub nodes_added_in_drag: bool, + /// Whether the current press has moved a node to another grid cell, in which case the double-click it ends does nothing. node_has_moved_in_drag: bool, + /// The latest press of the left mouse button, which tells whether the next press is the second of a double-click as soon as it lands. + latest_left_press: Option, + /// Whether the current press, as the second of a double-click, already used it to add a redirect dot or to start dragging one out of a connector, + /// so the double-click arriving after its release does nothing more, even if no dot was dragged out. + double_click_used_by_press: bool, + /// The connector a double-press is dragging a redirect dot out of, with where the press began in node graph space, until the pointer moves far enough to place the dot. + pub dot_drag_out: Option<(DotDragOutSource, DVec2)>, /// If dragging the selected nodes, this stores the starting position both in viewport and node graph coordinates, /// plus a flag indicating if it has been dragged since the mousedown began. pub drag_start: Option<(DragStart, bool)>, // Store the selected chain nodes on drag start so they can be reconnected if shaken pub drag_start_chain_nodes: Vec, + /// The wire a dragged node would be inserted onto if dropped now, which the frontend shows undimmed. + wire_insertion_preview: Option, + /// The center of the connector a press at the pointer would grab, in node graph space, which the frontend shows hovered. + hovered_connector: Option, /// If dragging the background to create a box selection, this stores its starting point in node graph coordinates, /// plus a flag indicating if it has been dragged since the mousedown began. pub box_selection_start: Option<(DVec2, bool)>, @@ -100,6 +111,12 @@ pub struct NodeGraphMessageHandler { wire_expanded_node: Option<(NodeId, Vec, TransactionCheckpoint)>, /// Whether [`NodeGraphMessage::WireHoverTick`] is subscribed to animation frames. wire_hover_tick_subscribed: bool, + /// The network with whatever is gliding into the place it moved to, which keeps its own glide offsets. + glide_network_path: Vec, + /// When the gliding nodes were last brought closer to their grid cells, in milliseconds, once an animation frame has arrived. + glide_last_tick_time: Option, + /// Whether [`NodeGraphMessage::GlideTick`] is subscribed to animation frames. + glide_tick_subscribed: bool, /// State for the context menus. pub context_menu: Option, /// Index of selected node to be deselected on pointer up when shift clicking an already selected node @@ -118,6 +135,7 @@ pub struct NodeGraphMessageHandler { frontend_nodes: Vec, /// Used to keep track of what wires are sent to the front end so the old ones can be removed frontend_wires: HashSet<(NodeId, usize)>, + evaluation_errors: Vec, } /// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network. @@ -133,6 +151,7 @@ impl<'a> MessageHandler> for NodeG inspector_collapsed_sections, inspector_expanded_input_chains, layers_panel_expanded_chains, + layers_in_view, ipp, graph_view_overlay_open, graph_fade_artwork_percentage, @@ -205,45 +224,6 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::SendGraph); } - NodeGraphMessage::AddImportPassthrough { import_index } => { - let import = OutputConnector::Import(import_index); - let Some(import_position) = network_interface.output_position(&import, breadcrumb_network_path) else { - log::error!("Could not get the position of import {import_index} in AddImportPassthrough"); - return; - }; - let Some(passthrough_definition) = resolve_proto_node_type(graphene_core::ops::passthrough::IDENTIFIER) else { - log::error!("Could not resolve the Passthrough node in AddImportPassthrough"); - return; - }; - let fed_inputs = network_interface - .outward_wires(breadcrumb_network_path) - .and_then(|outward_wires| outward_wires.get(&import).cloned()) - .unwrap_or_default(); - - // Two grid cells right of the import, with the node's primary input (a row below its top) level with it - let node_id = NodeId::new(); - let node_template = Box::new(passthrough_definition.default_node_template()); - responses.add(NodeGraphMessage::InsertNode { node_id, node_template }); - responses.add(NodeGraphMessage::ShiftNodePosition { - node_id, - x: (import_position.x / GRID_SIZE as f64).round() as i32 + 2, - y: (import_position.y / GRID_SIZE as f64).round() as i32 - 1, - }); - - responses.add(NodeGraphMessage::CreateWire { - output_connector: import, - input_connector: InputConnector::primary_input(node_id), - }); - for fed_input in fed_inputs { - responses.add(NodeGraphMessage::CreateWire { - output_connector: OutputConnector::primary_output(node_id), - input_connector: fed_input, - }); - } - - responses.add(NodeGraphMessage::SendGraph); - responses.add(NodeGraphMessage::RunDocumentGraph); - } NodeGraphMessage::AddExport => { network_interface.add_export(graph_craft::document::value::TaggedValue::None, -1, "", breadcrumb_network_path); responses.add(NodeGraphMessage::SendGraph); @@ -308,39 +288,11 @@ impl<'a> MessageHandler> for NodeG responses.add(PortfolioMessage::SubmitActiveGraphRender); } NodeGraphMessage::CreateWire { output_connector, input_connector } => { - // TODO: Add support for flattening NodeInput::Import exports in flatten_with_fns https://github.com/GraphiteEditor/Graphite/issues/1762 - if let (InputConnector::Export(_), OutputConnector::Import(_)) = (input_connector, output_connector) { - let mid_point = (network_interface.get_output_center(&output_connector, breadcrumb_network_path).unwrap() - + network_interface.get_input_center(&input_connector, breadcrumb_network_path).unwrap()) - / 2.; - let Some(passthrough_definition) = resolve_proto_node_type(graphene_core::ops::passthrough::IDENTIFIER) else { - log::error!("Could not resolve passthrough node when wiring an export to an import"); - return; - }; - let node_template = Box::new(passthrough_definition.default_node_template()); - - let node_id = NodeId::new(); - responses.add(NodeGraphMessage::InsertNode { node_id, node_template }); - responses.add(NodeGraphMessage::ShiftNodePosition { - node_id, - x: (mid_point.x / 24.) as i32, - y: (mid_point.y / 24.) as i32, - }); - let node_input_connector = InputConnector::primary_input(node_id); - let node_output_connector = OutputConnector::primary_output(node_id); - responses.add(NodeGraphMessage::CreateWire { - output_connector, - input_connector: node_input_connector, - }); - responses.add(NodeGraphMessage::CreateWire { - output_connector: node_output_connector, - input_connector, - }); - - return; - } network_interface.create_wire(&output_connector, &input_connector, selection_network_path); } + NodeGraphMessage::CreateWires { output_connector, input_connectors } => { + network_interface.create_wires(&output_connector, &input_connectors, selection_network_path); + } // Copies and cuts the same way as anywhere else NodeGraphMessage::Copy => responses.add(ClipboardMessage::CopyLayers), NodeGraphMessage::CreateNodeInLayerNoTransaction { node_type, layer } => { @@ -420,6 +372,15 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::RunDocumentGraph); } } + // A wire dragged out of a dimmed connector for adding an import adds that import, wired to the new node's first exposed input + else if let Some(import_index) = self.wire_in_progress_from_new_import { + if let Some((input_index, _)) = node_template.inputs.iter().enumerate().find(|(_, input)| input.is_exposed()) { + responses.add(NodeGraphMessage::AddImportAndConnect { + import_index, + input_connector: InputConnector::node_at_index(node_id, input_index), + }); + } + } // Only auto connect to the dragged wire if the node is being added to the currently opened network else if let Some(output_connector_position) = self.wire_in_progress_from_connector { let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else { @@ -497,7 +458,12 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::SendGraph); } + NodeGraphMessage::RemoveOrphanedDots => { + network_interface.remove_orphaned_dots(selection_network_path); + responses.add(NodeGraphMessage::SendGraph); + } NodeGraphMessage::DisconnectInput { input_connector } => { + // The operation this is a step of removes any dots it orphans once it's done network_interface.disconnect_input(&input_connector, selection_network_path); } NodeGraphMessage::DisconnectImportExport { index } => { @@ -511,6 +477,7 @@ impl<'a> MessageHandler> for NodeG } ImportOrExport::Export(export_index) => network_interface.disconnect_input(&InputConnector::Export(export_index), breadcrumb_network_path), } + network_interface.remove_orphaned_dots(breadcrumb_network_path); responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::RunDocumentGraph); @@ -524,14 +491,28 @@ impl<'a> MessageHandler> for NodeG // Duplicates in the flow like everywhere else NodeGraphMessage::DuplicateSelectedNodes => responses.add(DocumentMessage::DuplicateSelectedLayers), NodeGraphMessage::EnterNestedNetwork => { - // Do not enter the nested network if the node was dragged - if self.node_has_moved_in_drag { + // Nothing more happens if the second press dragged a node, or already used the double-click to add a dot or drag one out of a connector + if self.node_has_moved_in_drag || self.double_click_used_by_press { return; } let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, selection_network_path) else { return; }; + + // Double-clicking a redirect dot dissolves it, so the wires it bent run straight from what fed it + if network_interface.is_redirect_dot(&node_id, selection_network_path) { + responses.add(DocumentMessage::AddTransaction); + responses.add(NodeGraphMessage::DeleteNodes { + node_ids: vec![node_id], + delete_children: false, + }); + responses.add(NodeGraphMessage::RunDocumentGraph); + responses.add(NodeGraphMessage::SelectedNodesUpdated); + responses.add(NodeGraphMessage::SendGraph); + return; + } + if network_interface .layer_click_target_from_click(ipp.mouse.position, network_interface::LayerClickTargetTypes::Visibility, selection_network_path) .is_some() @@ -595,6 +576,8 @@ impl<'a> MessageHandler> for NodeG input_connector: InputConnector::node_at_index(node_id, input_index), input: node_input, }); + // Hiding an input takes away the wire it was fed by, along with any dot it ran through + responses.add(NodeGraphMessage::RemoveOrphanedDots); // Finish the history step responses.add(DocumentMessage::CommitTransaction); @@ -634,8 +617,12 @@ impl<'a> MessageHandler> for NodeG network_interface.disconnect_import_wires(0, breadcrumb_network_path); } + network_interface.remove_orphaned_dots(network_path); + network_interface.remove_orphaned_dots(breadcrumb_network_path); + responses.add(NodeGraphMessage::UpdateImportsExports); responses.add(NodeGraphMessage::SendWires); + responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::RunDocumentGraph); } NodeGraphMessage::ExposePrimaryExport { exposed } => { @@ -657,9 +644,12 @@ impl<'a> MessageHandler> for NodeG // Disconnect all connections in the encapsulating network if let Some((encapsulating_node, encapsulating_path)) = breadcrumb_network_path.split_last() { network_interface.disconnect_output_wires(&OutputConnector::primary_output(*encapsulating_node), encapsulating_path); + network_interface.remove_orphaned_dots(encapsulating_path); } + network_interface.remove_orphaned_dots(breadcrumb_network_path); responses.add(NodeGraphMessage::UpdateImportsExports); + responses.add(NodeGraphMessage::SendGraph); } NodeGraphMessage::InsertNode { node_id, node_template } => { network_interface.insert_node(node_id, *node_template, selection_network_path); @@ -671,13 +661,27 @@ impl<'a> MessageHandler> for NodeG } => { network_interface.insert_node_between(&node_id, &input_connector, insert_node_input_index, selection_network_path); } + NodeGraphMessage::InsertDotOnWire { node_id, input_connector, x, y } => { + network_interface.insert_dot_on_wire(node_id, &input_connector, IVec2::new(x, y), selection_network_path); + responses.add(NodeGraphMessage::RunDocumentGraph); + responses.add(NodeGraphMessage::SendGraph); + } + NodeGraphMessage::InsertDotOnOutput { node_id, output_connector, x, y } => { + network_interface.insert_dot_on_output(node_id, &output_connector, IVec2::new(x, y), selection_network_path); + responses.add(NodeGraphMessage::RunDocumentGraph); + responses.add(NodeGraphMessage::SendGraph); + } NodeGraphMessage::MergeSelectedNodes => { - let new_ids = network_interface - .selected_nodes_in_nested_network(breadcrumb_network_path) - .unwrap() - .selected_nodes() - .map(|id| (*id, *id)) - .collect::>(); + let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(breadcrumb_network_path) else { + log::error!("Could not get selected nodes in MergeSelectedNodes"); + return; + }; + // Redirect dots go in only along with the wires they bend between the nodes going in, as when copying + let selected_nodes = network_interface.selection_with_bridging_dots(selected_nodes.selected_nodes().copied().collect(), breadcrumb_network_path); + if selected_nodes.is_empty() { + return; + } + let new_ids = selected_nodes.iter().map(|id| (*id, *id)).collect::>(); let copied_nodes = network_interface.copy_nodes(&new_ids, breadcrumb_network_path).collect::>(); let selected_node_ids = copied_nodes.iter().map(|(node_id, _)| *node_id).collect::>(); @@ -689,10 +693,7 @@ impl<'a> MessageHandler> for NodeG let mut import_connections = Vec::new(); let mut export_connections = Vec::new(); // Scan current nodes top to bottom and find all inputs/outputs connected to nodes that are not in the copied nodes. These will represent the new imports and exports. - let Some(nodes_sorted_top_to_bottom) = network_interface.nodes_sorted_top_to_bottom( - network_interface.selected_nodes_in_nested_network(breadcrumb_network_path).unwrap().selected_nodes(), - breadcrumb_network_path, - ) else { + let Some(nodes_sorted_top_to_bottom) = network_interface.nodes_sorted_top_to_bottom(selected_nodes.iter(), breadcrumb_network_path) else { return; }; // Ensure that nodes can be grouped by checking if there is an unselected node between selected nodes @@ -799,6 +800,7 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta: -center_of_selected_nodes_grid_space - IVec2::new(2, 2), rubber_band: false, + glide: false, }); for (input_connector, import_index) in import_connections { @@ -861,6 +863,8 @@ impl<'a> MessageHandler> for NodeG None => loose_nodes.push(node_id), } } + // A copy in the flow is spliced into its original's wire, so a dot comes along only on a wire between loose copies + let loose_nodes = network_interface.selection_with_bridging_dots(loose_nodes, selection_network_path); // Nodes in no flow get copies offset from their originals, keeping the wires among them, and a layer brings its content along if !loose_nodes.is_empty() { @@ -938,22 +942,31 @@ impl<'a> MessageHandler> for NodeG } let clicked_id = network_interface.node_from_click(click, selection_network_path); - let clicked_input = network_interface.input_connector_from_click(click, selection_network_path); - let clicked_output = network_interface.output_connector_from_click(click, selection_network_path); + let clicked_input = network_interface.input_port_from_click(click, selection_network_path); + let clicked_output = network_interface.output_port_from_click(click, selection_network_path); let network_metadata = network_interface.network_metadata(selection_network_path).unwrap(); // Create the add node menu on right click, then exit if right_click { + // Pressing another button ends a run of clicks + self.latest_left_press = None; + // Abort dragging a node if self.drag_start.is_some() { self.drag_start = None; self.select_if_not_dragged = None; - self.duplicated_in_drag = false; + self.nodes_added_in_drag = false; + self.clear_wire_insertion_preview(responses); + self.stop_gliding(network_interface, responses); responses.add(DocumentMessage::AbortTransaction); responses.add(NodeGraphMessage::SelectedNodesSet { nodes: self.selection_before_pointer_down.clone(), }); return; } + // Abort dragging a dot out of a connector, before the dot has appeared + if self.dot_drag_out.take().is_some() { + return; + } // Abort a box selection if self.box_selection_start.is_some() { self.box_selection_start = None; @@ -1068,6 +1081,21 @@ impl<'a> MessageHandler> for NodeG return; } + // Every press starts out having moved no node and dragging no dot, wherever it lands + self.node_has_moved_in_drag = false; + self.dot_drag_out = None; + + // Whether this is the second press of a double-click, known as it lands rather than once the double-click arrives after its release + let press_time = ipp.pointer_down_time(); + let is_double_press = self.latest_left_press.is_some_and(|press| press.continued_by(press_time, click)); + self.latest_left_press = Some(LeftPress { + time: press_time, + position: click, + is_double: is_double_press, + is_click: false, + }); + self.double_click_used_by_press = false; + // Since the user is clicking elsewhere in the graph, ensure the context menu is closed if self.context_menu.is_some() { self.context_menu = None; @@ -1096,6 +1124,7 @@ impl<'a> MessageHandler> for NodeG self.wire_in_progress_from_connector = Some(connector_position); self.wire_in_progress_type = FrontendGraphDataType::General; self.wire_in_progress_from_new_import = Some(import_index); + Self::keep_pressed_connector_lit(Some(connector_position), responses); self.update_node_graph_hints(responses); return; @@ -1109,6 +1138,7 @@ impl<'a> MessageHandler> for NodeG self.wire_in_progress_to_connector = Some(connector_position); self.wire_in_progress_type = FrontendGraphDataType::General; self.wire_in_progress_from_new_export = Some(export_index); + Self::keep_pressed_connector_lit(Some(connector_position), responses); self.update_node_graph_hints(responses); return; @@ -1142,9 +1172,17 @@ impl<'a> MessageHandler> for NodeG self.preview_on_mouse_up = Some(clicked_node); } + // The second press of a double-click on a connector with wires drags a redirect dot out of it, once the pointer moves far enough to place the dot + if is_double_press && let Some(source) = Self::dot_drag_out_source(clicked_input, clicked_output, network_interface, selection_network_path) { + self.dot_drag_out = Some((source, node_graph_point)); + self.double_click_used_by_press = true; + return; + } + // Begin moving an existing wire, or drag a new one backward out of an empty input toward an output if let Some(clicked_input) = &clicked_input { responses.add(DocumentMessage::StartTransaction); + Self::keep_pressed_connector_lit(network_interface.input_position(clicked_input, breadcrumb_network_path), responses); let output_connector = if *clicked_input == InputConnector::Export(0) { network_interface.root_node(breadcrumb_network_path).map(|root_node| root_node.to_connector()) @@ -1165,6 +1203,7 @@ impl<'a> MessageHandler> for NodeG self.initial_disconnecting = true; self.disconnecting = Some(*clicked_input); + let output_connector = network_interface.output_past_sole_dots(output_connector, breadcrumb_network_path); self.wire_in_progress_from_connector = network_interface.output_position(&output_connector, breadcrumb_network_path); self.wire_in_progress_type = network_interface.output_type(&output_connector, breadcrumb_network_path).displayed_type(); @@ -1179,6 +1218,7 @@ impl<'a> MessageHandler> for NodeG self.wire_in_progress_from_connector = network_interface.output_position(&clicked_output, selection_network_path); let output_type = network_interface.output_type(&clicked_output, breadcrumb_network_path); self.wire_in_progress_type = output_type.displayed_type(); + Self::keep_pressed_connector_lit(self.wire_in_progress_from_connector, responses); self.update_node_graph_hints(responses); return; @@ -1240,8 +1280,7 @@ impl<'a> MessageHandler> for NodeG }) .collect::>(); self.begin_dragging = true; - self.node_has_moved_in_drag = false; - self.duplicated_in_drag = false; + self.nodes_added_in_drag = false; self.update_node_graph_hints(responses); } @@ -1255,6 +1294,23 @@ impl<'a> MessageHandler> for NodeG return; } + // The second press of a double-click on a wire splits it with a redirect dot, which the press goes on to drag + if is_double_press && let Some(input_connector) = Self::wire_at_point(node_graph_point, network_interface, preferences.graph_wire_style, selection_network_path) { + let dot = NodeId::new(); + let center = (node_graph_point / GRID_SIZE as f64).round().as_ivec2(); + + responses.add(DocumentMessage::StartTransaction); + responses.add(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector, + x: center.x, + y: center.y, + }); + self.drag_new_dot(dot, node_graph_point, IVec2::ZERO, responses); + self.double_click_used_by_press = true; + return; + } + // Clicked on the graph background so we box select if !shift_click && !alt_click { responses.add(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() }) @@ -1271,9 +1327,11 @@ impl<'a> MessageHandler> for NodeG return; }; - // Auto-panning - let messages = [NodeGraphMessage::PointerOutsideViewport { shift }.into(), NodeGraphMessage::PointerMove { shift }.into()]; - self.auto_panning.setup_by_mouse_position(ipp, viewport, &messages, responses); + // Auto-panning, only while dragging since hovering also moves the pointer here + if self.drag_start.is_some() || self.box_selection_start.is_some() || self.wire_in_progress_from_connector.is_some() { + let messages = [NodeGraphMessage::PointerOutsideViewport { shift }.into(), NodeGraphMessage::PointerMove { shift }.into()]; + self.auto_panning.setup_by_mouse_position(ipp, viewport, &messages, responses); + } let viewport_location = ipp.mouse.position; let point = network_metadata @@ -1283,17 +1341,45 @@ impl<'a> MessageHandler> for NodeG .inverse() .transform_point2(viewport_location); - if self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none() && self.wire_in_progress_is_backward() { + if let Some((source, press_point)) = self.dot_drag_out { + // The dot appears once the grid point nearest the pointer differs from where the press began, and is dragged on from there + let moved = ((point - press_point) / GRID_SIZE as f64).round().as_ivec2(); + if moved != IVec2::ZERO { + self.dot_drag_out = None; + + let dot = NodeId::new(); + let center = (press_point / GRID_SIZE as f64).round().as_ivec2() + moved; + let (x, y) = (center.x, center.y); + + responses.add(DocumentMessage::StartTransaction); + responses.add(match source { + DotDragOutSource::Output(output_connector) => NodeGraphMessage::InsertDotOnOutput { node_id: dot, output_connector, x, y }, + DotDragOutSource::Export(export_index) => NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::Export(export_index), + x, + y, + }, + }); + self.drag_new_dot(dot, press_point, moved, responses); + } + } else if self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none() && self.wire_in_progress_is_backward() { // A wire dragged backward keeps its input end in place and snaps its loose end to an output, or to a dimmed connector for adding an import let output_position = network_interface .output_connector_from_click(ipp.mouse.position, selection_network_path) .and_then(|output_connector| network_interface.output_position(&output_connector, selection_network_path)); let empty_import_position = || network_interface.empty_import_export_connector_at(point, true, selection_network_path).map(|(_, position)| position); - self.wire_in_progress_from_connector = Some(output_position.or_else(empty_import_position).unwrap_or(point)); + let snapped_position = output_position.or_else(empty_import_position); + self.wire_in_progress_from_connector = Some(snapped_position.unwrap_or(point)); - self.send_wire_in_progress(self.wire_in_progress_from_input, network_interface, selection_network_path, responses); + self.send_wire_in_progress(self.wire_in_progress_from_input, snapped_position.is_some(), network_interface, selection_network_path, responses); } else if self.wire_in_progress_from_connector.is_some() && self.context_menu.is_none() { let to_connector = network_interface.input_connector_from_click(ipp.mouse.position, selection_network_path); + let empty_export_position = to_connector + .is_none() + .then(|| network_interface.empty_import_export_connector_at(point, false, selection_network_path)) + .flatten() + .map(|(_, position)| position); if let Some(to_connector) = &to_connector { let Some(input_position) = network_interface.input_position(to_connector, selection_network_path) else { log::error!("Could not get input position for connector: {to_connector:?}"); @@ -1302,7 +1388,7 @@ impl<'a> MessageHandler> for NodeG self.wire_in_progress_to_connector = Some(input_position); } // Snap to a dimmed connector for adding an export, which a wire dropped on adds - else if let Some((_, empty_export_position)) = network_interface.empty_import_export_connector_at(point, false, selection_network_path) { + else if let Some(empty_export_position) = empty_export_position { self.wire_in_progress_to_connector = Some(empty_export_position); } // Not hovering over a node input or node output, update with the mouse position. @@ -1322,6 +1408,8 @@ impl<'a> MessageHandler> for NodeG } else { responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting }); } + // Picking up a wire from the end of a dot leaves that dot with nothing to redirect + responses.add(NodeGraphMessage::RemoveOrphanedDots); // Update the frontend that the node is disconnected responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::SendGraph); @@ -1329,7 +1417,8 @@ impl<'a> MessageHandler> for NodeG } } - self.send_wire_in_progress(to_connector, network_interface, selection_network_path, responses); + let loose_end_snapped = to_connector.is_some() || empty_export_position.is_some(); + self.send_wire_in_progress(to_connector, loose_end_snapped, network_interface, selection_network_path, responses); // Input connectors stick out past their node's edge, so hovering one counts as hovering its node let wire_hovered_node = to_connector @@ -1343,21 +1432,20 @@ impl<'a> MessageHandler> for NodeG *dragged = true; } - self.node_has_moved_in_drag = true; if self.begin_dragging { self.begin_dragging = false; - if ipp.keyboard.get(Key::Alt as usize) { - // Duplicate nodes inline within the existing PointerDown transaction. - // This means a completed Alt-drag is one undo step, and aborting (right-click / Escape) - // rolls back both the duplication and the move with a single plain AbortTransaction. - Self::duplicate_selected_nodes(network_interface, selection_network_path, responses); + // Duplicate nodes inline within the existing PointerDown transaction. + // This means a completed Alt-drag is one undo step, and aborting (right-click / Escape) + // rolls back both the duplication and the move with a single plain AbortTransaction. + if ipp.keyboard.get(Key::Alt as usize) && Self::duplicate_selected_nodes(network_interface, selection_network_path, responses) { // Duplicating sets a 2x2 offset, so shift the nodes back to the original position responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta: IVec2::new(-2, -2), rubber_band: false, + glide: false, }); self.preview_on_mouse_up = None; - self.duplicated_in_drag = true; + self.nodes_added_in_drag = true; } } @@ -1371,7 +1459,17 @@ impl<'a> MessageHandler> for NodeG graph_delta.x -= previous_round_x; graph_delta.y -= previous_round_y; - responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: true }); + responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { + graph_delta, + rubber_band: true, + glide: true, + }); + if graph_delta != IVec2::ZERO { + self.node_has_moved_in_drag = true; + + // Queued after the shift so it reads where the node has come to rest + responses.add(NodeGraphMessage::UpdateWireInsertionPreview); + } self.update_node_graph_hints(responses); } else if let Some((_, box_selection_dragged)) = &mut self.box_selection_start { @@ -1389,8 +1487,18 @@ impl<'a> MessageHandler> for NodeG } self.update_node_graph_hints(responses); } + + responses.add(NodeGraphMessage::UpdateHoveredConnector); } NodeGraphMessage::PointerUp => { + // A press released where it was made is a click, which a second press soon after can make a double-click + if let Some(press) = &mut self.latest_left_press { + press.is_click = press.position.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL; + } + + // A double-press released before the pointer moved far enough to drag a dot out of its connector leaves the wires as they were + self.dot_drag_out = None; + if selection_network_path != breadcrumb_network_path { log::error!("Selection network path does not match breadcrumb network path in PointerUp"); return; @@ -1471,14 +1579,23 @@ impl<'a> MessageHandler> for NodeG if let Some(import_index) = new_import_index { responses.add(NodeGraphMessage::AddImportAndConnect { import_index, input_connector }); - } else if let Some(output_connector) = output_connector { + } + // Dropped back on the input it was picked up from without ever leaving, the wire stays as it was, along with any dots it runs through + else if let Some(output_connector) = output_connector + && self.disconnecting != Some(input_connector) + { responses.add(NodeGraphMessage::CreateWire { output_connector, input_connector }); responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::SendGraph); } + + // Moving a wire off a dot can leave that dot with nothing to redirect + responses.add(NodeGraphMessage::RemoveOrphanedDots); } // With its loose end dropped elsewhere, the node creation menu opens for a node to wire it to, unless a backward wire was only clicked - else if !self.initial_disconnecting && (output_connector.is_some() || (backward && wire_in_progress_from_connector != wire_in_progress_to_connector)) { + else if !self.initial_disconnecting + && (output_connector.is_some() || new_import_index.is_some() || (backward && wire_in_progress_from_connector != wire_in_progress_to_connector)) + { // If the add node menu is already open, we don't want to open it again if self.context_menu.is_some() { return; @@ -1496,9 +1613,10 @@ impl<'a> MessageHandler> for NodeG // A forward wire offers the nodes taking its type, with the new node's input where it was dropped. // A backward wire offers every node, with the new node's output (on its right, five grid cells across) where it was dropped. // TODO: Filter both directions to the nodes that fit, decided in the backend with the conversion-aware type checks from https://github.com/GraphiteEditor/Graphite/pull/4688 - let (compatible_type, node_creation_point) = match output_connector { - Some(output_connector) if !backward => (network_interface.output_type(&output_connector, selection_network_path).add_node_string(), point), - _ => (None, point - DVec2::new((5 * GRID_SIZE) as f64, 0.)), + let (compatible_type, node_creation_point) = match (backward, output_connector) { + (false, Some(output_connector)) => (network_interface.output_type(&output_connector, selection_network_path).add_node_string(), point), + (false, None) => (None, point), + (true, _) => (None, point - DVec2::new((5 * GRID_SIZE) as f64, 0.)), }; self.context_menu = Some(ContextMenuInformation { @@ -1551,104 +1669,17 @@ impl<'a> MessageHandler> for NodeG } responses.add(NodeGraphMessage::SendGraph); - let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else { - log::error!("Could not get selected nodes in PointerUp"); - return; - }; // Check if a single node was dragged onto a wire and that the node was dragged onto the wire - if selected_nodes.selected_nodes_ref().len() == 1 && !self.begin_dragging { - let selected_node_id = selected_nodes.selected_nodes_ref()[0]; - let has_primary_output_connection = network_interface.outward_wires(selection_network_path).is_some_and(|outward_wires| { - outward_wires - .get(&OutputConnector::primary_output(selected_node_id)) - .is_some_and(|outward_wires| !outward_wires.is_empty()) + if !self.begin_dragging + && let Some((selected_node_id, insert_node_input_index, overlapping_wire)) = Self::wire_to_insert_on(network_interface, preferences.graph_wire_style, selection_network_path) + { + responses.add(NodeGraphMessage::InsertNodeBetween { + node_id: selected_node_id, + input_connector: overlapping_wire, + insert_node_input_index, }); - if !has_primary_output_connection { - let Some(network) = network_interface.nested_network(selection_network_path) else { - return; - }; - let Some(selected_node) = network.nodes.get(&selected_node_id) else { - return; - }; - // Check that the first visible input is disconnected - let selected_node_input_connect_index = selected_node - .inputs - .iter() - .enumerate() - .find(|input| input.1.is_exposed()) - .filter(|input| input.1.as_value().is_some()) - .map(|input| input.0); - if let Some(selected_node_input_connect_index) = selected_node_input_connect_index { - let Some(node_bbox) = network_interface.node_bounding_box(&selected_node_id, selection_network_path) else { - log::error!("Could not get bounding box for node: {selected_node_id}"); - return; - }; - let mut wires_to_check = network_interface.node_graph_input_connectors(selection_network_path).into_iter().collect::>(); - // Prevent inserting on a link that is connected upstream to the selected node - for upstream_node in network_interface.upstream_flow_back_from_nodes(vec![selected_node_id], selection_network_path, network_interface::FlowType::UpstreamFlow) { - for input_index in 0..network_interface.number_of_inputs(&upstream_node, selection_network_path) { - wires_to_check.remove(&InputConnector::node_at_index(upstream_node, input_index)); - } - } - - let overlapping_wires = wires_to_check - .into_iter() - .filter_map(|input| { - // Prevent inserting a layer into a chain - if network_interface.is_layer(&selected_node_id, selection_network_path) - && input.node_id().is_some_and(|input_node_id| network_interface.is_chain(&input_node_id, selection_network_path)) - { - return None; - } - - let (wire, _center_line, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?; - - let node_bbox = kurbo::Rect::new(node_bbox[0].x, node_bbox[0].y, node_bbox[1].x, node_bbox[1].y).to_path(DEFAULT_ACCURACY); - let inside = bezpath_is_inside_bezpath(&wire, &node_bbox, None, None); - - let intersect = wire - .segments() - .any(|segment| node_bbox.segments().filter_map(|segment| segment.as_line()).any(|line| !segment.intersect_line(line).is_empty())); - - (intersect || inside).then_some((input, is_stack)) - }) - .collect::>(); - - // Prioritize vertical thick lines and cancel if there are multiple potential wires - let mut node_wires = Vec::new(); - let mut stack_wires = Vec::new(); - for (overlapping_wire_input, is_stack) in overlapping_wires { - if is_stack { - stack_wires.push(overlapping_wire_input) - } else { - node_wires.push(overlapping_wire_input) - } - } - - let overlapping_wire = if network_interface.is_layer(&selected_node_id, selection_network_path) { - if stack_wires.len() == 1 { - stack_wires.first() - } else if stack_wires.is_empty() && node_wires.len() == 1 { - node_wires.first() - } else { - None - } - } else if node_wires.len() == 1 { - node_wires.first() - } else { - None - }; - if let Some(overlapping_wire) = overlapping_wire { - responses.add(NodeGraphMessage::InsertNodeBetween { - node_id: selected_node_id, - input_connector: *overlapping_wire, - insert_node_input_index: selected_node_input_connect_index, - }); - responses.add(NodeGraphMessage::RunDocumentGraph); - responses.add(NodeGraphMessage::SendGraph); - } - } - } + responses.add(NodeGraphMessage::RunDocumentGraph); + responses.add(NodeGraphMessage::SendGraph); } self.select_if_not_dragged = None; } @@ -1671,7 +1702,8 @@ impl<'a> MessageHandler> for NodeG self.drag_start = None; self.begin_dragging = false; - self.duplicated_in_drag = false; + self.nodes_added_in_drag = false; + self.clear_wire_insertion_preview(responses); self.box_selection_start = None; self.end_wire_in_progress(network_interface, selection_network_path, responses); @@ -1698,6 +1730,42 @@ impl<'a> MessageHandler> for NodeG NodeGraphMessage::WireHoverTick => { self.expand_wire_hovered_node_after_delay(ipp.time, network_interface, selection_network_path, responses); } + NodeGraphMessage::SendGlide => { + let glide_offsets = network_interface.glide_offsets(&self.glide_network_path); + Self::send_glide(&glide_offsets, &glide_offsets, network_interface, preferences.graph_wire_style, &self.glide_network_path, responses); + } + NodeGraphMessage::GlideTick => { + // A document switched to from one that was gliding inherits its frame subscription, which it ends + if !self.glide_tick_subscribed { + responses.add(BroadcastMessage::UnsubscribeEvent { + on: EventMessage::AnimationFrame, + send: Box::new(NodeGraphMessage::GlideTick.into()), + }); + return; + } + + if !graph_view_overlay_open || self.glide_network_path != breadcrumb_network_path { + self.stop_gliding(network_interface, responses); + return; + } + + // Whatever settles this frame still needs its wires sent once more, to meet it where it sits + let was_gliding = network_interface.glide_offsets(&self.glide_network_path); + let mut glide_offsets = was_gliding.clone(); + + // Each offset shrinks exponentially, which eases the node in and keeps up with a drag that moves it again before it settles + if let Some(last_tick_time) = self.glide_last_tick_time { + let elapsed = ipp.time.saturating_sub(last_tick_time) as f64; + glide_offsets.shrink((-elapsed / NODE_GLIDE_TIME_CONSTANT_MILLISECONDS).exp()); + } + self.glide_last_tick_time = Some(ipp.time); + network_interface.set_glide_offsets(glide_offsets.clone(), &self.glide_network_path); + + Self::send_glide(&glide_offsets, &was_gliding, network_interface, preferences.graph_wire_style, &self.glide_network_path, responses); + if glide_offsets.is_empty() { + self.set_glide_tick_subscribed(false, responses); + } + } NodeGraphMessage::ShakeNode => { let Some((drag_start, _)) = &mut self.drag_start else { log::error!("Drag start should be initialized when shaking a node"); @@ -1719,12 +1787,12 @@ impl<'a> MessageHandler> for NodeG // Collect the distance to move the shaken nodes after the undo let graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32); - if !self.duplicated_in_drag { + if !self.nodes_added_in_drag { // Keep the incremental rounding baseline in sync with the total shift reapplied below drag_start.round_x = graph_delta.x; drag_start.round_y = graph_delta.y; - // Undo to the state of the graph before shaking (skip for Alt-drag to avoid removing the duplicates) + // Undo to the state of the graph before shaking (skipped when the drag added its nodes, which the undo would remove) responses.add(DocumentMessage::AbortTransaction); // Add a history step to abort to the state before shaking if right clicked @@ -1749,6 +1817,12 @@ impl<'a> MessageHandler> for NodeG } } + // A redirect dot is part of the wire it bends, so it's shaken out only along with a wire running between two shaken nodes, and otherwise stays in its wire + let all_selected_nodes = network_interface + .selection_with_bridging_dots(all_selected_nodes.into_iter().collect(), selection_network_path) + .into_iter() + .collect::>(); + let previewing = network_interface.previewing(selection_network_path); for selected_node in &all_selected_nodes { // Handle inputs of selected node @@ -1763,72 +1837,82 @@ impl<'a> MessageHandler> for NodeG } } - let number_of_outputs = network_interface.number_of_outputs(selected_node, selection_network_path); - let mut first_deselected_upstream_output = network_interface.upstream_output_connector(&InputConnector::primary_input(*selected_node), selection_network_path); - while let Some(OutputConnector::Node { node_id, .. }) = &first_deselected_upstream_output { - if !all_selected_nodes.contains(node_id) { - break; - } - - first_deselected_upstream_output = network_interface.upstream_output_connector(&InputConnector::primary_input(*node_id), selection_network_path); + // Walk upstream through the shaken nodes' first exposed inputs to the first output outside them, as deleting them would reconnect + let upstream_of = |node_id: &NodeId| { + network_interface + .first_exposed_input(node_id, selection_network_path) + .and_then(|input| network_interface.upstream_output_connector(&input, selection_network_path)) + }; + let mut first_deselected_upstream_output = upstream_of(selected_node); + while let Some(OutputConnector::Node { node_id, .. }) = first_deselected_upstream_output + && all_selected_nodes.contains(&node_id) + { + first_deselected_upstream_output = upstream_of(&node_id); } + // While previewing, the export's eventual return to this node is a connection too, so it moves upstream as well + if let Some(OutputConnector::Node { node_id, output_index }) = first_deselected_upstream_output + && let Previewing::Yes { + root_node_to_restore: Some(root_node_to_restore), + } = previewing && root_node_to_restore.to_connector() == OutputConnector::primary_output(*selected_node) + { + responses.add(NodeGraphMessage::SetRootNodeToRestore { + root_node_to_restore: RootNode { node_id, output_index }, + }); + } + + let number_of_outputs = network_interface.number_of_outputs(selected_node, selection_network_path); let Some(outward_wires) = network_interface.outward_wires(selection_network_path) else { log::error!("Could not get output wires in shake input"); continue; }; - // Disconnect output wires to non selected nodes + // What fed the shaken nodes takes over each wire their primary output fed outside them, and their other wires out to nodes are disconnected + let mut taken_over_inputs = Vec::new(); for output_index in 0..number_of_outputs { - let output_connector = OutputConnector::node(*selected_node, output_index); - if let Some(downstream_connections) = outward_wires.get(&output_connector) { - for &input_connector in downstream_connections { - if input_connector.node_id().is_some_and(|downstream_node| !all_selected_nodes.contains(&downstream_node)) { - responses.add(NodeGraphMessage::DisconnectInput { input_connector }); - } - } - } - } - - // Handle reconnection - // Find first non selected upstream node by primary flow - if let Some(first_deselected_upstream_output) = first_deselected_upstream_output { - // While previewing, the export's eventual return to this node is a connection too, so it moves upstream as well - if let Previewing::Yes { - root_node_to_restore: Some(root_node_to_restore), - } = previewing && root_node_to_restore.to_connector() == OutputConnector::primary_output(*selected_node) - && let OutputConnector::Node { node_id, output_index } = first_deselected_upstream_output - { - responses.add(NodeGraphMessage::SetRootNodeToRestore { - root_node_to_restore: RootNode { node_id, output_index }, - }); - } - - let Some(downstream_connections_to_first_output) = outward_wires.get(&OutputConnector::primary_output(*selected_node)).cloned() else { - log::error!("Could not get downstream_connections_to_first_output in shake node"); - return; + let Some(downstream_connections) = outward_wires.get(&OutputConnector::node(*selected_node, output_index)) else { + continue; }; - // Reconnect only if all downstream outputs are not selected - for downstream_connection_to_first_output in &downstream_connections_to_first_output { - if !downstream_connection_to_first_output.node_id().is_some_and(|node_id| all_selected_nodes.contains(&node_id)) { - // Reconnect the upstream output to all downstream inputs - responses.add(NodeGraphMessage::CreateWire { - output_connector: first_deselected_upstream_output, - input_connector: *downstream_connection_to_first_output, - }); + for &input_connector in downstream_connections { + if input_connector.node_id().is_some_and(|downstream_node| all_selected_nodes.contains(&downstream_node)) { + continue; } - // Set all chain nodes back to chain position - // TODO: Fix - // for chain_node_to_reset in std::mem::take(&mut self.drag_start_chain_nodes) { - // responses.add(NodeGraphMessage::SetChainPosition { node_id: chain_node_to_reset }); - // } + match first_deselected_upstream_output.filter(|_| output_index == 0) { + Some(_) => taken_over_inputs.push(input_connector), + None if input_connector.node_id().is_some() => responses.add(NodeGraphMessage::DisconnectInput { input_connector }), + // An export with nothing to take over its wire is left fed by the shaken node + None => {} + } } } + // Wired together, so an import taking over several exports feeds them all through one dot + if let Some(output_connector) = first_deselected_upstream_output + && !taken_over_inputs.is_empty() + { + responses.add(NodeGraphMessage::CreateWires { + output_connector, + input_connectors: taken_over_inputs, + }); + } + + // Set all chain nodes back to chain position + // TODO: Fix + // for chain_node_to_reset in std::mem::take(&mut self.drag_start_chain_nodes) { + // responses.add(NodeGraphMessage::SetChainPosition { node_id: chain_node_to_reset }); + // } } - if !self.duplicated_in_drag { - responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta, rubber_band: false }); + if !self.nodes_added_in_drag { + responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { + graph_delta, + rubber_band: false, + glide: false, + }); } + // A dot left with nothing to carry, like one fed by a shaken generator, goes along with its wire + responses.add(NodeGraphMessage::RemoveOrphanedDots); + // Freed of its output wire, the node may now fit onto the wire beneath it + responses.add(NodeGraphMessage::UpdateWireInsertionPreview); responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::SendGraph); } @@ -1940,7 +2024,20 @@ impl<'a> MessageHandler> for NodeG responses.add(FrontendMessage::ClearAllNodeGraphWires); } NodeGraphMessage::SendWires => { - let wires = self.collect_wires(network_interface, preferences.graph_wire_style, breadcrumb_network_path); + let mut wires = self.collect_wires(network_interface, preferences.graph_wire_style, breadcrumb_network_path); + + // The dispatcher defers this past any glide update in the same batch, so the wires following whatever glides must come last here too + let glide_offsets = network_interface.glide_offsets(breadcrumb_network_path); + if !glide_offsets.is_empty() { + wires.extend(Self::gliding_wires( + &glide_offsets, + &glide_offsets, + network_interface, + preferences.graph_wire_style, + breadcrumb_network_path, + )); + } + responses.add(FrontendMessage::UpdateNodeGraphWires { wires }); } NodeGraphMessage::UpdateVisibleNodes => { @@ -1972,8 +2069,12 @@ impl<'a> MessageHandler> for NodeG nodes.push(*node_id); } } + if self.evaluation_errors.iter().any(|error| error.node_path.contains(node_id)) { + nodes.push(*node_id); + } } + layers_in_view.set_node_graph(nodes.iter().copied().collect(), responses); responses.add(FrontendMessage::UpdateVisibleNodes { nodes }); } NodeGraphMessage::SendGraph => { @@ -1986,8 +2087,8 @@ impl<'a> MessageHandler> for NodeG self.frontend_nodes = nodes.iter().map(|node| node.id).collect(); responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes }); - let error = self.node_graph_error(network_interface, breadcrumb_network_path); - responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostic { error }); + let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); + responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors }); let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path); responses.add(NodeGraphMessage::UpdateImportsExports); @@ -1997,6 +2098,7 @@ impl<'a> MessageHandler> for NodeG has_left_input_wire, }); responses.add(NodeGraphMessage::SendSelectedNodes); + responses.add(NodeGraphMessage::UpdateHoveredConnector); self.update_node_graph_hints(responses); } } @@ -2038,26 +2140,44 @@ impl<'a> MessageHandler> for NodeG NodeGraphMessage::SetInput { input_connector, input } => { network_interface.set_input(&input_connector, input, selection_network_path); } - NodeGraphMessage::ShiftSelectedNodes { direction, rubber_band } => { + NodeGraphMessage::NudgeSelectedNodes { direction } => { + responses.add(DocumentMessage::StartTransaction); + responses.add(NodeGraphMessage::ShiftSelectedNodes { + direction, + rubber_band: false, + glide: true, + }); + responses.add(DocumentMessage::EndTransaction); + } + NodeGraphMessage::ShiftSelectedNodes { direction, rubber_band, glide } => { + // The shift can also push other nodes and the imports and exports, so everything it moves glides to where it lands + let positions_before = (glide && graph_view_overlay_open).then(|| Self::glide_positions(network_interface, selection_network_path)); + network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path); if !rubber_band { network_interface.clear_drag_offsets(selection_network_path); } + if let Some(positions_before) = positions_before { + self.begin_glide(positions_before, network_interface, selection_network_path, responses); + responses.add(NodeGraphMessage::SendGlide); + } + if graph_view_overlay_open { responses.add(NodeGraphMessage::SendGraph); responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderScrollbars); } } - NodeGraphMessage::ShiftSelectedNodesByAmount { mut graph_delta, rubber_band } => { + NodeGraphMessage::ShiftSelectedNodesByAmount { mut graph_delta, rubber_band, glide } => { while graph_delta != IVec2::ZERO { match graph_delta.x.cmp(&0) { Ordering::Greater => { responses.add(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Right, rubber_band, + glide, }); graph_delta.x -= 1; } @@ -2065,6 +2185,7 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Left, rubber_band, + glide, }); graph_delta.x += 1; } @@ -2076,6 +2197,7 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down, rubber_band, + glide, }); graph_delta.y -= 1; } @@ -2083,6 +2205,7 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Up, rubber_band, + glide, }); graph_delta.y += 1; } @@ -2301,6 +2424,45 @@ impl<'a> MessageHandler> for NodeG responses.add(InspectorMessage::Refresh); responses.add(DataPanelMessage::Refresh); } + NodeGraphMessage::UpdateHoveredConnector => { + let Some(network_metadata) = network_interface.network_metadata(breadcrumb_network_path) else { + return; + }; + let viewport_location = ipp.mouse.position; + let point = network_metadata + .persistent_metadata + .navigation_metadata + .node_graph_to_viewport + .inverse() + .transform_point2(viewport_location); + + // Moving nodes or drawing a selection box can't grab a connector, so none is shown hovered meanwhile + let can_grab_connector = graph_view_overlay_open && self.drag_start.is_none() && self.box_selection_start.is_none(); + let in_viewport = viewport.is_in_bounds(viewport.logical(viewport_location) + viewport.offset()); + let hovered_connector = (can_grab_connector && in_viewport) + .then(|| Self::connector_under_pointer(viewport_location, point, network_interface, breadcrumb_network_path)) + .flatten(); + self.set_hovered_connector(hovered_connector, responses); + } + NodeGraphMessage::UpdateWireInsertionPreview => { + // Only a drag in progress inserts anything on drop, and one that hasn't started moving yet inserts nothing + let target = if self.drag_start.is_some() && !self.begin_dragging { + Self::wire_to_insert_on(network_interface, preferences.graph_wire_style, selection_network_path).map(|(_, _, input_connector)| input_connector) + } else { + None + }; + if target == self.wire_insertion_preview { + return; + } + + self.wire_insertion_preview = target; + let wire = target.map(|input_connector| match input_connector { + InputConnector::Node { node_id, input_index } => (node_id, input_index), + // Wires into exports are keyed under the max node ID, as in the wires sent to the frontend + InputConnector::Export(export_index) => (NodeId(u64::MAX), export_index), + }); + responses.add(FrontendMessage::UpdateWireInsertionPreview { wire }); + } NodeGraphMessage::UpdateBoxSelection => { if let Some((box_selection_start, _)) = self.box_selection_start { let Some(network_metadata) = network_interface.network_metadata(selection_network_path) else { @@ -2402,7 +2564,27 @@ impl<'a> MessageHandler> for NodeG } NodeGraphMessage::UpdateLayerPanel => { - Self::update_layer_panel(network_interface, selection_network_path, layers_panel_open, tool_edit_target, layers_panel_expanded_chains, responses); + let layers = layers_in_view.layers_panel().iter().copied(); + Self::update_layer_panel( + layers, + network_interface, + selection_network_path, + layers_panel_open, + tool_edit_target, + layers_panel_expanded_chains, + responses, + ); + } + NodeGraphMessage::SendLayerPanelDetails { layers } => { + Self::update_layer_panel( + layers, + network_interface, + selection_network_path, + layers_panel_open, + tool_edit_target, + layers_panel_expanded_chains, + responses, + ); } NodeGraphMessage::UpdateNewNodeGraph => { let Some(selected_nodes) = network_interface.selected_nodes_mut(selection_network_path) else { @@ -2447,6 +2629,16 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::SendGraph); } + NodeGraphMessage::UpdateEvaluationErrors { errors } => { + if self.evaluation_errors != errors { + self.evaluation_errors = errors; + if breadcrumb_network_path == selection_network_path && graph_view_overlay_open { + let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); + responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors }); + responses.add(NodeGraphMessage::UpdateVisibleNodes); + } + } + } NodeGraphMessage::UpdateActionButtons => { if selection_network_path == breadcrumb_network_path { self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses); @@ -2500,13 +2692,109 @@ impl NodeGraphMessageHandler { self.wire_in_progress_from_new_export = None; self.disconnecting = None; - responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: None }); + responses.add(FrontendMessage::UpdateWirePathInProgress { + wire_path: None, + dragged_from: None, + snapped_to: None, + }); } pub fn is_reordering_import_export(&self) -> bool { self.reordering_import.is_some() || self.reordering_export.is_some() } + /// The connector under a press that a redirect dot can be dragged out of, which is an output or export with wires a dot can bend. + fn dot_drag_out_source( + clicked_input: Option, + clicked_output: Option, + network_interface: &NodeNetworkInterface, + network_path: &[NodeId], + ) -> Option { + match (clicked_input, clicked_output) { + (Some(export @ InputConnector::Export(export_index)), _) => network_interface.can_bend_wire_into(&export, network_path).then_some(DotDragOutSource::Export(export_index)), + (None, Some(output)) => (!network_interface.inputs_fed_through_bendable_wires(&output, network_path).is_empty()).then_some(DotDragOutSource::Output(output)), + _ => None, + } + } + + /// The wire a press at the point (in node graph space) lands on, within a few pixels at the graph's zoom. + fn wire_at_point(point: DVec2, network_interface: &NodeNetworkInterface, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option { + let zoom = network_interface + .network_metadata(network_path)? + .persistent_metadata + .navigation_metadata + .node_graph_to_viewport + .matrix2 + .x_axis + .x; + network_interface.wire_input_from_point(point, 6. / zoom.max(f64::EPSILON), wire_style, network_path) + } + + /// Selects the redirect dot being inserted under the pointer and drags it along, as a drag begun at `start` (in node graph space) that has already come `moved` grid cells. + fn drag_new_dot(&mut self, dot: NodeId, start: DVec2, moved: IVec2, responses: &mut VecDeque) { + responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![dot] }); + + let drag_start = DragStart { + start_x: start.x, + start_y: start.y, + round_x: moved.x, + round_y: moved.y, + }; + self.drag_start = Some((drag_start, moved != IVec2::ZERO)); + self.drag_start_chain_nodes = Vec::new(); + // Already underway, so holding Alt doesn't duplicate the dot + self.begin_dragging = false; + self.nodes_added_in_drag = true; + self.node_has_moved_in_drag = moved != IVec2::ZERO; + + self.update_node_graph_hints(responses); + } + + /// The center of the connector a press at the pointer would grab, in node graph space, as `PointerDown` decides what lies under it. + fn connector_under_pointer(viewport_location: DVec2, point: DVec2, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option { + // Names and layer buttons take presses before the connectors beneath them + let layer_button_under_pointer = |target_type| network_interface.layer_click_target_from_click(viewport_location, target_type, network_path).is_some(); + if network_interface.import_export_name_from_point(point, network_path).is_some() + || layer_button_under_pointer(network_interface::LayerClickTargetTypes::Visibility) + || layer_button_under_pointer(network_interface::LayerClickTargetTypes::Lock) + { + return None; + } + + // Centered where it's drawn, even while gliding into place + let glide_offsets = network_interface.glide_offsets(network_path); + let empty_connector = |is_import| { + let (_, center) = network_interface.empty_import_export_connector_at(point, is_import, network_path)?; + Some(center + if is_import { glide_offsets.imports } else { glide_offsets.exports }) + }; + let input = || { + let input = network_interface.input_port_from_click(viewport_location, network_path)?; + Some(network_interface.input_position(&input, network_path)? + glide_offsets.input(&input)) + }; + let output = || { + let output = network_interface.output_port_from_click(viewport_location, network_path)?; + Some(network_interface.output_position(&output, network_path)? + glide_offsets.output(&output)) + }; + empty_connector(true).or_else(|| empty_connector(false)).or_else(input).or_else(output) + } + + /// Tells the frontend which connector to show hovered, given by its center in node graph space. + fn set_hovered_connector(&mut self, hovered_connector: Option, responses: &mut VecDeque) { + if self.hovered_connector != hovered_connector { + self.hovered_connector = hovered_connector; + responses.add(FrontendMessage::UpdateHoveredConnector { + center: hovered_connector.map(|center| (center.x, center.y)), + }); + } + } + + /// Stops highlighting the wire a dragged node would be inserted onto. + fn clear_wire_insertion_preview(&mut self, responses: &mut VecDeque) { + if self.wire_insertion_preview.take().is_some() { + responses.add(FrontendMessage::UpdateWireInsertionPreview { wire: None }); + } + } + /// Cancels dragging an import or export to reorder it, leaving it where it was. pub fn abort_import_export_reorder(&mut self, responses: &mut VecDeque) { self.reordering_import = None; @@ -2526,6 +2814,8 @@ impl NodeGraphMessageHandler { responses.add(DocumentMessage::AbortTransaction); self.update_node_graph_hints(responses); } + self.clear_wire_insertion_preview(responses); + self.stop_gliding(network_interface, responses); if self.context_menu.take().is_some() { responses.add(FrontendMessage::UpdateContextMenuInformation { context_menu_information: None }); } @@ -2536,8 +2826,18 @@ impl NodeGraphMessageHandler { self.wire_in_progress_from_input.is_some() || self.wire_in_progress_from_new_export.is_some() } - /// Draws the wire in progress between its two ends, where `input_end` is the input it meets at its input end, if any. - fn send_wire_in_progress(&self, input_end: Option, network_interface: &NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque) { + /// Keeps a pressed connector lit as the source of the wire about to be dragged out of it, since the press ends its hover before the pointer moves far enough to draw the wire. + fn keep_pressed_connector_lit(center: Option, responses: &mut VecDeque) { + responses.add(FrontendMessage::UpdateWirePathInProgress { + wire_path: None, + dragged_from: center.map(|center| (center.x, center.y)), + snapped_to: None, + }); + } + + /// Draws the wire in progress between its two ends, where `input_end` is the input it meets at its input end, if any, + /// and `loose_end_snapped` is whether the end following the pointer has snapped to a connector. + fn send_wire_in_progress(&self, input_end: Option, loose_end_snapped: bool, network_interface: &NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque) { let (Some(from_connector), Some(to_connector)) = (self.wire_in_progress_from_connector, self.wire_in_progress_to_connector) else { return; }; @@ -2560,7 +2860,19 @@ impl NodeGraphMessageHandler { is_list: false, center_path_string: String::new(), }; - responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: Some(wire_path) }); + + // The end it's dragged from always meets a connector, while the loose end does once it snaps to one + let (dragged_from, loose_end) = if self.wire_in_progress_is_backward() { + (to_connector, from_connector) + } else { + (from_connector, to_connector) + }; + + responses.add(FrontendMessage::UpdateWirePathInProgress { + wire_path: Some(wire_path), + dragged_from: Some((dragged_from.x, dragged_from.y)), + snapped_to: loose_end_snapped.then_some((loose_end.x, loose_end.y)), + }); } /// The output the wire in progress is dragged from. @@ -2616,10 +2928,7 @@ impl NodeGraphMessageHandler { hidden_value && !network_interface.is_internal_input(&node_id, input_index, network_path) - && network_interface - .potential_valid_input_types(&input_connector, network_path) - .iter() - .any(|valid_type| output_types.iter().any(|output_type| type_feeds_connector(output_type, valid_type))) + && output_types.iter().any(|output_type| network_interface.input_accepts_type(&input_connector, output_type, network_path)) }) .collect::>(); if revealed_input_indices.is_empty() { @@ -2668,6 +2977,138 @@ impl NodeGraphMessageHandler { network_interface.set_input(&input_connector, input, network_path); } + /// Where each node and the imports and exports sit, to find what a shift moves. + fn glide_positions(network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> (HashMap, Option<(IVec2, IVec2)>) { + let node_ids = network_interface + .nested_network(network_path) + .map(|network| network.nodes.keys().copied().collect::>()) + .unwrap_or_default(); + let node_positions = network_interface.positions(node_ids, network_path).into_iter().collect(); + + (node_positions, network_interface.import_export_position(network_path)) + } + + /// Lets everything that moved away from `positions_before` glide to where it now sits from where it was drawn, so it doesn't jump. + fn begin_glide( + &mut self, + positions_before: (HashMap, Option<(IVec2, IVec2)>), + network_interface: &NodeNetworkInterface, + network_path: &[NodeId], + responses: &mut VecDeque, + ) { + if self.glide_network_path != network_path { + self.stop_gliding(network_interface, responses); + self.glide_network_path = network_path.to_vec(); + } + + let (node_positions_before, import_export_position_before) = positions_before; + let (node_positions, import_export_position) = Self::glide_positions(network_interface, network_path); + let mut glide_offsets = network_interface.glide_offsets(network_path); + + for (node_id, position) in node_positions { + if let Some(position_before) = node_positions_before.get(&node_id) + && *position_before != position + { + *glide_offsets.nodes.entry(node_id).or_default() += (*position_before - position).as_dvec2() * GRID_SIZE as f64; + } + } + + if let (Some((imports_before, exports_before)), Some((imports, exports))) = (import_export_position_before, import_export_position) { + glide_offsets.imports += (imports_before - imports).as_dvec2(); + glide_offsets.exports += (exports_before - exports).as_dvec2(); + } + + self.set_glide_tick_subscribed(!glide_offsets.is_empty(), responses); + network_interface.set_glide_offsets(glide_offsets, network_path); + } + + /// Sends where everything gliding into place is drawn, along with the wires meeting whatever was gliding, which follow it rather than where it sits. + fn send_glide( + glide_offsets: &GlideOffsets, + was_gliding: &GlideOffsets, + network_interface: &NodeNetworkInterface, + wire_style: GraphWireStyle, + network_path: &[NodeId], + responses: &mut VecDeque, + ) { + responses.add(FrontendMessage::UpdateGlideOffsets { + nodes: glide_offsets.nodes.iter().map(|(node_id, offset)| (*node_id, (offset.x, offset.y))).collect(), + imports: (glide_offsets.imports.x, glide_offsets.imports.y), + exports: (glide_offsets.exports.x, glide_offsets.exports.y), + }); + + let wires = Self::gliding_wires(glide_offsets, was_gliding, network_interface, wire_style, network_path); + responses.add(FrontendMessage::UpdateNodeGraphWires { wires }); + } + + /// The wires meeting whatever was gliding, drawn to follow it rather than where it sits. + fn gliding_wires(glide_offsets: &GlideOffsets, was_gliding: &GlideOffsets, network_interface: &NodeNetworkInterface, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Vec { + // The inputs of the nodes and exports that were gliding, and those fed by the nodes and imports that were gliding (leaving out any node deleted meanwhile) + let mut inputs = HashSet::new(); + let mut outputs = Vec::new(); + let network = network_interface.nested_network(network_path); + for node_id in was_gliding.nodes.keys().filter(|node_id| network.is_some_and(|network| network.nodes.contains_key(node_id))) { + inputs.extend((0..network_interface.number_of_inputs(node_id, network_path)).map(|input_index| InputConnector::node_at_index(*node_id, input_index))); + outputs.extend((0..network_interface.number_of_outputs(node_id, network_path)).map(|output_index| OutputConnector::node(*node_id, output_index))); + } + + if was_gliding.exports != DVec2::ZERO { + inputs.extend((0..network_interface.number_of_exports(network_path)).map(InputConnector::Export)); + } + if was_gliding.imports != DVec2::ZERO { + outputs.extend((0..network_interface.number_of_imports(network_path)).map(OutputConnector::Import)); + } + + network_interface.with_outward_wires(network_path, |outward_wires| { + for output in &outputs { + inputs.extend(outward_wires.get(output).into_iter().flatten().copied()); + } + }); + + let mut wires = inputs + .iter() + .filter(|input| network_interface.input_from_connector(input, network_path).is_some_and(|input| input.is_exposed())) + .filter_map(|input| network_interface.wire_update_from_input(input, wire_style, glide_offsets, network_path)) + .collect::>(); + wires.extend(network_interface.wire_to_root(wire_style, glide_offsets, network_path)); + wires + } + + /// Settles whatever is gliding into place at once, such as when the drag moving it is aborted. + pub fn stop_gliding(&mut self, network_interface: &NodeNetworkInterface, responses: &mut VecDeque) { + if !self.glide_tick_subscribed { + return; + } + + network_interface.set_glide_offsets(GlideOffsets::default(), &self.glide_network_path); + responses.add(FrontendMessage::UpdateGlideOffsets { + nodes: Vec::new(), + imports: (0., 0.), + exports: (0., 0.), + }); + self.set_glide_tick_subscribed(false, responses); + } + + fn set_glide_tick_subscribed(&mut self, subscribed: bool, responses: &mut VecDeque) { + if self.glide_tick_subscribed == subscribed { + return; + } + self.glide_tick_subscribed = subscribed; + self.glide_last_tick_time = None; + + let send = Box::new(NodeGraphMessage::GlideTick.into()); + responses.add(match subscribed { + true => BroadcastMessage::SubscribeEvent { + on: EventMessage::AnimationFrame, + send, + }, + false => BroadcastMessage::UnsubscribeEvent { + on: EventMessage::AnimationFrame, + send, + }, + }); + } + fn set_wire_hover_tick_subscribed(&mut self, subscribed: bool, responses: &mut VecDeque) { if self.wire_hover_tick_subscribed == subscribed { return; @@ -2689,7 +3130,12 @@ impl NodeGraphMessageHandler { /// Similar to [`NodeGraphMessageHandler::actions`], but this provides additional actions if the node graph is open and should only be called in that circumstance. pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList { - let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp, SendClickTargets, EndSendClickTargets); + let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp); + + // Only development builds draw the click targets, so users don't come across the overlay by accident + if cfg!(debug_assertions) { + common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets)); + } if self.has_selection { common.extend(actions!(NodeGraphMessageDiscriminant; @@ -2701,7 +3147,7 @@ impl NodeGraphMessageHandler { ToggleSelectedAsLayersOrNodes, ToggleSelectedLocked, ToggleSelectedVisibility, - ShiftSelectedNodes, + NudgeSelectedNodes, )); } @@ -2714,8 +3160,92 @@ impl NodeGraphMessageHandler { common } - fn duplicate_selected_nodes(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], responses: &mut VecDeque) { + /// The wire a single dragged node would be inserted onto if dropped where it is, with the node and the index of its input the wire would feed. + /// A node is only inserted when it's alone in the selection, has nothing wired out of its primary output, has a free first exposed input, and overlaps exactly one fitting wire. + // O(wires), since each wire's path is intersected with the node's bounds + pub(crate) fn wire_to_insert_on(network_interface: &mut NodeNetworkInterface, graph_wire_style: GraphWireStyle, selection_network_path: &[NodeId]) -> Option<(NodeId, usize, InputConnector)> { + let selected_nodes = network_interface.selected_nodes_in_nested_network(selection_network_path)?; + let [selected_node_id] = *selected_nodes.selected_nodes_ref().as_slice() else { return None }; + + let has_primary_output_connection = network_interface.outward_wires(selection_network_path).is_some_and(|outward_wires| { + outward_wires + .get(&OutputConnector::primary_output(selected_node_id)) + .is_some_and(|outward_wires| !outward_wires.is_empty()) + }); + if has_primary_output_connection { + return None; + } + + // The input it's spliced in by has to be disconnected + let insert_node_input_index = network_interface + .first_exposed_input(&selected_node_id, selection_network_path) + .filter(|input| network_interface.input_from_connector(input, selection_network_path).is_some_and(|input| input.as_value().is_some()))? + .input_index(); + + let Some(node_bbox) = network_interface.node_bounding_box(&selected_node_id, selection_network_path) else { + log::error!("Could not get bounding box for node: {selected_node_id}"); + return None; + }; + let node_bbox = kurbo::Rect::new(node_bbox[0].x, node_bbox[0].y, node_bbox[1].x, node_bbox[1].y).to_path(DEFAULT_ACCURACY); + + let mut wires_to_check = network_interface.node_graph_input_connectors(selection_network_path).into_iter().collect::>(); + // Prevent inserting on a link that is connected upstream to the selected node + for upstream_node in network_interface.upstream_flow_back_from_nodes(vec![selected_node_id], selection_network_path, network_interface::FlowType::UpstreamFlow) { + for input_index in 0..network_interface.number_of_inputs(&upstream_node, selection_network_path) { + wires_to_check.remove(&InputConnector::node_at_index(upstream_node, input_index)); + } + } + + let overlapping_wires = wires_to_check + .into_iter() + .filter_map(|input| { + // Prevent inserting a layer into a chain + if network_interface.is_layer(&selected_node_id, selection_network_path) + && input.node_id().is_some_and(|input_node_id| network_interface.is_chain(&input_node_id, selection_network_path)) + { + return None; + } + + let (wire, _center_line, is_stack) = network_interface.vector_wire_from_input(&input, graph_wire_style, selection_network_path)?; + + let inside = bezpath_is_inside_bezpath(&wire, &node_bbox, None, None); + let intersect = wire + .segments() + .any(|segment| node_bbox.segments().filter_map(|segment| segment.as_line()).any(|line| !segment.intersect_line(line).is_empty())); + + (intersect || inside).then_some((input, is_stack)) + }) + .collect::>(); + + // Prioritize vertical thick lines and cancel if there are multiple potential wires + let (stack_wires, node_wires): (Vec<_>, Vec<_>) = overlapping_wires.into_iter().partition(|(_, is_stack)| *is_stack); + let stack_wires = stack_wires.into_iter().map(|(input, _)| input).collect::>(); + let node_wires = node_wires.into_iter().map(|(input, _)| input).collect::>(); + + let overlapping_wire = if network_interface.is_layer(&selected_node_id, selection_network_path) { + if stack_wires.len() == 1 { + stack_wires.first() + } else if stack_wires.is_empty() && node_wires.len() == 1 { + node_wires.first() + } else { + None + } + } else if node_wires.len() == 1 { + node_wires.first() + } else { + None + }; + + overlapping_wire.map(|input| (selected_node_id, insert_node_input_index, *input)) + } + + /// Duplicates the selected nodes and selects the copies, returning whether there were any to duplicate, since a lone dot has no copy. + fn duplicate_selected_nodes(network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], responses: &mut VecDeque) -> bool { let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path); + let all_selected_nodes = network_interface.selection_with_bridging_dots(all_selected_nodes, selection_network_path); + if all_selected_nodes.is_empty() { + return false; + } let copy_ids = all_selected_nodes.iter().enumerate().map(|(new, id)| (*id, NodeId(new as u64))).collect::>(); @@ -2726,6 +3256,7 @@ impl NodeGraphMessageHandler { responses.add(NodeGraphMessage::SelectedNodesSet { nodes: new_ids.values().cloned().collect(), }); + true } /// Send the cached layout to the frontend for the control bar at the top of the node panel @@ -2797,7 +3328,7 @@ impl NodeGraphMessageHandler { let single_layer_selected = selection_includes_layers && !has_multiple_selection; 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| { @@ -2983,6 +3514,8 @@ impl NodeGraphMessageHandler { // The same layer/node may appear several times. Sort and dedup them for a stable ordering. layers.sort(); layers.dedup(); + // Redirect dots are only bends in wires, so they have no parameters to inspect + nodes.retain(|node_id| !context.network_interface.is_redirect_dot(node_id, context.selection_network_path)); nodes.sort(); nodes.dedup(); @@ -3057,7 +3590,73 @@ impl NodeGraphMessageHandler { } } - vec![layer_section] + // The layers this one's output feeds, which a stack used in several places can be many of, and the graph's output none of. + // Followed through any nodes between, each layer takes it either from its bottom (as the sibling above in its stack) or into its content (as its parent). + let network_path = context.selection_network_path; + let outward_connectors = |node_id: NodeId| { + context + .network_interface + .with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).cloned()) + .flatten() + .unwrap_or_default() + }; + let (mut siblings, mut parents) = (Vec::new(), Vec::new()); + let mut pending_connectors = outward_connectors(layer); + let mut visited_nodes = HashSet::new(); + while let Some(connector) = pending_connectors.pop() { + let Some(node_id) = connector.node_id() else { continue }; + + if context.network_interface.is_layer(&node_id, network_path) { + let receivers = if connector.input_index() == 0 { &mut siblings } else { &mut parents }; + receivers.push(node_id); + continue; + } + + // A node passes it on only when taking it as its primary input, rather than as a parameter + if connector.input_index() == 0 && visited_nodes.insert(node_id) { + pending_connectors.extend(outward_connectors(node_id)); + } + } + + // Sorted for a stable button order, since outward wires are unordered + siblings.sort_unstable(); + siblings.dedup(); + parents.sort_unstable(); + parents.dedup(); + + // The layer feeding this one from below in its stack, unless this is the bottom + let layer_below = node_inspector::input_chain(layer, 0, context.network_interface, network_path).and_then(|(_, stack_layer)| stack_layer); + + // Each is only referred to by a button, wired to the layer's section. Parents sit just above, the wire turning into their content, + // and siblings above them, the wire continuing up past that turn into their bottom. + let mut sections = Vec::new(); + + if let Some(siblings_section) = node_inspector::layer_references_section(&siblings, "Select Sibling Layer", context) { + sections.push(siblings_section); + } + if let Some(mut parents_section) = node_inspector::layer_references_section(&parents, "Select Parent Layer", context) { + if let LayoutGroup::NodeSection(section) = &mut parents_section { + section.content_wire = Some(node_inspector::output_section_wire(layer, context)); + section.content_wire_continues = !siblings.is_empty(); + } + sections.push(parents_section); + } + if !sections.is_empty() + && let LayoutGroup::NodeSection(section) = &mut layer_section + { + section.output_wire = Some(node_inspector::output_section_wire(layer, context)); + } + sections.push(layer_section); + if let Some(layer_below) = layer_below + && let Some(mut below_section) = node_inspector::layer_references_section(&[layer_below], "Select Sibling Layer", context) + { + if let LayoutGroup::NodeSection(section) = &mut below_section { + section.output_wire = Some(node_inspector::output_section_wire(layer_below, context)); + } + sections.push(below_section); + } + + sections } // If multiple layers and/or nodes are selected, show nothing _ => Vec::new(), @@ -3086,7 +3685,7 @@ impl NodeGraphMessageHandler { wire_path_update: None, })); - if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, breadcrumb_network_path) { + if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, &GlideOffsets::default(), breadcrumb_network_path) { added_wires.push(wire_to_root); } else { added_wires.push(WirePathUpdate { @@ -3152,6 +3751,7 @@ impl NodeGraphMessageHandler { .node_metadata(&node_id, breadcrumb_network_path) .is_some_and(|node_metadata| node_metadata.persistent_metadata.is_layer()), can_be_layer: network_interface.is_eligible_to_be_layer(&node_id, breadcrumb_network_path), + is_redirect_dot: network_interface.is_redirect_dot(&node_id, breadcrumb_network_path), reference: network_interface.reference(&node_id, breadcrumb_network_path).map(|reference| reference.serialized()), display_name: network_interface.display_name(&node_id, breadcrumb_network_path), implementation_name: network_interface.implementation_name(&node_id, breadcrumb_network_path), @@ -3186,31 +3786,57 @@ impl NodeGraphMessageHandler { Some(subgraph_names) } - fn node_graph_error(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Option { - let graph_error = network_interface + fn node_graph_errors(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec { + let depth = breadcrumb_network_path.len(); + let inside = |path: &[NodeId]| path.starts_with(breadcrumb_network_path) && path.len() > depth; + let graph_errors: Vec<_> = network_interface .resolved_types .node_graph_errors .iter() - .find(|error| error.node_path.starts_with(breadcrumb_network_path) && error.node_path.len() > breadcrumb_network_path.len())?; - let error = if graph_error.node_path.len() == breadcrumb_network_path.len() + 1 { - format!("{:?}", graph_error.error) - } else { - "Node graph type error within this node".to_string() + .filter(|error| inside(&error.node_path)) + .map(|error| match error.node_path.len() == depth + 1 { + true => (error.node_path[depth], format!("{:?}", error.error)), + false => (error.node_path[depth], "Node graph type error within this node".to_string()), + }) + .collect(); + // Evaluation errors come from the last graph that compiled, so a type error hides them + let errors = match graph_errors.is_empty() { + true => self + .evaluation_errors + .iter() + .filter(|error| inside(&error.node_path)) + .map(|error| match error.node_path.len() == depth + 1 { + true => (error.node_path[depth], error.message.clone()), + false => (error.node_path[depth], "Node graph error within this node".to_string()), + }) + .collect(), + false => graph_errors, }; - let error_node = graph_error.node_path[breadcrumb_network_path.len()]; - let mut position = network_interface.position(&error_node, breadcrumb_network_path)?; - // Convert to graph space - position *= 24; - if network_interface.is_layer(&error_node, breadcrumb_network_path) { - position += IVec2::new(12, -12) - } - let position = position.into(); - - Some(NodeGraphErrorDiagnostic { position, error }) + let mut shown = HashSet::new(); + errors + .into_iter() + .filter(|(node, _)| shown.insert(*node)) + .filter_map(|(node, error)| { + let mut position = network_interface.position(&node, breadcrumb_network_path)?; + // Convert to graph space + position *= 24; + if network_interface.is_layer(&node, breadcrumb_network_path) { + position += IVec2::new(12, -12) + } + Some(NodeGraphErrorDiagnostic { + node_id: node, + position: position.into(), + error, + }) + }) + .collect() } + /// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view. + // O(given layers × nesting depth), apart from what the active tool would edit in the selected layers fn update_layer_panel( + layers: impl IntoIterator, network_interface: &NodeNetworkInterface, selection_network_path: &[NodeId], layers_panel_open: bool, @@ -3237,17 +3863,18 @@ impl NodeGraphMessageHandler { let selected_nodes = network_interface.selected_nodes().selected_nodes().copied().collect::>(); let edited_nodes = network_interface.transaction_edited_nodes(); - let mut descendants_of_selected = HashSet::new(); - for selected_layer in &selected_layers { - for descendant in LayerNodeIdentifier::new(*selected_layer, network_interface).descendants(network_interface.document_metadata()) { - descendants_of_selected.insert(descendant.to_node()); - } - } - - for (&node_id, node_metadata) in &network_interface.document_network_metadata().persistent_metadata.node_metadata { - if node_metadata.persistent_metadata.is_layer() { + let node_metadata = &network_interface.document_network_metadata().persistent_metadata.node_metadata; + for node_id in layers { + // The Layers panel may still list a layer that has since been deleted + if node_metadata.get(&node_id).is_some_and(|metadata| metadata.persistent_metadata.is_layer()) { let layer = LayerNodeIdentifier::new(node_id, network_interface); + let descendant_of_selected = layer + .ancestors(network_interface.document_metadata()) + .skip(1) + .filter(|ancestor| *ancestor != LayerNodeIdentifier::ROOT_PARENT) + .any(|ancestor| selected_layers.contains(&ancestor.to_node())); + let children_allowed = // The layer has other layers as children along the secondary input's horizontal flow layer.has_children(network_interface.document_metadata()) @@ -3310,7 +3937,7 @@ impl NodeGraphMessageHandler { visible: network_interface.is_visible(&node_id, &[]), unlocked: !network_interface.is_locked(&node_id, &[]), selected: selected_layers.contains(&node_id), - descendant_of_selected: descendants_of_selected.contains(&node_id), + descendant_of_selected, clipped: get_clip_mode(layer, network_interface).unwrap_or(false) && clippable, clippable, }; @@ -3323,7 +3950,7 @@ impl NodeGraphMessageHandler { // A wire is in progress and its start and end connectors are set let wiring = self.wire_in_progress_from_connector.is_some(); - // Node gragging is in progress (having already moved at least one pixel from the mouse down position) + // Node dragging is in progress (having already moved at least one pixel from the mouse down position) let dragging_nodes = self.drag_start.as_ref().is_some_and(|(_, dragged)| *dragged); // A box selection is in progress @@ -3379,11 +4006,16 @@ impl Default for NodeGraphMessageHandler { widgets: [LayoutGroup::row(Vec::new()), LayoutGroup::row(Vec::new())], drag_start: None, begin_dragging: false, - duplicated_in_drag: false, + nodes_added_in_drag: false, node_has_moved_in_drag: false, + latest_left_press: None, + double_click_used_by_press: false, + dot_drag_out: None, shift_without_push: false, box_selection_start: None, drag_start_chain_nodes: Vec::new(), + wire_insertion_preview: None, + hovered_connector: None, selection_before_pointer_down: Vec::new(), disconnecting: None, initial_disconnecting: false, @@ -3397,6 +4029,9 @@ impl Default for NodeGraphMessageHandler { wire_hovered_node: None, wire_expanded_node: None, wire_hover_tick_subscribed: false, + glide_network_path: Vec::new(), + glide_last_tick_time: None, + glide_tick_subscribed: false, context_menu: None, deselect_on_pointer_up: None, auto_panning: Default::default(), @@ -3406,6 +4041,7 @@ impl Default for NodeGraphMessageHandler { end_index: None, frontend_nodes: Vec::new(), frontend_wires: HashSet::new(), + evaluation_errors: Vec::new(), } } } @@ -3417,8 +4053,11 @@ impl PartialEq for NodeGraphMessageHandler { && self.widgets == other.widgets && self.drag_start == other.drag_start && self.begin_dragging == other.begin_dragging - && self.duplicated_in_drag == other.duplicated_in_drag + && self.nodes_added_in_drag == other.nodes_added_in_drag && self.node_has_moved_in_drag == other.node_has_moved_in_drag + && self.latest_left_press == other.latest_left_press + && self.double_click_used_by_press == other.double_click_used_by_press + && self.dot_drag_out == other.dot_drag_out && self.box_selection_start == other.box_selection_start && self.initial_disconnecting == other.initial_disconnecting && self.select_if_not_dragged == other.select_if_not_dragged @@ -3431,6 +4070,37 @@ impl PartialEq for NodeGraphMessageHandler { } } +/// A press of the left mouse button in the graph, kept to tell whether the next press is the second of a double-click. +#[derive(Debug, Clone, Copy, PartialEq)] +struct LeftPress { + /// When the press was made, in milliseconds. + time: f64, + /// Where the press was made, in viewport space. + position: DVec2, + /// Whether this press was itself the second of a double-click, which ends that run of clicks. + is_double: bool, + /// Whether the press was released where it was made, as a click that a second press can make a double-click. + is_click: bool, +} + +impl LeftPress { + /// Whether a press made at this time and place is the second of a double-click begun by this press. + fn continued_by(&self, time: f64, position: DVec2) -> bool { + // Desktop times presses that pass through the browser on another clock, so a negative gap counts as too long + let soon_after = (0. ..=DOUBLE_CLICK_MILLISECONDS as f64).contains(&(time - self.time)); + self.is_click && !self.is_double && soon_after && self.position.distance(position) <= DOUBLE_CLICK_ALLOWED_TRAVEL + } +} + +/// The connector a redirect dot is dragged out of, and so the wires the dot takes over. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum DotDragOutSource { + /// The wires leaving the output that a dot can bend, which then fan out from the dot. + Output(OutputConnector), + /// The wire into the export. + Export(usize), +} + /// The message adding the export that a dimmed connector for adding one stands in for at `export_index`, where index 0 is the empty primary. fn add_export_at(export_index: usize) -> NodeGraphMessage { if export_index == 0 { diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index 09fe85c553..33b96bf491 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -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::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), - Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), + Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), + Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().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 { - 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 { + 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"); } diff --git a/editor/src/messages/portfolio/document/node_graph/utility_types.rs b/editor/src/messages/portfolio/document/node_graph/utility_types.rs index 549df5797c..2a11dd4a3d 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -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, #[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, + pub message: String, +} + #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)] pub struct FrontendClickTargets { diff --git a/editor/src/messages/portfolio/document/overlays/utility_functions.rs b/editor/src/messages/portfolio/document/overlays/utility_functions.rs index 59de9f797e..76bc5f2823 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_functions.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_functions.rs @@ -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 { +pub fn selected_segments_for_layer(vector: &VectorGeometry, state: &SelectedLayerState) -> Vec { 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); } diff --git a/editor/src/messages/portfolio/document/overlays/utility_types_native.rs b/editor/src/messages/portfolio/document/overlays/utility_types_native.rs index 5be859a73f..d4dcfdf9b9 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_types_native.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_types_native.rs @@ -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); diff --git a/editor/src/messages/portfolio/document/overlays/utility_types_web.rs b/editor/src/messages/portfolio/document/overlays/utility_types_web.rs index 53eb93bf8d..5419513385 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_types_web.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_types_web.rs @@ -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(); diff --git a/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs b/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs index fa6e4ec817..7031a686d4 100644 --- a/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs @@ -7,7 +7,7 @@ use crate::test_utils::EditorTestUtils; use document_container::{AnyContainer, AsyncContainer}; fn dispatch(editor: &mut EditorTestUtils, message: impl Into) -> Vec { - editor.editor.handle_message(message) + editor.dispatch(message) } fn portfolio(editor: &EditorTestUtils) -> &PortfolioMessageHandler { diff --git a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs index 7f4ad9d14a..b7ba3327c3 100644 --- a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs @@ -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) { node_paths(&document.network_interface) diff --git a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs index d78eebc3d2..abab0d2276 100644 --- a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs @@ -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, pub clip_targets: HashSet, - pub vector_modify: HashMap, + pub vector_modify: HashMap, /// 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>, + pub layer_vector_data: HashMap>>, /// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list. pub layer_appearance_attributes: HashMap>, /// 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); } } diff --git a/editor/src/messages/portfolio/document/utility_types/layers_in_view.rs b/editor/src/messages/portfolio/document/utility_types/layers_in_view.rs new file mode 100644 index 0000000000..141d3607f3 --- /dev/null +++ b/editor/src/messages/portfolio/document/utility_types/layers_in_view.rs @@ -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, + /// The nodes in view in the node graph while it's open. + node_graph: HashSet, + /// The latest thumbnail of each layer, as rendered by the graph runtime. + thumbnails: HashMap, + /// The layers whose latest thumbnail the frontend has. + thumbnails_sent: HashSet, +} + +impl LayersInView { + pub fn layers_panel(&self) -> &HashSet { + &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, responses: &mut VecDeque) { + 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, responses: &mut VecDeque) { + 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) { + 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) { + // 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::>(); + 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) { + 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) -> 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"); + } +} diff --git a/editor/src/messages/portfolio/document/utility_types/mod.rs b/editor/src/messages/portfolio/document/utility_types/mod.rs index a38ca2c545..141690238d 100644 --- a/editor/src/messages/portfolio/document/utility_types/mod.rs +++ b/editor/src/messages/portfolio/document/utility_types/mod.rs @@ -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; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface.rs b/editor/src/messages/portfolio/document/utility_types/network_interface.rs index a5ce50be69..84e827904d 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -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, 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(), } } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs index 49e48770f5..9f517e885f 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs @@ -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()); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs index d1ec04c473..70633a015f 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/caches.rs @@ -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 { + 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 { + 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>> { 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 { + // 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 { 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 { + pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option { 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 { - 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 { + 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 diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs index 2a6588aa80..f319174cb2 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs @@ -1,7 +1,9 @@ use super::{ - ChainInsertionPoint, FlowType, ImportOrExport, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, - Previewing, RootNode, TransactionStatus, + ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, + OutputConnector, Previewing, RootNode, TransactionStatus, }; +use crate::consts::GRID_SIZE; +use crate::messages::input_mapper::utility_types::pointer::EditorPointerState; use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction}; use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; use crate::test_utils::test_prelude::*; @@ -267,6 +269,39 @@ async fn layer_stacking_follows_wiring() { assert_invariants(&editor, "after stacking and unstacking a layer"); } +#[tokio::test] +async fn a_dot_on_a_stack_wire_leaves_the_layer_beneath_it_where_it_was() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let upper = editor.create_node_by_name_at(merge_definition(), 20, 10).await; + let lower = editor.create_node_by_name_at(merge_definition(), 20, 16).await; + let network_interface = &mut editor.active_document_mut().network_interface; + network_interface.set_to_node_or_layer(&upper, &[], true); + network_interface.set_to_node_or_layer(&lower, &[], true); + network_interface.create_wire(&OutputConnector::primary_output(lower), &InputConnector::primary_input(upper), &[]); + assert!(network_interface.is_stack(&lower, &[]), "the lower layer should be stacked: fixture is wrong"); + assert!(network_interface.can_bend_wire_into(&InputConnector::primary_input(upper), &[]), "a stack wire should take a dot"); + let lower_position = network_interface.position(&lower, &[]); + + let dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::primary_input(upper), + x: 22, + y: 15, + }) + .await; + + let network_interface = &editor.active_document().network_interface; + assert_eq!(feeding(&editor, upper), Some(OutputConnector::node(dot, 0)), "the dot should feed the upper layer"); + assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(lower, 0)), "the lower layer should feed the dot"); + assert!(network_interface.is_absolute(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked"); + assert_eq!(network_interface.position(&lower, &[]), lower_position, "the lower layer shouldn't move"); + assert_invariants(&editor, "after putting a dot on a stack wire"); +} + #[tokio::test] async fn chain_membership_follows_wiring() { let mut editor = EditorTestUtils::create(); @@ -939,6 +974,7 @@ async fn drag_offsets_do_not_outlive_programmatic_shifts() { .handle_message(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down, rubber_band: false, + glide: false, }) .await; let network_interface = &editor.active_document().network_interface; @@ -948,6 +984,27 @@ async fn drag_offsets_do_not_outlive_programmatic_shifts() { assert_invariants(&editor, "after stack pushes, a delete collapse, and a nudge"); } +#[tokio::test] +async fn each_arrow_key_nudge_is_its_own_undo_step() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; + let start = editor.active_document().network_interface.position(&node, &[]).expect("The node should have a position"); + + editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await; + editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await; + + // Undoing takes back only the last nudge, not the node's creation before them + editor.handle_message(DocumentMessage::Undo).await; + let network_interface = &editor.active_document().network_interface; + let position = network_interface.position(&node, &[]).expect("Undo should keep the node created before the nudges"); + assert_eq!(position.x - start.x, 1, "Undo should take back only the last nudge"); + + assert_invariants(&editor, "after nudging and undoing"); +} + #[tokio::test] async fn signature_edits_keep_parallel_metadata_in_sync() { let mut editor = EditorTestUtils::create(); @@ -1135,9 +1192,11 @@ fn fed_inputs(editor: &EditorTestUtils, output_connector: &OutputConnector, netw } #[tokio::test] -async fn adding_an_import_passthrough_takes_over_the_wires_the_import_fed() { +async fn dragging_a_dot_out_of_an_import_takes_over_the_wires_the_import_fed() { let mut editor = EditorTestUtils::create(); editor.new_document().await; + // TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it + editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await; let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await; let path = vec![merge]; @@ -1146,19 +1205,21 @@ async fn adding_an_import_passthrough_takes_over_the_wires_the_import_fed() { assert!(!fed_before.is_empty(), "Merge's content import should feed its subgraph: fixture is wrong"); editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: merge }).await; - editor.handle_message(NodeGraphMessage::AddImportPassthrough { import_index: 1 }).await; + let import_position = editor + .active_document() + .network_interface + .output_position(&content_import, &path) + .expect("the import should have a position"); + double_press_drag_in_graph(&mut editor, &path, import_position, import_position + DVec2::new(72., 0.)).await; let fed_after = fed_inputs(&editor, &content_import, &path); - let [InputConnector::Node { node_id: passthrough, input_index: 0 }] = fed_after.into_iter().collect::>()[..] else { - panic!("the import should feed only the Passthrough's primary input"); + let [InputConnector::Node { node_id: dot, input_index: 0 }] = fed_after.into_iter().collect::>()[..] else { + panic!("the import should feed only the dot's input"); }; - assert_eq!( - fed_inputs(&editor, &OutputConnector::primary_output(passthrough), &path), - fed_before, - "the Passthrough should feed what the import fed" - ); + assert!(editor.active_document().network_interface.is_redirect_dot(&dot, &path)); + assert_eq!(fed_inputs(&editor, &OutputConnector::primary_output(dot), &path), fed_before, "the dot should feed what the import fed"); - assert_invariants(&editor, "after adding an import passthrough"); + assert_invariants(&editor, "after dragging a dot out of an import"); } #[tokio::test] @@ -1271,7 +1332,7 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima .network_metadata(&path) .and_then(|network_metadata| network_metadata.transient_metadata.wires.borrow().get(&wired_input).cloned()) .and_then(|wire| wire.wire_path_update); - let current_wire = network_interface.wire_path_from_input(&wired_input, GraphWireStyle::default(), false, &path); + let current_wire = network_interface.wire_path_from_input(&wired_input, GraphWireStyle::default(), false, &GlideOffsets::default(), &path); assert_eq!(drawn_wire, current_wire, "the input's wire should be redrawn from its new import"); assert_invariants(&editor, "after adding imports from the empty connectors"); @@ -1332,15 +1393,15 @@ async fn toggle_preview_transitions_with_a_connected_export() { assert_eq!(export_node(network_interface), Some(artboard)); assert_eq!(network_interface.previewing(&[]), Previewing::No); - // Toggling the restore node while previewing promotes it to the export with nothing left to restore + // Toggling the restore node while previewing ends the preview by restoring it network_interface.toggle_preview(node, &[]); network_interface.toggle_preview(artboard, &[]); assert_eq!(export_node(network_interface), Some(artboard)); - assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None }); + assert_eq!(network_interface.previewing(&[]), Previewing::No); - // Toggling it once more ends the preview by disconnecting the export entirely + // Toggling the node already feeding the export changes nothing network_interface.toggle_preview(artboard, &[]); - assert_eq!(export_node(network_interface), None); + assert_eq!(export_node(network_interface), Some(artboard)); assert_eq!(network_interface.previewing(&[]), Previewing::No); assert_invariants(&editor, "after cycling through the preview states"); @@ -1359,30 +1420,9 @@ fn value_input() -> NodeInput { fn wired_interface() -> (NodeNetworkInterface, NodeId, NodeId, NodeId) { let (source, node, consumer) = (NodeId(1), NodeId(2), NodeId(3)); let mut network_interface = NodeNetworkInterface::default(); - network_interface.insert_node( - source, - NodeTemplate { - inputs: vec![value_input()], - ..Default::default() - }, - &[], - ); - network_interface.insert_node( - node, - NodeTemplate { - inputs: vec![value_input(), value_input()], - ..Default::default() - }, - &[], - ); - network_interface.insert_node( - consumer, - NodeTemplate { - inputs: vec![value_input()], - ..Default::default() - }, - &[], - ); + network_interface.insert_node(source, plain_node(1), &[]); + network_interface.insert_node(node, plain_node(2), &[]); + network_interface.insert_node(consumer, plain_node(1), &[]); network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(source, 0), &[]); network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(node, 0), &[]); @@ -1416,9 +1456,8 @@ fn replacing_inputs_breaks_a_chain_only_where_its_link_is_dropped() { network_interface.insert_node( layer, NodeTemplate { - inputs: vec![value_input(); 2], node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::ZERO), - ..Default::default() + ..plain_node(2) }, &[], ); @@ -1533,7 +1572,7 @@ fn rewiring_off_a_vanished_output_delists_it_from_the_wire_cache() { assert_interface_invariants(&network_interface, "after wiring a consumer to the second output"); // Taking that output away leaves the consumer dangling, which a fresh computation still lists - network_interface.replace_implementation(&node, &[], &mut NodeTemplate::default()); + network_interface.replace_implementation(&node, &[], &mut plain_node(0)); restore_output_names(&mut network_interface); assert!( network_interface.outward_wires(&[]).is_some_and(|wires| wires.contains_key(&second_output)), @@ -1742,6 +1781,51 @@ async fn a_wire_dragged_backward_from_the_dimmed_export_connector_adds_an_export assert_invariants(&editor, "after dragging a wire backward from the dimmed export connector"); } +#[tokio::test] +async fn a_wire_dragged_from_the_dimmed_import_connector_onto_empty_space_wires_a_new_import_into_the_node_picked_from_the_menu() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await; + let path = vec![merge]; + editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: merge }).await; + + let network_interface = &editor.active_document().network_interface; + let import_count = network_interface.number_of_imports(&path); + let (new_import_index, empty_import_position) = *network_interface + .empty_import_export_connectors(true, &path) + .last() + .expect("there should be a dimmed connector for adding an import"); + + drag_in_graph(&mut editor, &path, empty_import_position, empty_import_position + DVec2::new(240., 0.)).await; + + let context_menu = editor.active_document().node_graph_handler.context_menu.clone(); + assert!( + matches!(context_menu.map(|menu| menu.context_menu_data), Some(ContextMenuData::CreateNode { compatible_type: None })), + "dropping the wire on empty space should open the node menu without filtering it, as the import has no type yet" + ); + + let fill = NodeId::new(); + editor + .handle_message(NodeGraphMessage::CreateNodeFromContextMenu { + node_id: Some(fill), + node_type: fill_definition(), + xy: Some((10, 0)), + add_transaction: true, + }) + .await; + + let network_interface = &editor.active_document().network_interface; + assert_eq!(network_interface.number_of_imports(&path), import_count + 1, "the import should be added"); + assert_eq!( + network_interface.upstream_output_connector(&InputConnector::node_at_index(fill, 0), &path), + Some(OutputConnector::Import(new_import_index)), + "the added import should be wired into the node picked from the menu" + ); + + assert_invariants(&editor, "after dragging a wire from the dimmed import connector onto empty space"); +} + #[tokio::test] async fn clicking_an_empty_input_without_dragging_leaves_it_and_opens_no_menu() { let mut editor = EditorTestUtils::create(); @@ -1824,3 +1908,1358 @@ async fn clicking_a_connected_input_leaves_it_connected_when_a_later_wire_is_dra "Fill's content should still be wired from the first Rectangle" ); } + +/// An ordinary node with the given number of inputs, since a default template is a Passthrough, which draws as a redirect dot. +fn plain_node(inputs: usize) -> NodeTemplate { + NodeTemplate { + implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { + exports: vec![NodeInput::value(TaggedValue::None, true)], + ..Default::default() + }), + inputs: vec![value_input(); inputs], + output_names: vec![String::new()], + ..Default::default() + } +} + +/// A redirect dot, which a default template with one input is, being a Passthrough. +fn dot_node() -> NodeTemplate { + NodeTemplate { + inputs: vec![value_input()], + ..Default::default() + } +} + +/// A plain source feeding a dot feeding a plain consumer, with the dot as the only thing between them. +fn dotted_wire() -> (NodeNetworkInterface, NodeId, NodeId, NodeId) { + let (source, dot, consumer) = (NodeId(1), NodeId(2), NodeId(3)); + let mut network_interface = NodeNetworkInterface::default(); + network_interface.insert_node(source, plain_node(1), &[]); + network_interface.insert_node(dot, dot_node(), &[]); + network_interface.insert_node(consumer, plain_node(1), &[]); + network_interface.set_input(&InputConnector::node_at_index(dot, 0), NodeInput::node(source, 0), &[]); + network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(dot, 0), &[]); + assert!(network_interface.is_redirect_dot(&dot, &[])); + assert!(!network_interface.is_redirect_dot(&source, &[])); + (network_interface, source, dot, consumer) +} + +#[test] +fn a_dot_on_a_wire_is_kept_and_one_that_lost_its_wire_is_removed() { + let (mut network_interface, source, dot, consumer) = dotted_wire(); + network_interface.remove_orphaned_dots(&[]); + assert!(network_interface.document_node(&dot, &[]).is_some(), "a dot with a wire through it stays"); + + // Taking the wire away from what the dot fed leaves it redirecting nothing + network_interface.disconnect_input(&InputConnector::node_at_index(consumer, 0), &[]); + network_interface.remove_orphaned_dots(&[]); + assert!(network_interface.document_node(&dot, &[]).is_none(), "a dot that nothing takes is removed"); + assert!(network_interface.document_node(&source, &[]).is_some()); + assert_interface_invariants(&network_interface, "after removing an orphaned dot"); +} + +#[test] +fn a_dot_that_nothing_feeds_is_removed() { + let (mut network_interface, _, dot, consumer) = dotted_wire(); + network_interface.disconnect_input(&InputConnector::node_at_index(dot, 0), &[]); + network_interface.remove_orphaned_dots(&[]); + assert!(network_interface.document_node(&dot, &[]).is_none(), "a dot with nothing feeding it is removed"); + assert!( + network_interface.upstream_output_connector(&InputConnector::node_at_index(consumer, 0), &[]).is_none(), + "what the dot fed is left unwired" + ); + assert_interface_invariants(&network_interface, "after removing a dot that lost its input"); +} + +/// A dotted wire with the dot also feeding a second consumer. +fn split_dotted_wire() -> (NodeNetworkInterface, NodeId, NodeId, NodeId) { + let (mut network_interface, source, dot, consumer) = dotted_wire(); + let split_consumer = NodeId(4); + network_interface.insert_node(split_consumer, plain_node(1), &[]); + network_interface.set_input(&InputConnector::node_at_index(split_consumer, 0), NodeInput::node(dot, 0), &[]); + (network_interface, source, dot, consumer) +} + +#[test] +fn a_dot_with_a_remaining_consumer_survives_losing_the_other() { + let (mut network_interface, source, dot, consumer) = split_dotted_wire(); + + network_interface.disconnect_input(&InputConnector::node_at_index(consumer, 0), &[]); + network_interface.remove_orphaned_dots(&[]); + assert!(network_interface.document_node(&dot, &[]).is_some(), "a split point still taking a wire stays"); + assert_eq!( + network_interface.upstream_output_connector(&InputConnector::node_at_index(dot, 0), &[]), + Some(OutputConnector::node(source, 0)) + ); +} + +#[test] +fn picking_up_the_last_wire_through_a_dot_draws_it_from_the_source() { + let (network_interface, source, dot, _) = dotted_wire(); + assert_eq!(network_interface.output_past_sole_dots(OutputConnector::node(dot, 0), &[]), OutputConnector::node(source, 0)); +} + +#[test] +fn picking_up_a_wire_through_a_shared_dot_draws_it_from_the_dot() { + let (network_interface, _, dot, _) = split_dotted_wire(); + assert_eq!( + network_interface.output_past_sole_dots(OutputConnector::node(dot, 0), &[]), + OutputConnector::node(dot, 0), + "a dot with another use is where a wire picked up from it is drawn from" + ); +} + +#[test] +fn copying_keeps_a_dot_only_when_it_bridges_copied_nodes() { + let (network_interface, source, dot, consumer) = dotted_wire(); + + let mut bridged = network_interface.selection_with_bridging_dots(vec![source, consumer], &[]); + bridged.sort(); + assert_eq!(bridged, vec![source, dot, consumer], "the dot between two copied nodes comes along"); + + assert!(network_interface.selection_with_bridging_dots(vec![dot], &[]).is_empty(), "a dot can't be copied on its own"); + assert_eq!( + network_interface.selection_with_bridging_dots(vec![source, dot], &[]), + vec![source], + "a dot reaching no copied node is left out" + ); + assert_eq!( + network_interface.selection_with_bridging_dots(vec![consumer, dot], &[]), + vec![consumer], + "a dot fed by no copied node is left out" + ); +} + +#[tokio::test] +async fn copying_a_layer_and_a_node_it_feeds_through_a_dot_leaves_the_dot_behind() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + // Layer -> dot -> loose node, where the layer is copied apart from the loose node and so can't keep the wire between them + editor.draw_rect(0., 0., 100., 100.).await; + let layer = editor + .active_document() + .network_interface + .upstream_output_connector(&InputConnector::Export(0), &[]) + .and_then(|output| output.node_id()) + .expect("the drawn layer should feed the export"); + let loose = editor.create_node_by_name_at(fill_definition(), 20, 20).await; + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(layer), &InputConnector::primary_input(loose), &[]); + let dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::primary_input(loose), + x: 15, + y: 20, + }) + .await; + assert_eq!(feeding(&editor, loose), Some(OutputConnector::node(dot, 0)), "the dot should feed the loose node: fixture is wrong"); + + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer, dot, loose] }).await; + assert_eq!(editor.active_document().partition_selection().other_nodes, vec![loose]); +} + +#[test] +fn a_dot_is_never_offered_as_a_layer() { + let (network_interface, _, dot, _) = dotted_wire(); + assert!(!network_interface.is_eligible_to_be_layer(&dot, &[])); +} + +#[test] +fn both_wires_of_a_dot_meet_at_its_center() { + let (network_interface, _, dot, _) = dotted_wire(); + let center = network_interface + .input_position(&InputConnector::node_at_index(dot, 0), &[]) + .expect("the dot's input should have a position"); + assert_eq!( + network_interface.output_position(&OutputConnector::node(dot, 0), &[]), + Some(center), + "both wires meet at the dot's center" + ); +} + +#[test] +fn a_dot_in_a_layers_chain_is_left_out_of_what_is_listed_for_it() { + let (layer, upper, dot, lower) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4)); + let mut network_interface = NodeNetworkInterface::default(); + network_interface.insert_node(layer, plain_node(2), &[]); + network_interface.set_to_node_or_layer(&layer, &[], true); + network_interface.insert_node(upper, plain_node(1), &[]); + network_interface.insert_node(dot, dot_node(), &[]); + network_interface.insert_node(lower, plain_node(1), &[]); + network_interface.set_input(&InputConnector::node_at_index(layer, 1), NodeInput::node(upper, 0), &[]); + network_interface.set_input(&InputConnector::node_at_index(upper, 0), NodeInput::node(dot, 0), &[]); + network_interface.set_input(&InputConnector::node_at_index(dot, 0), NodeInput::node(lower, 0), &[]); + assert!(network_interface.is_redirect_dot(&dot, &[])); + + assert_eq!( + network_interface.layer_chain_nodes(layer, &[]), + vec![upper, lower], + "the Layers panel lists the nodes on either side of the dot" + ); + // The node at the upstream end has no exposed primary input, so it is a pinned source rather than reorderable + assert_eq!(network_interface.reorderable_chain(layer, &[]), vec![upper]); + + let (inspector_chain, stack_layer) = crate::messages::portfolio::document::node_graph::node_inspector::input_chain(layer, 1, &network_interface, &[]).expect("a node feeds the layer"); + assert_eq!(inspector_chain, vec![upper, lower], "the Inspector shows a section for each node but not for the dot"); + assert_eq!(stack_layer, None); +} + +#[test] +fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() { + use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler; + + let (source, consumer, dragged) = (NodeId(1), NodeId(2), NodeId(3)); + let mut network_interface = NodeNetworkInterface::default(); + network_interface.insert_node(source, plain_node(1), &[]); + network_interface.insert_node(consumer, plain_node(1), &[]); + let mut dragged_template = plain_node(1); + dragged_template.inputs = vec![NodeInput::value(TaggedValue::None, true)]; + network_interface.insert_node(dragged, dragged_template, &[]); + network_interface.set_absolute_position(&source, IVec2::new(0, 0), &[]); + network_interface.set_absolute_position(&consumer, IVec2::new(20, 0), &[]); + network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(source, 0), &[]); + network_interface + .selected_nodes_mut(&[]) + .expect("the document network has a selection") + .set_selected_nodes(vec![dragged]); + + // Level with the wire between the other two + network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]); + assert_eq!( + NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), + Some((dragged, 0, InputConnector::node_at_index(consumer, 0))), + "the wire it overlaps is the one a drop would insert it onto" + ); + + network_interface.set_absolute_position(&dragged, IVec2::new(8, 10), &[]); + assert_eq!( + NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), + None, + "clear of every wire it previews nothing" + ); + + // With a node already taking its output, a drop would not insert it + network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]); + network_interface.set_input(&InputConnector::node_at_index(source, 0), NodeInput::node(dragged, 0), &[]); + assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), None); +} + +fn passthrough_definition() -> DefinitionIdentifier { + DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) +} + +/// Wires each node into the next one's first exposed input, making a run along the flow. +fn wire_run(editor: &mut EditorTestUtils, nodes: &[NodeId]) { + let network_interface = &mut editor.active_document_mut().network_interface; + for pair in nodes.windows(2) { + let input = network_interface.first_exposed_input(&pair[1], &[]).expect("each node after the first should take a wire"); + network_interface.create_wire(&OutputConnector::primary_output(pair[0]), &input, &[]); + } +} + +/// What feeds the node's first exposed input. +fn feeding(editor: &EditorTestUtils, node_id: NodeId) -> Option { + let network_interface = &editor.active_document().network_interface; + let input = network_interface.first_exposed_input(&node_id, &[])?; + network_interface.upstream_output_connector(&input, &[]) +} + +/// Whether the node is in the document network. +fn exists(editor: &EditorTestUtils, node_id: NodeId) -> bool { + exists_in(editor, node_id, &[]) +} + +/// Whether the node is in the network at `network_path`, asked without logging an error when it isn't. +fn exists_in(editor: &EditorTestUtils, node_id: NodeId, network_path: &[NodeId]) -> bool { + editor + .active_document() + .network_interface + .nested_network(network_path) + .is_some_and(|network| network.nodes.contains_key(&node_id)) +} + +/// Selects the nodes, then presses on the first to drag them all, shakes them loose, and releases them far below, clear of every wire. +async fn shake_nodes(editor: &mut EditorTestUtils, nodes: Vec) { + shake_nodes_in(editor, &[], nodes).await; +} + +/// Shakes the nodes loose like [`shake_nodes`], in the network at `network_path`. +async fn shake_nodes_in(editor: &mut EditorTestUtils, network_path: &[NodeId], nodes: Vec) { + let Some(&pressed) = nodes.first() else { return }; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await; + + // TODO: Remove once aborting a transaction (which shaking does) keeps the edits still uncommitted from before it began, instead of dropping them from the stored history + editor.handle_message(DocumentMessage::AddTransaction).await; + + let network_interface = &editor.active_document().network_interface; + let bounds = network_interface.node_bounding_box(&pressed, network_path).expect("the node should have bounds"); + let node_graph_to_viewport = network_interface + .network_metadata(network_path) + .expect("the network should have metadata") + .persistent_metadata + .navigation_metadata + .node_graph_to_viewport; + let center = node_graph_to_viewport.transform_point2((bounds[0] + bounds[1]) / 2.); + let release = center + node_graph_to_viewport.transform_vector2(DVec2::new(0., 1000.)); + + editor.move_mouse(center.x, center.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor + .handle_message(NodeGraphMessage::PointerDown { + shift_click: false, + control_click: false, + alt_click: false, + right_click: false, + }) + .await; + editor.move_mouse(center.x + 30., center.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.handle_message(NodeGraphMessage::PointerMove { shift: Key::Shift }).await; + editor.handle_message(NodeGraphMessage::ShakeNode).await; + editor.move_mouse(release.x, release.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.handle_message(NodeGraphMessage::PointerMove { shift: Key::Shift }).await; + editor.handle_message(NodeGraphMessage::PointerUp).await; +} + +#[tokio::test] +async fn shaking_a_node_out_of_a_wire_through_a_dot_keeps_the_dot_and_the_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let rectangle = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let fill = editor.create_node_by_name_at(fill_definition(), 10, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await; + wire_run(&mut editor, &[rectangle, fill, dot, consumer]); + assert!( + editor.active_document().network_interface.is_redirect_dot(&dot, &[]), + "the Passthrough should be a redirect dot: fixture is wrong" + ); + + shake_nodes(&mut editor, vec![fill]).await; + + assert!(exists(&editor, dot), "the dot is part of the wire, so shaking a node that fed it leaves it in place"); + assert_eq!( + feeding(&editor, dot), + Some(OutputConnector::node(rectangle, 0)), + "the dot should now be fed by what fed the shaken node" + ); + assert_eq!(feeding(&editor, consumer), Some(OutputConnector::node(dot, 0)), "the dot should still feed what it fed"); + assert_eq!(feeding(&editor, fill), None, "the shaken node should be left unwired"); +} + +#[tokio::test] +async fn shaking_the_node_feeding_a_dot_into_a_layer_keeps_the_dot_and_the_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + // Something -> Node 1 -> Node 2 -> dot -> layer, with the dot inserted on the wire as double-clicking it does + let something = editor.create_node_by_name_at(rectangle_definition(), 2, 10).await; + let first = editor.create_node_by_name_at(fill_definition(), 12, 10).await; + let second = editor.create_node_by_name_at(fill_definition(), 22, 10).await; + let layer = editor.create_node_by_name_at(merge_definition(), 45, 10).await; + editor.active_document_mut().network_interface.set_to_node_or_layer(&layer, &[], true); + wire_run(&mut editor, &[something, first, second]); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(second), &InputConnector::layer_secondary_input(layer), &[]); + let dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::layer_secondary_input(layer), + x: 38, + y: 11, + }) + .await; + assert_eq!( + editor.active_document().network_interface.upstream_output_connector(&InputConnector::layer_secondary_input(layer), &[]), + Some(OutputConnector::node(dot, 0)), + "the dot should feed the layer: fixture is wrong" + ); + + shake_nodes(&mut editor, vec![second]).await; + + assert!(exists(&editor, dot), "the dot should stay on the wire"); + assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(first, 0)), "Node 1 should now feed the dot"); + assert_eq!( + editor.active_document().network_interface.upstream_output_connector(&InputConnector::layer_secondary_input(layer), &[]), + Some(OutputConnector::node(dot, 0)), + "the dot should still feed the layer" + ); + assert_eq!(feeding(&editor, second), None, "Node 2 should be left unwired"); +} + +#[tokio::test] +async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + // Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let shaken = editor + .create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0) + .await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await; + wire_run(&mut editor, &[source, shaken, dot, consumer]); + assert_ne!( + editor.active_document().network_interface.first_exposed_input(&shaken, &[]), + Some(InputConnector::primary_input(shaken)), + "the shaken node's primary input should be hidden: fixture is wrong" + ); + + shake_nodes(&mut editor, vec![shaken]).await; + + assert!(exists(&editor, dot)); + assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(source, 0)), "what fed the shaken node should take over its wire"); + assert_eq!(feeding(&editor, consumer), Some(OutputConnector::node(dot, 0))); +} + +#[tokio::test] +async fn shaking_a_generator_feeding_a_dot_takes_the_dot_with_its_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let generator = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 10, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + wire_run(&mut editor, &[generator, dot, consumer]); + + shake_nodes(&mut editor, vec![generator]).await; + + assert!(!exists(&editor, dot), "with nothing left to feed it, the dot goes along with its wire"); + assert_eq!(feeding(&editor, consumer), None); +} + +#[tokio::test] +async fn shaking_nodes_on_either_side_of_a_dot_keeps_the_wire_between_them() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let upper = editor.create_node_by_name_at(fill_definition(), 10, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; + let lower = editor.create_node_by_name_at(fill_definition(), 30, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 40, 0).await; + wire_run(&mut editor, &[source, upper, dot, lower, consumer]); + + shake_nodes(&mut editor, vec![upper, lower]).await; + + assert_eq!( + feeding(&editor, consumer), + Some(OutputConnector::node(source, 0)), + "the flow should close the gap the shaken nodes leave" + ); + assert_eq!( + feeding(&editor, dot), + Some(OutputConnector::node(upper, 0)), + "the wire between the shaken nodes should come along whole" + ); + assert_eq!(feeding(&editor, lower), Some(OutputConnector::node(dot, 0))); +} + +#[tokio::test] +async fn shaking_a_node_along_with_its_dot_still_hands_the_dot_its_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let shaken = editor.create_node_by_name_at(fill_definition(), 10, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await; + wire_run(&mut editor, &[source, shaken, dot, consumer]); + + shake_nodes(&mut editor, vec![shaken, dot]).await; + + assert_eq!( + feeding(&editor, dot), + Some(OutputConnector::node(source, 0)), + "a dot bends only its own wire, so it stays on it even when selected" + ); + assert_eq!(feeding(&editor, consumer), Some(OutputConnector::node(dot, 0))); + assert_eq!(feeding(&editor, shaken), None); +} + +#[tokio::test] +async fn hiding_an_input_fed_through_a_dot_takes_the_dot_with_its_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 10, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + wire_run(&mut editor, &[source, dot]); + let hidden_input = InputConnector::node_at_index(consumer, 1); + editor.active_document_mut().network_interface.create_wire(&OutputConnector::primary_output(dot), &hidden_input, &[]); + + editor + .handle_message(NodeGraphMessage::ExposeInput { + input_connector: hidden_input, + set_to_exposed: false, + start_transaction: true, + }) + .await; + + assert!(!exists(&editor, dot), "the dot should go with the wire the hidden input was fed by"); + assert!(editor.active_document().network_interface.upstream_output_connector(&hidden_input, &[]).is_none()); +} + +#[tokio::test] +async fn dropping_a_wire_back_on_the_input_it_was_picked_up_from_keeps_its_dot() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 10, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + wire_run(&mut editor, &[source, dot, consumer]); + + let input_position = editor + .active_document() + .network_interface + .input_position(&InputConnector::primary_input(consumer), &[]) + .expect("the input should have a position"); + drag_in_graph(&mut editor, &[], input_position, input_position + DVec2::new(1., 0.)).await; + + assert!(exists(&editor, dot), "a wire put back where it was should keep its dot"); + assert_eq!(feeding(&editor, consumer), Some(OutputConnector::node(dot, 0))); +} + +#[test] +fn a_passthrough_holding_a_value_is_removed_only_once_nothing_takes_it() { + // A Passthrough holding a value rather than a wire, as a migration leaves in place of a removed node + let (value_holder, consumer, other_consumer, unrelated) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4)); + let mut network_interface = NodeNetworkInterface::default(); + network_interface.insert_node(value_holder, dot_node(), &[]); + for node_id in [consumer, other_consumer, unrelated] { + network_interface.insert_node(node_id, plain_node(1), &[]); + } + for node_id in [consumer, other_consumer] { + network_interface.set_input(&InputConnector::node_at_index(node_id, 0), NodeInput::node(value_holder, 0), &[]); + } + assert!(network_interface.is_redirect_dot(&value_holder, &[])); + + network_interface.delete_nodes(vec![unrelated], false, &[]); + assert!(network_interface.document_node(&value_holder, &[]).is_some(), "an edit elsewhere should leave it alone"); + + network_interface.disconnect_input(&InputConnector::node_at_index(other_consumer, 0), &[]); + network_interface.remove_orphaned_dots(&[]); + assert!(network_interface.document_node(&value_holder, &[]).is_some(), "it should stay while it still feeds a node"); + assert_eq!( + network_interface.upstream_output_connector(&InputConnector::node_at_index(consumer, 0), &[]), + Some(OutputConnector::node(value_holder, 0)) + ); + + network_interface.disconnect_input(&InputConnector::node_at_index(consumer, 0), &[]); + network_interface.remove_orphaned_dots(&[]); + assert!(network_interface.document_node(&value_holder, &[]).is_none(), "with nothing taking its output, it bends no wire"); + assert_interface_invariants(&network_interface, "after removing a dot holding a value that nothing takes"); +} + +#[tokio::test] +async fn reordering_a_chain_around_a_dot_takes_the_dot_with_its_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (_, near, far, _, _) = layer_with_chain(&mut editor).await; + let dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::primary_input(near), + x: 21, + y: 11, + }) + .await; + assert_eq!(feeding(&editor, near), Some(OutputConnector::node(dot, 0)), "the dot should feed the near node: fixture is wrong"); + + editor.active_document_mut().network_interface.reorder_chain_nodes(&[far], 0, &[]); + + assert!(!exists(&editor, dot), "the wire the dot bent is gone once its ends trade places"); + assert_eq!(feeding(&editor, far), Some(OutputConnector::node(near, 0)), "the chain should be reordered"); + assert_invariants(&editor, "after reordering a chain around a dot"); +} + +#[tokio::test] +async fn grouping_nodes_on_either_side_of_a_dot_takes_the_dot_inside() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let upper = editor.create_node_by_name_at(fill_definition(), 10, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; + let lower = editor.create_node_by_name_at(fill_definition(), 30, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 40, 0).await; + wire_run(&mut editor, &[source, upper, dot, lower, consumer]); + + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![upper, lower] }).await; + editor.handle_message(NodeGraphMessage::MergeSelectedNodes).await; + + assert!( + !exists(&editor, upper) && !exists(&editor, lower), + "the unselected dot between them shouldn't stop the nodes from being grouped" + ); + assert!(!exists(&editor, dot), "the dot should go inside with the wire it bends"); + let group = feeding(&editor, consumer).and_then(|output| output.node_id()).expect("the group should feed the consumer"); + assert_eq!(feeding(&editor, group), Some(OutputConnector::node(source, 0))); +} + +#[tokio::test] +async fn duplicating_nodes_on_either_side_of_a_dot_in_their_flow_adds_no_dot() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let upper = editor.create_node_by_name_at(fill_definition(), 10, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; + let lower = editor.create_node_by_name_at(fill_definition(), 30, 0).await; + wire_run(&mut editor, &[source, upper, dot, lower]); + + let copies = duplicate_selection(&mut editor, vec![upper, lower]).await; + assert_eq!(copies.len(), 2, "each node should get a copy in the flow, and the dot none"); + + let network_interface = &editor.active_document().network_interface; + let dot_count = network_interface + .document_network() + .nodes + .keys() + .filter(|node_id| network_interface.is_redirect_dot(node_id, &[])) + .count(); + assert_eq!(dot_count, 1, "the copies are spliced into the flow, where the one dot already bends the wire"); + + let upper_copy = feeding(&editor, dot).and_then(|output| output.node_id()).expect("the dot should still be fed"); + assert!(copies.contains(&upper_copy), "the upper node's copy should be spliced in right after it, ahead of the dot"); + assert_eq!(feeding(&editor, upper_copy), Some(OutputConnector::node(upper, 0))); +} + +/// Clicks at `from` and presses there again, then drags that second press of a double-click to `to`, both in the graph space of the network at `path`. +async fn double_press_drag_in_graph(editor: &mut EditorTestUtils, path: &[NodeId], from: DVec2, to: DVec2) { + drag_in_graph(editor, path, from, from).await; + drag_in_graph(editor, path, from, to).await; +} + +/// Clicks twice at a point in the graph space of the document network, with the second press dragged by `second_press_drag`, +/// then double-clicks there, as the double-click arrives after the second release. +async fn double_click_in_graph(editor: &mut EditorTestUtils, point: DVec2, second_press_drag: DVec2) { + double_press_drag_in_graph(editor, &[], point, point + second_press_drag).await; + editor.handle_message(NodeGraphMessage::EnterNestedNetwork).await; +} + +/// The middle of the longest segment of the wire feeding the input, in document network graph space. +fn wire_middle(network_interface: &NodeNetworkInterface, input: InputConnector) -> DVec2 { + use kurbo::ParamCurveArclen; + + let (wire, _, _) = network_interface.vector_wire_from_input(&input, GraphWireStyle::Direct, &[]).expect("the wire should have a path"); + let longest_segment = wire + .segments() + .max_by(|a, b| a.arclen(kurbo::DEFAULT_ACCURACY).total_cmp(&b.arclen(kurbo::DEFAULT_ACCURACY))) + .expect("the wire should have a segment"); + let middle = kurbo::ParamCurve::eval(&longest_segment, 0.5); + DVec2::new(middle.x, middle.y) +} + +/// Double-clicks the middle of the wire feeding the input. +async fn double_click_wire(editor: &mut EditorTestUtils, input: InputConnector) { + let middle = wire_middle(&editor.active_document().network_interface, input); + double_click_in_graph(editor, middle, DVec2::ZERO).await; +} + +/// The grid position of a redirect dot centered on the grid point nearest to the point, as its center sits a grid row below its position. +fn dot_position_centered_near(point: DVec2) -> IVec2 { + (point / GRID_SIZE as f64).round().as_ivec2() - IVec2::Y +} + +#[tokio::test] +async fn double_clicking_a_wire_adds_a_dot_even_after_a_node_was_dragged() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + let elsewhere = editor.create_node_by_name_at(fill_definition(), 0, 20).await; + wire_run(&mut editor, &[source, consumer]); + + // Drag a node unrelated to the wire, which ends the press that moved it + let bounds = editor.active_document().network_interface.node_bounding_box(&elsewhere, &[]).expect("the node should have bounds"); + let center = (bounds[0] + bounds[1]) / 2.; + drag_in_graph(&mut editor, &[], center, center + DVec2::new(72., 0.)).await; + + double_click_wire(&mut editor, InputConnector::primary_input(consumer)).await; + + let dot = feeding(&editor, consumer).and_then(|output| output.node_id()).expect("the consumer should be fed"); + assert!( + editor.active_document().network_interface.is_redirect_dot(&dot, &[]), + "double-clicking the wire should add a dot to it, however long ago a node was dragged" + ); + assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(source, 0))); +} + +#[tokio::test] +async fn a_dot_over_a_node_is_pressed_rather_than_the_node_beneath() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + let beneath = editor.create_node_by_name_at(fill_definition(), 10, 4).await; + wire_run(&mut editor, &[source, consumer]); + + // Centered over the middle of the node beneath + let dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::primary_input(consumer), + x: 12, + y: 5, + }) + .await; + + let network_interface = &editor.active_document().network_interface; + let dot_bounds = network_interface.node_bounding_box(&dot, &[]).expect("the dot should have bounds"); + let dot_center = (dot_bounds[0] + dot_bounds[1]) / 2.; + let beneath_bounds = network_interface.node_bounding_box(&beneath, &[]).expect("the node should have bounds"); + assert!( + beneath_bounds[0].cmple(dot_center).all() && dot_center.cmple(beneath_bounds[1]).all(), + "the dot should sit over the node: fixture is wrong" + ); + + let node_graph_to_viewport = network_interface + .network_metadata(&[]) + .expect("the network should have metadata") + .persistent_metadata + .navigation_metadata + .node_graph_to_viewport; + assert_eq!(network_interface.node_from_click(node_graph_to_viewport.transform_point2(dot_center), &[]), Some(dot)); +} + +#[tokio::test] +async fn double_clicking_a_subgraph_enters_it_unless_that_press_dragged_it() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + // In its node form, so the double-click lands on the body rather than a layer's name + let subgraph = editor.create_node_by_name_at(merge_definition(), 0, 0).await; + editor.active_document_mut().network_interface.set_to_node_or_layer(&subgraph, &[], false); + + let double_click_node = async |editor: &mut EditorTestUtils, second_press_drag: DVec2| { + let bounds = editor.active_document().network_interface.node_bounding_box(&subgraph, &[]).expect("the node should have bounds"); + double_click_in_graph(editor, (bounds[0] + bounds[1]) / 2., second_press_drag).await; + }; + + double_click_node(&mut editor, DVec2::new(72., 0.)).await; + assert!( + editor.active_document().selection_network_path().is_empty(), + "a double-click with a press that moved the node shouldn't enter it" + ); + + double_click_node(&mut editor, DVec2::new(2., 0.)).await; + assert_eq!( + editor.active_document().selection_network_path(), + &[subgraph], + "a double-click that jitters without moving the node should enter it" + ); +} + +#[tokio::test] +async fn double_press_dragging_a_wire_drags_the_dot_it_adds() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + wire_run(&mut editor, &[source, consumer]); + + let middle = wire_middle(&editor.active_document().network_interface, InputConnector::primary_input(consumer)); + double_press_drag_in_graph(&mut editor, &[], middle, middle + DVec2::new(72., 48.)).await; + + let dot = feeding(&editor, consumer).and_then(|output| output.node_id()).expect("the consumer should be fed"); + let network_interface = &editor.active_document().network_interface; + assert!(network_interface.is_redirect_dot(&dot, &[]), "the second press should split the wire with a dot"); + assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(source, 0))); + assert_eq!( + network_interface.position(&dot, &[]), + Some(dot_position_centered_near(middle) + IVec2::new(3, 2)), + "the press should go on to drag the dot it added" + ); + + assert_invariants(&editor, "after dragging a new dot off a wire"); +} + +#[tokio::test] +async fn dragging_a_dot_out_of_an_output_fans_its_wires_out_from_the_dot() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let upper = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + let lower = editor.create_node_by_name_at(fill_definition(), 20, 10).await; + let source_output = OutputConnector::node(source, 0); + for consumer in [upper, lower] { + editor + .active_document_mut() + .network_interface + .create_wire(&source_output, &InputConnector::primary_input(consumer), &[]); + } + + let output_position = editor + .active_document() + .network_interface + .output_position(&source_output, &[]) + .expect("the output should have a position"); + double_press_drag_in_graph(&mut editor, &[], output_position, output_position + DVec2::new(96., 0.)).await; + + let [InputConnector::Node { node_id: dot, input_index: 0 }] = fed_inputs(&editor, &source_output, &[]).into_iter().collect::>()[..] else { + panic!("the output should feed only the dot's input"); + }; + let network_interface = &editor.active_document().network_interface; + assert!(network_interface.is_redirect_dot(&dot, &[])); + assert_eq!( + fed_inputs(&editor, &OutputConnector::primary_output(dot), &[]), + HashSet::from([InputConnector::primary_input(upper), InputConnector::primary_input(lower)]), + "the wires the output fed should fan out from the dot" + ); + assert_eq!(network_interface.position(&dot, &[]), Some(dot_position_centered_near(output_position) + IVec2::new(4, 0))); + + assert_invariants(&editor, "after dragging a dot out of an output"); +} + +#[tokio::test] +async fn dragging_a_dot_out_of_an_export_runs_its_wire_through_the_dot() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await; + let path = vec![merge]; + editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: merge }).await; + + let export = InputConnector::Export(0); + let network_interface = &editor.active_document().network_interface; + let upstream = network_interface.upstream_output_connector(&export, &path).expect("Merge's export should be fed by a node inside it"); + let export_position = network_interface.input_position(&export, &path).expect("the export should have a position"); + double_press_drag_in_graph(&mut editor, &path, export_position, export_position - DVec2::new(72., 0.)).await; + + let network_interface = &editor.active_document().network_interface; + let dot = network_interface + .upstream_output_connector(&export, &path) + .and_then(|output| output.node_id()) + .expect("the export should be fed by a node"); + assert!(network_interface.is_redirect_dot(&dot, &path), "a dot should be dragged out of the export"); + assert_eq!(network_interface.upstream_output_connector(&InputConnector::primary_input(dot), &path), Some(upstream)); + + assert_invariants(&editor, "after dragging a dot out of an export"); +} + +#[tokio::test] +async fn double_clicking_a_connector_without_dragging_leaves_its_wires_alone() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + wire_run(&mut editor, &[source, consumer]); + let node_count = editor.active_document().network_interface.document_network().nodes.len(); + + let output_position = editor + .active_document() + .network_interface + .output_position(&OutputConnector::node(source, 0), &[]) + .expect("the output should have a position"); + double_click_in_graph(&mut editor, output_position, DVec2::ZERO).await; + + assert_eq!(editor.active_document().network_interface.document_network().nodes.len(), node_count, "no dot should be added"); + assert_eq!(feeding(&editor, consumer), Some(OutputConnector::node(source, 0))); +} + +#[tokio::test] +async fn double_clicking_a_dot_dissolves_it_into_the_wires_it_bent() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 12, 0).await; + let upper = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + let lower = editor.create_node_by_name_at(fill_definition(), 20, 10).await; + wire_run(&mut editor, &[source, dot, upper]); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(dot), &InputConnector::primary_input(lower), &[]); + + let bounds = editor.active_document().network_interface.node_bounding_box(&dot, &[]).expect("the dot should have bounds"); + double_click_in_graph(&mut editor, (bounds[0] + bounds[1]) / 2., DVec2::ZERO).await; + + assert!(!exists(&editor, dot), "double-clicking the dot should remove it"); + assert_eq!( + fed_inputs(&editor, &OutputConnector::node(source, 0), &[]), + HashSet::from([InputConnector::primary_input(upper), InputConnector::primary_input(lower)]), + "the wires the dot bent should run straight from what fed it" + ); + + assert_invariants(&editor, "after double-clicking a dot"); +} + +#[tokio::test] +async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; + let path = [subgraph]; + editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await; + + // The grid columns of the imports and exports + let import_export_columns = |editor: &EditorTestUtils| { + let (import, export) = editor + .active_document() + .network_interface + .import_export_position(&path) + .expect("the imports and exports should have positions"); + (import.x / GRID_SIZE as i32, export.x / GRID_SIZE as i32) + }; + let (import_column, export_column) = import_export_columns(&editor); + + let beside_import = editor.create_node_by_name_at(passthrough_definition(), import_column + 1, 0).await; + let beside_export = editor.create_node_by_name_at(passthrough_definition(), export_column - 1, 0).await; + assert_eq!( + import_export_columns(&editor), + (import_column, export_column), + "dots a grid cell away shouldn't push the imports or exports" + ); + + editor.active_document_mut().network_interface.delete_nodes(vec![beside_import, beside_export], false, &path); + editor.create_node_by_name_at(passthrough_definition(), import_column, 0).await; + editor.create_node_by_name_at(passthrough_definition(), export_column, 0).await; + assert_eq!( + import_export_columns(&editor), + (import_column - 1, export_column + 1), + "dots right at the imports and exports should push them a grid cell away" + ); +} + +#[tokio::test] +async fn previewing_keeps_the_dot_it_will_restore_the_export_to_and_outlasts_removing_other_dots() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let root = editor.create_node_by_name_at(fill_definition(), 0, 0).await; + let previewed = editor.create_node_by_name_at(fill_definition(), 0, 10).await; + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await; + let other_dot = editor.create_node_by_name_at(passthrough_definition(), 10, 20).await; + let consumer = editor.create_node_by_name_at(fill_definition(), 20, 20).await; + wire_run(&mut editor, &[source, other_dot, consumer]); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(root), &InputConnector::Export(0), &[]); + let export_dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: export_dot, + input_connector: InputConnector::Export(0), + x: 20, + y: 1, + }) + .await; + + editor.handle_message(NodeGraphMessage::TogglePreview { node_id: previewed }).await; + let network_interface = &mut editor.active_document_mut().network_interface; + network_interface.disconnect_input(&InputConnector::primary_input(consumer), &[]); + network_interface.remove_orphaned_dots(&[]); + + assert!(!exists(&editor, other_dot), "the dot left with nothing to feed should be removed"); + assert!(exists(&editor, export_dot), "the dot the preview will restore the export to should stay"); + assert!( + matches!(editor.active_document().network_interface.previewing(&[]), Previewing::Yes { .. }), + "removing a dot outside the preview should leave it running" + ); + + editor.handle_message(NodeGraphMessage::TogglePreview { node_id: previewed }).await; + assert_eq!( + editor.active_document().network_interface.upstream_output_connector(&InputConnector::Export(0), &[]), + Some(OutputConnector::node(export_dot, 0)), + "ending the preview should restore the export to the dot" + ); + assert_invariants(&editor, "after previewing past a dot on the export's wire"); +} + +#[tokio::test] +async fn removing_an_import_removes_the_dot_that_fed_its_input_on_the_subgraph_node() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let merge = editor.create_node_by_name_at(merge_definition(), 20, 0).await; + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let dot = editor.create_node_by_name_at(passthrough_definition(), 10, 0).await; + wire_run(&mut editor, &[source, dot]); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(dot), &InputConnector::node_at_index(merge, 1), &[]); + + editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: merge }).await; + editor.handle_message(NodeGraphMessage::RemoveImport { import_index: 1 }).await; + + assert!(!exists(&editor, dot), "the dot fed only the removed input, so it should go with it"); + assert_invariants(&editor, "after removing an import fed through a dot"); +} + +#[tokio::test] +async fn a_new_layer_goes_beneath_a_dot_on_the_wire_into_the_export() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + editor.draw_rect(0., 0., 100., 100.).await; + let top_layer = editor + .active_document() + .network_interface + .upstream_output_connector(&InputConnector::Export(0), &[]) + .and_then(|output| output.node_id()) + .expect("the drawn layer should feed the export"); + assert!( + editor.active_document().network_interface.can_bend_wire_into(&InputConnector::Export(0), &[]), + "the wire from the top layer into the export should take a dot" + ); + + let dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::Export(0), + x: 20, + y: -3, + }) + .await; + editor.draw_rect(200., 0., 300., 100.).await; + + let network_interface = &editor.active_document().network_interface; + assert_eq!( + network_interface.upstream_output_connector(&InputConnector::Export(0), &[]), + Some(OutputConnector::node(dot, 0)), + "the dot should stay on the wire into the export" + ); + let new_layer = feeding(&editor, dot).and_then(|output| output.node_id()).expect("the dot should still be fed"); + assert!(new_layer != top_layer && network_interface.is_layer(&new_layer, &[]), "the new layer should go beneath the dot"); + assert_eq!( + network_interface.upstream_output_connector(&InputConnector::primary_input(new_layer), &[]), + Some(OutputConnector::node(top_layer, 0)), + "the new layer should stack straight onto the old top layer, with no dot on the stack wire between them" + ); + assert_eq!(LayerNodeIdentifier::ROOT_PARENT.children(network_interface.document_metadata()).count(), 2); + + assert_invariants(&editor, "after adding a layer beneath a dot on the export's wire"); +} + +#[tokio::test] +async fn chain_nodes_pasted_loose_keep_the_wire_and_dot_between_them() { + for select_the_dot in [false, true] { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (_, near, far, _, _) = layer_with_chain(&mut editor).await; + let dot = NodeId::new(); + editor + .handle_message(NodeGraphMessage::InsertDotOnWire { + node_id: dot, + input_connector: InputConnector::primary_input(near), + x: 20, + y: 11, + }) + .await; + + let selection = if select_the_dot { vec![far, dot, near] } else { vec![far, near] }; + let clipboard = copy_in_graph(&mut editor, selection).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: Vec::new() }).await; + let pasted = paste(&mut editor, clipboard).await; + + let network_interface = &editor.active_document().network_interface; + assert_eq!(pasted.len(), 3, "both nodes and the dot between them should be pasted"); + let dot_copy = *pasted.iter().find(|node_id| network_interface.is_redirect_dot(node_id, &[])).expect("the dot should come along"); + let far_copy = feeding(&editor, dot_copy).and_then(|output| output.node_id()).expect("the copied dot should be fed"); + let near_copy = *pasted + .iter() + .find(|node_id| feeding(&editor, **node_id) == Some(OutputConnector::node(dot_copy, 0))) + .expect("the copied dot should feed a copy"); + assert!(pasted.contains(&far_copy) && far_copy != far, "the copied dot should be fed by the far node's copy"); + assert_ne!(near_copy, near); + + assert_invariants(&editor, "after pasting chain nodes loose"); + } +} + +#[tokio::test] +async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + let upper = editor.create_node_by_name_at(fill_definition(), 20, 0).await; + let lower = editor.create_node_by_name_at(fill_definition(), 20, 10).await; + wire_run(&mut editor, &[source, upper]); + + let network_interface = &editor.active_document().network_interface; + let output_position = network_interface.output_position(&OutputConnector::node(source, 0), &[]).expect("the output should have a position"); + let lower_input_position = network_interface.input_position(&InputConnector::primary_input(lower), &[]).expect("the input should have a position"); + + // The first press drags a wire away to empty space, so it isn't a click that a second press could turn into a double-click + drag_in_graph(&mut editor, &[], output_position, output_position + DVec2::new(0., 480.)).await; + drag_in_graph(&mut editor, &[], output_position, lower_input_position).await; + + assert_eq!(feeding(&editor, lower), Some(OutputConnector::node(source, 0)), "the second press should drag a wire, not a dot"); + assert_eq!(feeding(&editor, upper), Some(OutputConnector::node(source, 0))); +} + +/// Opens a new subgraph with one node inside, which is all that lies between its import and its export. +async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) { + // TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it + editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await; + + let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; + editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await; + editor.handle_message(NodeGraphMessage::AddImport).await; + editor.handle_message(NodeGraphMessage::AddPrimaryExport).await; + + let node = editor.create_node_by_name_at(fill_definition(), 10, 0).await; + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::Import(0), + input_connector: InputConnector::primary_input(node), + }) + .await; + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::primary_output(node), + input_connector: InputConnector::Export(0), + }) + .await; + + let network_interface = &editor.active_document().network_interface; + assert_eq!( + network_interface.upstream_output_connector(&InputConnector::Export(0), &[subgraph]), + Some(OutputConnector::primary_output(node)), + "the node should feed the subgraph's export: fixture is wrong" + ); + assert_eq!( + network_interface.upstream_output_connector(&InputConnector::primary_input(node), &[subgraph]), + Some(OutputConnector::Import(0)), + "the subgraph's import should feed the node: fixture is wrong" + ); + + (subgraph, node) +} + +/// The redirect dot carrying the subgraph's import out its export, if that's what joins them. +fn dot_between_import_and_export(editor: &EditorTestUtils, subgraph: NodeId) -> Option { + let network_interface = &editor.active_document().network_interface; + let path = [subgraph]; + let dot = network_interface.upstream_output_connector(&InputConnector::Export(0), &path)?.node_id()?; + + let joins_them = network_interface.is_redirect_dot(&dot, &path) && network_interface.upstream_output_connector(&InputConnector::primary_input(dot), &path) == Some(OutputConnector::Import(0)); + joins_them.then_some(dot) +} + +#[tokio::test] +async fn deleting_the_only_node_between_an_import_and_export_leaves_a_dot_joining_them() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (subgraph, node) = subgraph_holding_one_node(&mut editor).await; + + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; + editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await; + + assert!(!exists_in(&editor, node, &[subgraph]), "the node should be deleted"); + assert!( + dot_between_import_and_export(&editor, subgraph).is_some(), + "deleting should dissolve the node from the flow as shaking does, keeping the import wired out through a dot" + ); +} + +#[tokio::test] +async fn deleting_the_dot_between_an_import_and_export_puts_a_new_one_in_its_place() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (subgraph, node) = subgraph_holding_one_node(&mut editor).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; + editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await; + let dot = dot_between_import_and_export(&editor, subgraph).expect("deleting the node should have left a dot"); + + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![dot] }).await; + editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await; + + assert!(!exists_in(&editor, dot, &[subgraph]), "the dot should be deleted"); + let replacement = dot_between_import_and_export(&editor, subgraph).expect("a network needs a node to carry its import out, so a new dot should take the old one's place"); + assert_ne!(replacement, dot); +} + +/// Wires the subgraph's one node into a second export too, so the node carries its import out of both exports. +async fn feed_a_second_export(editor: &mut EditorTestUtils, node: NodeId) { + editor.handle_message(NodeGraphMessage::AddSecondaryExport).await; + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::primary_output(node), + input_connector: InputConnector::Export(1), + }) + .await; +} + +/// The redirect dot carrying the subgraph's import out of both its exports, if one dot fans out to them and it's the only dot there. +fn one_dot_fanning_out_to_both_exports(editor: &EditorTestUtils, subgraph: NodeId) -> Option { + let dot = dot_between_import_and_export(editor, subgraph)?; + let network_interface = &editor.active_document().network_interface; + let path = [subgraph]; + + let feeds_both = network_interface.upstream_output_connector(&InputConnector::Export(1), &path) == Some(OutputConnector::node(dot, 0)); + let dot_count = network_interface + .nested_network(&path)? + .nodes + .keys() + .filter(|node_id| network_interface.is_redirect_dot(node_id, &path)) + .count(); + (feeds_both && dot_count == 1).then_some(dot) +} + +#[tokio::test] +async fn deleting_what_joins_an_import_to_two_exports_leaves_one_dot_fanning_out_to_both() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (subgraph, node) = subgraph_holding_one_node(&mut editor).await; + feed_a_second_export(&mut editor, node).await; + + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; + editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await; + let dot = one_dot_fanning_out_to_both_exports(&editor, subgraph).expect("deleting the node should leave one dot feeding both exports"); + + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![dot] }).await; + editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await; + let replacement = one_dot_fanning_out_to_both_exports(&editor, subgraph).expect("deleting the dot should put one new dot in its place, still feeding both exports"); + assert_ne!(replacement, dot); +} + +#[tokio::test] +async fn shaking_out_what_joins_an_import_to_two_exports_leaves_one_dot_fanning_out_to_both() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (subgraph, node) = subgraph_holding_one_node(&mut editor).await; + feed_a_second_export(&mut editor, node).await; + + shake_nodes_in(&mut editor, &[subgraph], vec![node]).await; + + assert!( + one_dot_fanning_out_to_both_exports(&editor, subgraph).is_some(), + "shaking the node out should leave one dot feeding both exports" + ); +} + +#[test] +fn a_wire_is_found_near_its_path_but_not_away_from_it() { + let (source, consumer) = (NodeId(1), NodeId(2)); + let mut network_interface = NodeNetworkInterface::default(); + network_interface.insert_node(source, plain_node(1), &[]); + network_interface.insert_node(consumer, plain_node(1), &[]); + network_interface.set_absolute_position(&source, IVec2::new(0, 0), &[]); + network_interface.set_absolute_position(&consumer, IVec2::new(12, 6), &[]); + network_interface.set_input(&InputConnector::node_at_index(consumer, 0), NodeInput::node(source, 0), &[]); + + let input = InputConnector::node_at_index(consumer, 0); + let on_wire = wire_middle(&network_interface, input); + + assert_eq!(network_interface.wire_input_from_point(on_wire, 6., GraphWireStyle::Direct, &[]), Some(input)); + assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., GraphWireStyle::Direct, &[]), None); +} + +#[tokio::test] +async fn a_dragged_layer_keeps_its_wires_where_it_is_drawn_in_the_frame_it_moves() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, ..) = layer_with_chain(&mut editor).await; + editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await; + + let left_input = InputConnector::layer_secondary_input(layer); + let network_interface = &editor.active_document().network_interface; + let wire_before = network_interface.wire_path_from_input(&left_input, GraphWireStyle::default(), false, &GlideOffsets::default(), &[]); + let bounds = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds"); + let press = DVec2::new(bounds[1].x - 30., (bounds[0].y + bounds[1].y) / 2.); + let node_graph_to_viewport = network_interface + .network_metadata(&[]) + .expect("the network should have metadata") + .persistent_metadata + .navigation_metadata + .node_graph_to_viewport; + + let pressed = node_graph_to_viewport.transform_point2(press); + editor.move_mouse(pressed.x, pressed.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor + .handle_message(NodeGraphMessage::PointerDown { + shift_click: false, + control_click: false, + alt_click: false, + right_click: false, + }) + .await; + + // One grid cell right, through the input preprocessor so the frontend messages of the move itself are returned + let moved = node_graph_to_viewport.transform_point2(press + DVec2::new(GRID_SIZE as f64, 0.)); + let editor_mouse_state = EditorPointerState { + editor_position: moved, + mouse_keys: MouseKeys::LEFT, + ..Default::default() + }; + let messages = editor + .handle_message(InputPreprocessorMessage::PointerMove { + editor_mouse_state, + modifier_keys: ModifierKeys::empty(), + }) + .await; + + // Still drawn a whole cell back as it starts gliding, so the last wire sent to its left input is the one from before the move + let last_wire_sent = messages + .into_iter() + .filter_map(|message| match message { + FrontendMessage::UpdateNodeGraphWires { wires } => Some(wires), + _ => None, + }) + .flatten() + .rfind(|wire| wire.id == layer && wire.input_index == 1) + .and_then(|wire| wire.wire_path_update); + assert_eq!(last_wire_sent.map(|wire| wire.path_string), wire_before.map(|wire| wire.path_string)); +} + +/// Nudges the only node of a new document while its graph is open, so the node starts gliding into the cell it moved to. +async fn gliding_nudged_node(editor: &mut EditorTestUtils) -> NodeId { + editor.new_document().await; + let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; + editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await; + assert!( + !editor.active_document().network_interface.glide_offsets(&[]).is_empty(), + "the nudged node should be gliding: fixture is wrong" + ); + node +} + +#[tokio::test] +async fn redoing_a_nudge_undone_while_it_glides_leaves_nothing_gliding() { + let mut editor = EditorTestUtils::create(); + // Undone from the history's own snapshots, rather than the storage rebuilt afresh + editor.editor.handle_message(PreferencesMessage::SaveAsGdd { enabled: false }); + gliding_nudged_node(&mut editor).await; + + editor.handle_message(DocumentMessage::Undo).await; + editor.handle_message(DocumentMessage::Redo).await; + + assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty()); +} + +#[tokio::test] +async fn entering_a_node_while_its_network_glides_settles_it() { + let mut editor = EditorTestUtils::create(); + gliding_nudged_node(&mut editor).await; + let merge = editor.create_node_by_name_at(merge_definition(), 20, 0).await; + + editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: merge }).await; + + assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty()); +} diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs index 1f9b986715..0debcf67d4 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs @@ -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)?; } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs index 9bdf5c3a50..a6c32b2c48 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/geometry.rs @@ -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.); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs index 4c80f08d28..5ec8c3a2fd 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/hit_tests.rs @@ -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::>(); 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::>(); - // 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 { @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 { 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::>() .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 { + /// 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 { 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::>(); 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()) }) } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/layout.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/layout.rs index 228f0f7441..a32ff34096 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/layout.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/layout.rs @@ -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::>() { - 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::>() { 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 { - 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 { 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 } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs index dbc373783c..8f81805f3e 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs @@ -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::>>(); + let center = match output_center.zip(input_centers) { + Some((output_center, input_centers)) => { + let inputs_center = input_centers.iter().sum::() / 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::>(); + 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, 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, 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 { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs index 2d50f947da..fb5ad08c50 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/queries.rs @@ -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 { + 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 { + 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, network_path: &[NodeId]) -> Vec { + let mut kept = selected.into_iter().filter(|node_id| !self.is_redirect_dot(node_id, network_path)).collect::>(); + let Some(network) = self.nested_network(network_path) else { return kept }; + let kept_set = kept.iter().copied().collect::>(); + + let dots = network.nodes.keys().copied().filter(|node_id| self.is_redirect_dot(node_id, network_path)).collect::>(); + 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, network_path: &'a [NodeId]) -> impl Iterator + '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() } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs index 8d435b9396..e9d5643f19 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/resolved_types.rs @@ -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>; + +/// The conversions of every `input_adapter` in the registry. +static ADAPTER_CONVERSIONS: Lazy> = Lazy::new(|| { + let mut adapter_conversions: HashMap = 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>>> = 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> = 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 = inputs_from_import - .iter() - .map(|input_connector| self.potential_valid_input_types(input_connector, &nested_path).into_iter().collect::>()) - .fold(None, |acc: Option>, set| match acc { - Some(acc_set) => Some(acc_set.intersection(&set).cloned().collect()), - None => Some(set), - }) - .unwrap_or_default(); - - intersection.into_iter().collect::>() + 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 bool> { + let accepts_here: Box 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::>(); + + 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::>(); + + 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::>(); + + 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::>(); + 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> { + 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 { + 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::>(); + valid_types.filter(|valid_type| fed_acceptors.iter().all(|accepts| accepts(valid_type))).collect::>() + } + None => valid_types.collect(), + } + }) + .fold(None, |acc: Option>, 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 { 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::>()) - .fold(None, |acc: Option>, set| match acc { - Some(acc_set) => Some(acc_set.intersection(&set).cloned().collect()), - None => Some(set), - }) - .unwrap_or_default(); - - intersection.into_iter().collect::>() + 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::>(); + 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"); } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs index f75929b676..b5ad0a23f3 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs @@ -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; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs index c32b54537c..2de9282423 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store/mod.rs @@ -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. diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs index 077bc6985f..ac69f4d841 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs @@ -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 { + pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option { 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 { + pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option { 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) { + pub fn update_vector_modify(&mut self, new_vector_modify: HashMap) { 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>) { + pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap>>) { self.document_metadata.mark_changed(); self.document_metadata.layer_vector_data = new_layer_vector_data; } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs index ea551eb932..3d572f5f8e 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs @@ -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 { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs index 9217f69c1c..e8ce2f185a 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/types.rs @@ -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) -> 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 { @@ -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 { + 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 { + 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>, /// 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, /// Cache for all outward wire connections pub(crate) outward_wires: TransientCache>>, /// All export connector click targets @@ -532,6 +606,82 @@ pub struct NodeNetworkTransientMetadata { pub(crate) wires: std::cell::RefCell>, /// 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>, + /// 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, +} + +/// 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, + 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"); } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/validation.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/validation.rs index 4a123e3cad..2de357c113 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/validation.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/validation.rs @@ -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) { + 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, violations: &mut Vec) { let Some(network) = self.nested_network(path) else { return }; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs index c1570533bf..7aedef29ff 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/view.rs @@ -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 { + 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 { + 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 { 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 { diff --git a/editor/src/messages/portfolio/document/utility_types/nodes.rs b/editor/src/messages/portfolio/document/utility_types/nodes.rs index 97c385f5b6..5d182d3e5a 100644 --- a/editor/src/messages/portfolio/document/utility_types/nodes.rs +++ b/editor/src/messages/portfolio/document/utility_types/nodes.rs @@ -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))] diff --git a/editor/src/messages/portfolio/document/utility_types/transformation.rs b/editor/src/messages/portfolio/document/utility_types/transformation.rs index 36bd24b4ee..ad0b79b446 100644 --- a/editor/src/messages/portfolio/document/utility_types/transformation.rs +++ b/editor/src/messages/portfolio/document/utility_types/transformation.rs @@ -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 })) }) diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 6511f4d7d4..60c2cae3cf 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -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, usize, NodeInput)> { + type Location = (Vec, 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> = HashMap::new(); + let mut turned_by: Vec<(Location, HashSet)> = 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> = 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 = 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 = 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)> { + // 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| 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| 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::(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| { + 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::>(), ["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())); + } } diff --git a/editor/src/messages/portfolio/portfolio_message.rs b/editor/src/messages/portfolio/portfolio_message.rs index 0f7cb3915c..d65451beab 100644 --- a/editor/src/messages/portfolio/portfolio_message.rs +++ b/editor/src/messages/portfolio/portfolio_message.rs @@ -149,6 +149,7 @@ pub enum PortfolioMessage { ignore_hash: bool, }, SubmitEyedropperPreviewRender, + PollNodeGraphEvaluation, ToggleResetNodesToDefinitionsOnOpen, ToggleRulers, UpdateDocumentWidgets, diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index 5ae23bea9d..e843ab635a 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -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, loading_documents: HashMap, @@ -69,6 +71,7 @@ pub struct PortfolioMessageHandler { impl MessageHandler> for PortfolioMessageHandler { fn process_message(&mut self, message: PortfolioMessage, responses: &mut VecDeque, context: PortfolioMessageContext) { let PortfolioMessageContext { + environment, ipp, preferences, animation, @@ -88,6 +91,7 @@ impl MessageHandler> for Portfolio { let document_inputs = DocumentMessageContext { document_id, + environment, ipp, fonts: &self.fonts, executor: &mut self.executor, @@ -143,9 +147,7 @@ impl MessageHandler> 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> 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> 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> 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> 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> 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) { - self.document_store = DocumentStoreHandle::new(store); + pub fn new(executor: NodeGraphExecutor, document_store: Arc) -> 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) -> 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#" - - - The document cannot render in its current state. - Undo to go back, if available, or check for error details - by clicking the Node Graph button up at the top right. - /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 { if let Some(document) = self.documents.get(&document_id) { Some(DocumentInfo { diff --git a/editor/src/messages/prelude.rs b/editor/src/messages/prelude.rs index a4f555dc20..766da5b616 100644 --- a/editor/src/messages/prelude.rs +++ b/editor/src/messages/prelude.rs @@ -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}; diff --git a/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs b/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs index 962e9a5d06..c7a823c50e 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs @@ -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) { + pub fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { 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) { + pub fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { 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); } } diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs index fa507e5cab..5aad44524a 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs @@ -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, 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>, 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, drag_start: DVec2) { + pub fn update_inner_radius(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque, 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 { + 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()) } diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs index 4b00e73e5c..b4a79c0429 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs @@ -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 = 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, drag_start: DVec2) { + pub fn update_inner_radius(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque, 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); } diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs index 601c64efd2..a2053fe1af 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs @@ -1,14 +1,15 @@ -use crate::consts::{COLOR_OVERLAY_RED, POINT_RADIUS_HANDLE_SNAP_THRESHOLD}; +use crate::consts::{COLOR_OVERLAY_RED, SPIRAL_END_HOVER_RADIUS}; 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::Responses; -use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage}; +use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::shape_editor::ShapeState; -use crate::messages::tool::common_functionality::shapes::shape_utility::extract_spiral_parameters; +use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_spiral_parameters, pointer_travel_per_radian}; use crate::messages::tool::common_functionality::shapes::spiral_shape::calculate_spiral_endpoints; +use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate}; use glam::DVec2; use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; @@ -103,9 +104,9 @@ impl SpiralTurns { let end_point = viewport.transform_point2(spiral_point(turns * TAU + start_angle.to_radians(), inner_radius, growth_factor, spiral_type)); let start_point = viewport.transform_point2(spiral_point(0. + start_angle.to_radians(), inner_radius, growth_factor, spiral_type)); - if mouse_position.distance(end_point) < POINT_RADIUS_HANDLE_SNAP_THRESHOLD { + if mouse_position.distance(end_point) < SPIRAL_END_HOVER_RADIUS { self.store_initial_parameters(layer, inner_radius, outer_radius, turns, start_angle, mouse_position, GizmoType::End, spiral_type); - } else if mouse_position.distance(start_point) < POINT_RADIUS_HANDLE_SNAP_THRESHOLD { + } else if mouse_position.distance(start_point) < SPIRAL_END_HOVER_RADIUS { self.store_initial_parameters(layer, inner_radius, outer_radius, turns, start_angle, mouse_position, GizmoType::Start, spiral_type); } } @@ -141,9 +142,65 @@ impl SpiralTurns { } } - pub fn update_number_of_turns(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + /// How much the outer radius grows as the spiral gains a number of turns, keeping its growth and tightness the same. + fn outer_radius_change(&self, turns_gained: f64) -> f64 { + match self.spiral_type { + SpiralType::Archimedean => turns_gained * self.initial_growth_factor * TAU, + SpiralType::Logarithmic => self.initial_outer_radius * ((self.initial_growth_factor * TAU * turns_gained).exp() - 1.), + } + } + + /// The start angle in degrees, the turns, and the outer radius that dragging the start writes for a number of turns, which turns the start along as turns come off. + fn start_dragged_to(&self, turns: f64) -> (f64, f64, f64) { + let turns_taken_off = self.initial_turns - turns; + let outer_radius = (self.initial_outer_radius + self.outer_radius_change(-turns_taken_off)).max(0.1); + (self.initial_start_angle + turns_taken_off * 360., turns.max(0.5), outer_radius) + } + + /// Snaps a number of turns to whole and half turns, judged by how far the pointer travels around the center on screen. + fn snap_turns(&self, view: SnapView, snap_session: &mut SnapSession, layer: LayerNodeIdentifier, free_turns: f64) -> f64 { + let document = view.document; + let Some((spiral_type, start_angle, inner_radius, outer_radius, turns, _)) = extract_spiral_parameters(layer, document) else { + return free_turns; + }; + if !free_turns.is_finite() { + return free_turns; + } + + // The turns follow the pointer's angle in the spiral's own space, which a stretched spiral spaces unevenly on screen + let layer_to_viewport = document.metadata().transform_to_viewport(layer); + let on_screen_per_turn = TAU * pointer_travel_per_radian(layer_to_viewport, view.input.mouse.position); + + let growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type); + let viewport_to_document = document.metadata().document_to_viewport.inverse(); + let position_of = |turns_landed_on: f64| { + let (angle, growth_factor) = match self.gizmo_type { + GizmoType::Start => { + let (start_angle, turns, outer_radius) = self.start_dragged_to(turns_landed_on); + (start_angle.to_radians(), calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type)) + } + _ => (turns_landed_on * TAU + start_angle.to_radians(), growth_factor), + }; + viewport_to_document.transform_point2(layer_to_viewport.transform_point2(spiral_point(angle, inner_radius, growth_factor, spiral_type))) + }; + + // The whole and half turns around the asked-for number, counted in half turns + let nearest_half_turns = (free_turns * 2.).round() as i64; + let candidates: Vec = (nearest_half_turns.saturating_sub(2).max(1)..=nearest_half_turns.saturating_add(2)) + .map(|half_turns| ValueCandidate { + value: half_turns as f64 / 2., + kind: if half_turns % 2 == 0 { Kind::WholeValue } else { Kind::AngleStep }, + identity: half_turns as u64, + }) + .collect(); + + snap_session.snap_value(view, position_of, free_turns, on_screen_per_turn, &candidates) + } + + pub fn update_number_of_turns(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { use graphene_std::vector::generator_nodes::spiral::*; + let SnapView { document, input, .. } = view; let Some(layer) = self.layer else { return; }; @@ -171,11 +228,18 @@ impl SpiralTurns { // Convert the total angle (in degrees) to number of full turns let turns_delta = total_delta / 360.; - // Calculate the new outer radius based on spiral type and turn change - let outer_radius_change = match self.spiral_type { - SpiralType::Archimedean => turns_delta * (self.initial_growth_factor) * TAU, - SpiralType::Logarithmic => self.initial_outer_radius * ((self.initial_growth_factor * TAU * turns_delta).exp() - 1.), + // Dragging the start takes turns away rather than adding them + let direction = match self.gizmo_type { + GizmoType::Start => -1., + GizmoType::End => 1., + GizmoType::None => return, }; + let free_turns = self.initial_turns + turns_delta * direction; + let snap_correction = (self.snap_turns(view, snap_session, layer, free_turns) - free_turns) * direction; + let turns_delta = turns_delta + snap_correction; + + // Calculate the new outer radius based on spiral type and turn change + let outer_radius_change = self.outer_radius_change(turns_delta); // Skip if outer_radius calculation produced invalid values if !outer_radius_change.is_finite() { @@ -188,13 +252,11 @@ impl SpiralTurns { match self.gizmo_type { GizmoType::Start => { - let sign = -1.; - let new_turns = (self.initial_turns + turns_delta * sign).max(0.5); - let new_outer_radius = (self.initial_outer_radius + outer_radius_change * sign).max(0.1); + let (new_start_angle, new_turns, new_outer_radius) = self.start_dragged_to(self.initial_turns - turns_delta); responses.add(NodeGraphMessage::SetInput { input_connector: InputConnector::node(node_id, StartAngleInput), - input: NodeInput::value(TaggedValue::Number(self.initial_start_angle + total_delta), false), + input: NodeInput::value(TaggedValue::Number(new_start_angle), false), }); responses.add(NodeGraphMessage::SetInput { input_connector: InputConnector::node(node_id, TurnsInput), diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs index 255c2d2634..4214546340 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs @@ -1,4 +1,4 @@ -use crate::consts::{ARC_SNAP_THRESHOLD, GIZMO_HIDE_THRESHOLD}; +use crate::consts::GIZMO_HIDE_THRESHOLD; use crate::messages::message::Message; use crate::messages::portfolio::document::overlays::utility_functions::text_width; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; @@ -6,13 +6,14 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::prelude::DocumentMessageHandler; use crate::messages::tool::common_functionality::graph_modification_utils; -use crate::messages::tool::common_functionality::shapes::shape_utility::{arc_end_points, calculate_arc_text_transform, extract_arc_parameters, format_rounded}; +use crate::messages::tool::common_functionality::shapes::shape_utility::{arc_end_points, calculate_arc_text_transform, extract_arc_parameters, format_rounded, pointer_travel_per_radian}; +use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate}; use crate::messages::tool::tool_messages::tool_prelude::*; use glam::DVec2; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeInput}; use std::collections::VecDeque; -use std::f64::consts::FRAC_PI_4; +use std::f64::consts::PI; #[derive(Clone, Debug, Default, PartialEq)] pub enum SweepAngleGizmoState { @@ -40,7 +41,7 @@ pub struct SweepAngleGizmo { position_before_rotation: DVec2, previous_mouse_position: DVec2, total_angle_delta: f64, - snap_angles: Vec, + snap_angles: Vec, handle_state: SweepAngleGizmoState, } @@ -192,7 +193,8 @@ impl SweepAngleGizmo { overlay_context.arc_sweep_angle(offset_angle, angle, final_point, bold_radius, center, &text, transform); } - pub fn update_arc(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + pub fn update_arc(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { + let SnapView { document, input, .. } = view; let Some(layer) = self.layer else { return }; let Some((_, current_start_angle, current_sweep_angle, _)) = extract_arc_parameters(Some(layer), document) else { return; @@ -216,11 +218,10 @@ impl SweepAngleGizmo { EndpointType::Start => { // Dragging start changes both start and sweep - let sign = -angle.signum(); let mut total = angle; let new_start_angle = self.initial_start_angle + total; - let new_sweep_angle = self.initial_sweep_angle + total.abs() * sign; + let new_sweep_angle = self.initial_sweep_angle - total; match () { // Clamp sweep angle to 360° @@ -276,13 +277,14 @@ impl SweepAngleGizmo { self.apply_arc_update(node_id, self.initial_start_angle + underflow, self.initial_sweep_angle + underflow.abs(), input, responses); } _ => { - if let Some(snapped_delta) = self.check_snapping(self.initial_sweep_angle + total.abs() * sign) { - total += snapped_delta; + let free_sweep_angle = self.initial_sweep_angle - total; + total += free_sweep_angle - self.snap_sweep_angle(view, snap_session, free_sweep_angle); + if snap_session.caught() { self.update_state(SweepAngleGizmoState::Snapped); } self.total_angle_delta = angle; - self.apply_arc_update(node_id, self.initial_start_angle + total, self.initial_sweep_angle + total.abs() * sign, input, responses); + self.apply_arc_update(node_id, self.initial_start_angle + total, self.initial_sweep_angle - total, input, responses); } } } @@ -317,8 +319,9 @@ impl SweepAngleGizmo { self.apply_arc_update(node_id, self.initial_start_angle + angle_delta, self.initial_sweep_angle + angle_delta.abs() * sign, input, responses); } _ => { - if let Some(snapped_delta) = self.check_snapping(self.initial_sweep_angle + angle) { - total += snapped_delta; + let free_sweep_angle = self.initial_sweep_angle + angle; + total += self.snap_sweep_angle(view, snap_session, free_sweep_angle) - free_sweep_angle; + if snap_session.caught() { self.update_state(SweepAngleGizmoState::Snapped); } @@ -348,22 +351,44 @@ impl SweepAngleGizmo { responses.add(NodeGraphMessage::RunDocumentGraph); } - pub fn check_snapping(&self, new_sweep_angle: f64) -> Option { - self.snap_angles.iter().find(|angle| (**angle - new_sweep_angle).abs() <= ARC_SNAP_THRESHOLD).map(|angle| { - let delta = angle - new_sweep_angle; - if self.endpoint == EndpointType::End { delta } else { -delta } - }) + /// Snaps a sweep angle in degrees to the multiples of 45°, judged by how far the pointer travels around the center on screen. + fn snap_sweep_angle(&self, view: SnapView, snap_session: &mut SnapSession, free_sweep_angle: f64) -> f64 { + let document = view.document; + let Some(layer) = self.layer else { return free_sweep_angle }; + let Some((radius, start_angle, sweep_angle, _)) = extract_arc_parameters(Some(layer), document) else { + return free_sweep_angle; + }; + + // The sweep follows the pointer's angle in the arc's own space, which a stretched arc spaces unevenly on screen + let layer_to_viewport = document.metadata().transform_to_viewport(layer); + let on_screen_per_degree = pointer_travel_per_radian(layer_to_viewport, view.input.mouse.position) * PI / 180.; + + // The dragged end turns about the center in the arc's own space, the start leaving the far end where it is as it shrinks the sweep + let layer_to_document = document.metadata().document_to_viewport.inverse() * layer_to_viewport; + let position_of = |sweep_angle_landed_on: f64| { + let end_angle = match self.endpoint { + EndpointType::Start => start_angle + sweep_angle - sweep_angle_landed_on, + _ => start_angle + sweep_angle_landed_on, + }; + layer_to_document.transform_point2(radius * DVec2::from_angle(end_angle.to_radians())) + }; + + snap_session.snap_value(view, position_of, free_sweep_angle, on_screen_per_degree, &self.snap_angles) } - pub fn calculate_snap_angles() -> Vec { - let mut snap_points = Vec::new(); - - for i in 0..=8 { - let snap_point = i as f64 * FRAC_PI_4; - snap_points.push(snap_point.to_degrees()); - } - - snap_points + /// The multiples of 45° from 0° to 360°, of which 90° and 270° are right angles. + pub fn calculate_snap_angles() -> Vec { + (0..=8_u64) + .map(|step| { + let degrees = step * 45; + let kind = if degrees == 90 || degrees == 270 { Kind::RightAngle } else { Kind::AngleStep }; + ValueCandidate { + value: degrees as f64, + kind, + identity: degrees, + } + }) + .collect() } pub fn cleanup(&mut self) { diff --git a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs index 24a9dbe96a..4f790f9727 100644 --- a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs +++ b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs @@ -164,46 +164,54 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde } /// Merge the `first_endpoint` with `second_endpoint`. -pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, first_endpoint: PointId, second_endpont: PointId, responses: &mut VecDeque) { +pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, first_endpoint: PointId, second_endpoint: PointId, responses: &mut VecDeque) { let transform = document.metadata().transform_to_document(layer); let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - let segment = vector.segment_iter().find(|(_, _, start, end)| *end == second_endpont || *start == second_endpont); + let segment = vector.segment_iter().find(|(_, _, start, end)| *end == second_endpoint || *start == second_endpoint); let Some((segment, _, mut segment_start_point, mut segment_end_point)) = segment else { log::error!("Could not get the segment for second_endpoint."); return; }; let mut handles = [None; 2]; - if let Some(handle_position) = ManipulatorPointId::PrimaryHandle(segment).get_position(&vector) { - let anchor_position = ManipulatorPointId::Anchor(segment_start_point).get_position(&vector).unwrap(); + if let Some(handle_position) = vector.position_of(ManipulatorPointId::PrimaryHandle(segment)) { + let anchor_position = vector.position_of(ManipulatorPointId::Anchor(segment_start_point)).unwrap(); let handle_position = transform.transform_point2(handle_position); let anchor_position = transform.transform_point2(anchor_position); let anchor_to_handle = handle_position - anchor_position; handles[0] = Some(anchor_to_handle); } - if let Some(handle_position) = ManipulatorPointId::EndHandle(segment).get_position(&vector) { - let anchor_position = ManipulatorPointId::Anchor(segment_end_point).get_position(&vector).unwrap(); + if let Some(handle_position) = vector.position_of(ManipulatorPointId::EndHandle(segment)) { + let anchor_position = vector.position_of(ManipulatorPointId::Anchor(segment_end_point)).unwrap(); let handle_position = transform.transform_point2(handle_position); let anchor_position = transform.transform_point2(anchor_position); let anchor_to_handle = handle_position - anchor_position; handles[1] = Some(anchor_to_handle); } - if segment_start_point == second_endpont { - core::mem::swap(&mut segment_start_point, &mut segment_end_point); - handles.reverse(); + // The segment keeps its direction, with whichever end sat on the merged-away point moving to the point it merges into + if segment_start_point == second_endpoint { + segment_start_point = first_endpoint; + } else { + segment_end_point = first_endpoint; } - let modification_type = VectorModificationType::RemovePoint { id: second_endpont }; + let modification_type = VectorModificationType::RemovePoint { id: second_endpoint }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); let modification_type = VectorModificationType::RemoveSegment { id: segment }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); - let points = [segment_start_point, first_endpoint]; + let points = [segment_start_point, segment_end_point]; let id = SegmentId::generate(); let modification_type = VectorModificationType::InsertSegment { id, points, handles }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + + // The replacement takes over as the beginning of the path that the removed segment began + if vector.path_beginnings().contains(&segment) { + let modification_type = VectorModificationType::SetPathBreak { segment: id, breaks: true }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } } /// Create a new bitmap layer. @@ -324,8 +332,8 @@ pub struct ReplaceablePaintChain { /// The whole-expanse paint on a 'Merge' layer that a paint tool may take over, or `None` /// when the layer isn't one or its chain holds anything the tools didn't put there. -/// The walk stops at the first node the rest of the graph also draws from, since repainting through it would change -/// what those other consumers see, and it passes through 'Transform' nodes so a swap keeps the layer's placement. +/// Nodes from the first one the rest of the graph also draws from are detached rather than deleted, so those other +/// consumers see no change, and the walk passes through 'Transform' nodes so a swap keeps the layer's placement. pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option { if !network_interface.is_merge(&layer.to_node(), &[]) { return None; @@ -344,17 +352,17 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N let mut input = InputConnector::layer_secondary_input(layer.to_node()); // Trails the walk over the 'Transform' nodes that survive, then holds still once the paint to clear away begins let mut attachment_input = input; + // Everything upstream of a shared node is shared too, so it's kept, though it must still be paint for the layer to count as blank + let mut shared = false; while let Some(upstream) = network_interface.upstream_output_connector(&input, &[]) { let node_id = upstream.node_id()?; // Arriving here means this layer consumes the node, so a further consumer makes it shared - let shared = network_interface - .with_outward_wires(&[], |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).is_some_and(|inputs| inputs.len() > 1)) - .unwrap_or(true); - if shared { - break; - } + shared = shared + || network_interface + .with_outward_wires(&[], |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).is_some_and(|inputs| inputs.len() > 1)) + .unwrap_or(true); let Some(DefinitionIdentifier::ProtoNode(identifier)) = network_interface.reference(&node_id, &[]) else { return None; @@ -362,7 +370,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N if identifier == graphene_std::transform_nodes::transform::IDENTIFIER { input = InputConnector::primary_input(node_id); - if nodes.is_empty() { + if nodes.is_empty() && !shared { attachment_input = input; } continue; @@ -373,7 +381,9 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N return None; } - nodes.push(node_id); + if !shared { + nodes.push(node_id); + } if generator { break; diff --git a/editor/src/messages/tool/common_functionality/shape_editor.rs b/editor/src/messages/tool/common_functionality/shape_editor.rs index 186dd2d68d..99d09532f8 100644 --- a/editor/src/messages/tool/common_functionality/shape_editor.rs +++ b/editor/src/messages/tool/common_functionality/shape_editor.rs @@ -11,8 +11,10 @@ use crate::messages::tool::tool_messages::path_tool::{PathOverlayMode, PointSele use glam::{DAffine2, DVec2}; use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table; use graphene_std::vector::algorithms::shapes::polyline_bezpath; -use graphene_std::vector::misc::{BezierHandles, HandleId, ManipulatorPointId, PathSegPoints, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles}; -use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModificationType}; +use graphene_std::vector::misc::{ + BezierHandles, HandleId, HandleType, ManipulatorPointId, PathSegPoints, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles, +}; +use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModificationType}; use kurbo::{Affine, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveNearest, PathSeg, Rect, Shape}; use std::f64::consts::TAU; @@ -163,13 +165,13 @@ pub struct ShapeState { pub struct SelectedPointsInfo { pub points: Vec, pub offset: DVec2, - pub vector: Vector, + pub vector: VectorGeometry, } #[derive(Debug)] pub struct SelectedSegmentsInfo { pub segments: Vec, - pub vector: Vector, + pub vector: VectorGeometry, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -187,6 +189,7 @@ pub struct ClosestSegment { bezier: PathSeg, points: [PointId; 2], colinear: [Option; 2], + begins_path: bool, t: f64, bezier_point_to_viewport: DVec2, } @@ -277,6 +280,15 @@ impl ClosestSegment { }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + // The first half takes over as the beginning of the path that the split segment began + if self.begins_path { + let modification_type = VectorModificationType::SetPathBreak { + segment: segment_ids[0], + breaks: true, + }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } + // Last segment let modification_type = VectorModificationType::InsertSegment { id: segment_ids[1], @@ -325,10 +337,7 @@ impl ClosestSegment { } else { let [first_point, last_point] = self.points(); if let Some(vector) = document.network_interface.compute_modified_vector(self.layer()) { - if let (Some(pos1), Some(pos2)) = ( - ManipulatorPointId::Anchor(first_point).get_position(&vector), - ManipulatorPointId::Anchor(last_point).get_position(&vector), - ) { + if let (Some(pos1), Some(pos2)) = (vector.position_of(ManipulatorPointId::Anchor(first_point)), vector.position_of(ManipulatorPointId::Anchor(last_point))) { (pos1 - pos2).try_normalize() } else { None @@ -441,8 +450,8 @@ impl ShapeState { responses: &mut VecDeque, ) { // Get the local positions of the selected points - let start_local_pos = document.network_interface.compute_modified_vector(layer1).and_then(|v| v.point_domain.position_from_id(start_point)); - let end_local_pos = document.network_interface.compute_modified_vector(layer2).and_then(|v| v.point_domain.position_from_id(end_point)); + let start_local_pos = document.network_interface.compute_modified_vector(layer1).and_then(|v| v.position_from_id(start_point)); + let end_local_pos = document.network_interface.compute_modified_vector(layer2).and_then(|v| v.position_from_id(end_point)); // Transform to document/world space let start_transform = document.metadata().transform_to_document(layer1); @@ -541,7 +550,7 @@ impl ShapeState { for &layer in self.selected_shape_state.keys() { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; - let endpoints: Vec = vector.point_domain.ids().iter().copied().filter(|&point_id| vector.all_connected(point_id).count() == 1).collect(); + let endpoints: Vec = vector.anchor_endpoints().collect(); if endpoints.len() == 2 { let start_point = endpoints[0]; @@ -575,7 +584,7 @@ impl ShapeState { if let Some((layer, manipulator_point_id)) = self.find_nearest_visible_point_indices(network_interface, mouse_position, select_threshold, path_overlay_mode, frontier_handles_info) { let vector = network_interface.compute_modified_vector(layer)?; - let point_position = manipulator_point_id.get_position(&vector)?; + let point_position = vector.position_of(manipulator_point_id)?; let selected_shape_state = self.selected_shape_state.get(&layer)?; let already_selected = selected_shape_state.is_point_selected(manipulator_point_id); @@ -629,7 +638,7 @@ impl ShapeState { return None; } let vector = network_interface.compute_modified_vector(layer)?; - let point_position = manipulator_point_id.get_position(&vector)?; + let point_position = vector.position_of(manipulator_point_id)?; let selected_shape_state = self.selected_shape_state.get(&layer)?; // Check if point is visible under current overlay mode or not let selected_segments_for_layer = selected_segments_for_layer(&vector, selected_shape_state); @@ -701,12 +710,12 @@ impl ShapeState { if selected_stack.is_empty() { // Fall back on just selecting all points/segments in the layer if points { - for &point in vector.point_domain.ids() { + for point in vector.anchor_points() { state.select_point(ManipulatorPointId::Anchor(point)); } } if segments { - for &segment in vector.segment_domain.ids() { + for segment in vector.segment_ids() { state.select_segment(segment); } } @@ -761,7 +770,7 @@ impl ShapeState { state.clear_points(); - for &point in vector.point_domain.ids() { + for point in vector.anchor_points() { state.select_point(ManipulatorPointId::Anchor(point)) } } @@ -770,7 +779,7 @@ impl ShapeState { fn select_all_segments_in_layer_with_state(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, state: &mut SelectedLayerState) { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - for &segment in vector.segment_domain.ids() { + for segment in vector.segment_ids() { state.select_segment(segment); } } @@ -866,21 +875,7 @@ impl ShapeState { self.selected_shape_state.get(&layer).map(|state| &state.selected_segments) } - pub fn move_primary(&self, segment: SegmentId, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque) { - responses.add(GraphOperationMessage::Vector { - layer, - modification_type: VectorModificationType::ApplyPrimaryDelta { segment, delta }, - }); - } - - pub fn move_end(&self, segment: SegmentId, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque) { - responses.add(GraphOperationMessage::Vector { - layer, - modification_type: VectorModificationType::ApplyEndDelta { segment, delta }, - }); - } - - pub fn move_anchor(&self, point: PointId, vector: &Vector, delta: DVec2, layer: LayerNodeIdentifier, selected: Option<&SelectedLayerState>, responses: &mut VecDeque) { + pub fn move_anchor(&self, point: PointId, vector: &VectorGeometry, delta: DVec2, layer: LayerNodeIdentifier, selected: Option<&SelectedLayerState>, responses: &mut VecDeque) { // Move anchor responses.add(GraphOperationMessage::Vector { layer, @@ -897,7 +892,10 @@ impl ShapeState { } let relative_position = handle - point_to_dvec2(path_segment.start()) + delta; - let modification_type = VectorModificationType::SetPrimaryHandle { segment, relative_position }; + let modification_type = VectorModificationType::SetHandlePosition { + handle: HandleId::primary(segment), + relative_position, + }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -921,26 +919,22 @@ impl ShapeState { let vector = network_interface.compute_modified_vector(layer)?; let transform = network_interface.document_metadata().transform_to_document_if_feeds(layer, network_interface).inverse(); let position = transform.transform_point2(new_position); - let current_position = point.get_position(&vector)?; - let delta = position - current_position; + let current_position = vector.position_of(*point)?; match *point { - ManipulatorPointId::Anchor(point) => self.move_anchor(point, &vector, delta, layer, None, responses), - ManipulatorPointId::PrimaryHandle(segment) => { - self.move_primary(segment, delta, layer, responses); - if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_manipulators.iter().find(|handles| handles[0] == handle || handles[1] == handle) - { - let modification_type = VectorModificationType::SetG1Continuous { handles: *handles, enabled: false }; - responses.add(GraphOperationMessage::Vector { layer, modification_type }); - } - } - ManipulatorPointId::EndHandle(segment) => { - self.move_end(segment, delta, layer, responses); - if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_manipulators.iter().find(|handles| handles[0] == handle || handles[1] == handle) - { - let modification_type = VectorModificationType::SetG1Continuous { handles: *handles, enabled: false }; + ManipulatorPointId::Anchor(anchor) => self.move_anchor(anchor, &vector, position - current_position, layer, None, responses), + ManipulatorPointId::PrimaryHandle(_) | ManipulatorPointId::EndHandle(_) => { + let handle = point.as_handle()?; + + // Set by its offset from the anchor, since a delta has no stored offset to add onto until the Path node edits this handle + let relative_position = position - vector.anchor_position_of(*point)?; + responses.add(GraphOperationMessage::Vector { + layer, + modification_type: handle.set_relative_position(relative_position), + }); + + if let Some(handles) = vector.colinear_pair_containing(handle) { + let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } @@ -960,7 +954,7 @@ impl ShapeState { .flat_map(|(data, selection_state)| { selection_state.selected_points.iter().filter_map(move |&point| { let Some(data) = &data else { return None }; - let _ = point.get_handle_pair(data)?; // ignores the endpoints. + let _ = data.handle_pair_of(point)?; // ignores the endpoints. Some(data.colinear(point)) }) }); @@ -972,12 +966,12 @@ impl ShapeState { if first_is_colinear { ManipulatorAngle::Colinear } else { ManipulatorAngle::Free } } - pub fn convert_manipulator_handles_to_colinear(&self, vector: &Vector, point_id: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier) { - let Some(anchor_position) = ManipulatorPointId::Anchor(point_id).get_position(vector) else { + pub fn convert_manipulator_handles_to_colinear(&self, vector: &VectorGeometry, point_id: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier) { + let Some(anchor_position) = vector.position_of(ManipulatorPointId::Anchor(point_id)) else { return; }; let handles = vector.all_connected(point_id).take(2).collect::>(); - let non_zero_handles = handles.iter().filter(|handle| handle.length(vector) > 1e-6).count(); + let non_zero_handles = handles.iter().filter(|handle| vector.handle_length(**handle) > 1e-6).count(); let handle_segments = handles.iter().map(|handles| handles.segment).collect::>(); // Check if the anchor is connected to linear segments and has no handles @@ -985,7 +979,7 @@ impl ShapeState { // Grab the next and previous manipulator groups by simply looking at the next / previous index let points = handles.iter().map(|handle| vector.other_point(handle.segment, point_id)); - let anchor_positions = points.map(|point| point.and_then(|point| ManipulatorPointId::Anchor(point).get_position(vector))).collect::>(); + let anchor_positions = points.map(|point| point.and_then(|point| vector.position_of(ManipulatorPointId::Anchor(point)))).collect::>(); let mut segment_angle = 0.; let mut segment_count = 0.; @@ -1024,15 +1018,14 @@ impl ShapeState { if non_zero_handles != 0 && !linear_segments { let [a, b] = handles.as_slice() else { return }; - let (non_zero_handle, zero_handle) = if a.length(vector) > 1e-6 { (a, b) } else { (b, a) }; - let Some(direction) = non_zero_handle - .to_manipulator_point() - .get_position(vector) + let (non_zero_handle, zero_handle) = if vector.handle_length(*a) > 1e-6 { (a, b) } else { (b, a) }; + let Some(direction) = vector + .position_of(non_zero_handle.to_manipulator_point()) .and_then(|position| (position - anchor_position).try_normalize()) else { return; }; - let new_position = -direction * non_zero_handle.length(vector); + let new_position = -direction * vector.handle_length(*non_zero_handle); let modification_type = zero_handle.set_relative_position(new_position); responses.add(GraphOperationMessage::Vector { layer, modification_type }); } else { @@ -1053,7 +1046,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Create the opposite handle if it doesn't exist (if it is not a cubic segment) - if handle.opposite().to_manipulator_point().get_position(vector).is_none() { + if vector.position_of(handle.opposite().to_manipulator_point()).is_none() { let modification_type = handle.opposite().set_relative_position(DVec2::ZERO); responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1085,28 +1078,27 @@ impl ShapeState { // Here we take handles as the current handle and the most opposite non-colinear-handle - let is_handle_colinear = |handle: HandleId| -> bool { vector.colinear_manipulators.iter().any(|&handles| handles[0] == handle || handles[1] == handle) }; + let is_handle_colinear = |handle: HandleId| -> bool { vector.colinear(handle.to_manipulator_point()) }; let other_handles = if matches!(point, ManipulatorPointId::Anchor(_)) { - point.get_handle_pair(&vector) + vector.handle_pair_of(point) } else { - let Some(anchor) = point.get_anchor_position(&vector) else { continue }; - let Some(orig_handle_pos) = point.get_position(&vector) else { continue }; + let Some(anchor) = vector.anchor_position_of(point) else { continue }; + let Some(orig_handle_pos) = vector.position_of(point) else { continue }; let Some(v_orig) = (orig_handle_pos - anchor).try_normalize() else { continue }; - point.get_all_connected_handles(&vector).and_then(|handles| { + vector.all_connected_handles_of(point).and_then(|handles| { let mut non_colinear_handles = handles.iter().filter(|&handle| !is_handle_colinear(*handle)).clone().collect::>(); // Skip handles with no position or with the same position as the anchor non_colinear_handles.retain(|&handle| { - let Some(handle) = handle.to_manipulator_point().get_position(&vector) else { return false }; + let Some(handle) = vector.position_of(handle.to_manipulator_point()) else { return false }; (handle - anchor).is_non_zero() }); // Find the most colinear handle (maximum absolute angle from the original) let most_colinear = non_colinear_handles.into_iter().max_by(|&handle_a, &handle_b| { - let [Some(angle_a), Some(angle_b)] = - [handle_a, handle_b].map(|handle| handle.to_manipulator_point().get_position(&vector).and_then(|pos| v_orig.try_angle_to(pos - anchor))) + let [Some(angle_a), Some(angle_b)] = [handle_a, handle_b].map(|handle| vector.position_of(handle.to_manipulator_point()).and_then(|pos| v_orig.try_angle_to(pos - anchor))) else { error!("invalid handles (e.g. no handle or zero length) should be filtered above"); return core::cmp::Ordering::Equal; @@ -1133,13 +1125,13 @@ impl ShapeState { skip_set.insert(handles); let [selected0, selected1] = handles.map(|handle| layer_state.selected_points.contains(&handle.to_manipulator_point())); - let handle_positions = handles.map(|handle| handle.to_manipulator_point().get_position(&vector)); + let handle_positions = handles.map(|handle| vector.position_of(handle.to_manipulator_point())); - let Some(anchor_id) = point.get_anchor(&vector) else { continue }; - let Some(anchor) = vector.point_domain.position_from_id(anchor_id) else { continue }; + let Some(anchor_id) = vector.anchor_of(point) else { continue }; + let Some(anchor) = vector.position_from_id(anchor_id) else { continue }; let anchor_points = handles.map(|handle| vector.other_point(handle.segment, anchor_id)); - let anchor_positions = anchor_points.map(|point| point.and_then(|point| vector.point_domain.position_from_id(point))); + let anchor_positions = anchor_points.map(|point| point.and_then(|point| vector.position_from_id(point))); // If one handle is selected (but both exist), only move the other handle if let (true, [Some(pos0), Some(pos1)]) = ((selected0 ^ selected1), handle_positions) { @@ -1181,7 +1173,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Create the opposite handle if it doesn't exist (if it is not a cubic segment) - if handles[index].opposite().to_manipulator_point().get_position(&vector).is_none() { + if vector.position_of(handles[index].opposite().to_manipulator_point()).is_none() { let modification_type = handles[index].opposite().set_relative_position(DVec2::ZERO); responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1245,14 +1237,14 @@ impl ShapeState { ManipulatorPointId::EndHandle(segment) => HandleId::end(segment), }; - let Some(anchor_id) = point.get_anchor(&vector) else { continue }; + let Some(anchor_id) = vector.anchor_of(point) else { continue }; if state.is_point_selected(ManipulatorPointId::Anchor(anchor_id)) { continue; } - let Some(anchor_position) = vector.point_domain.position_from_id(anchor_id) else { continue }; + let Some(anchor_position) = vector.position_from_id(anchor_id) else { continue }; - let Some(handle_position) = point.get_position(&vector) else { continue }; + let Some(handle_position) = vector.position_of(point) else { continue }; let handle_position = handle_position + delta; let modification_type = handle.set_relative_position(handle_position - anchor_position); @@ -1283,7 +1275,7 @@ impl ShapeState { } else { // TODO: Is this equivalent to `transform_to_document_space`? If changed, the before and after should be tested. let transform = document.metadata().document_to_viewport.inverse() * transform_to_viewport_space; - let Some(other_position) = other.to_manipulator_point().get_position(&vector) else { + let Some(other_position) = vector.position_of(other.to_manipulator_point()) else { continue; }; let direction = transform.transform_vector2(handle_position - anchor_position).try_normalize(); @@ -1308,14 +1300,14 @@ impl ShapeState { let vector = document.network_interface.compute_modified_vector(layer)?; let transform = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface); let opposing_handle_lengths = vector - .colinear_manipulators - .iter() - .filter_map(|&handles| { + .colinear_pairs() + .into_iter() + .filter_map(|handles| { // We will keep track of the opposing handle length when: // i) Exactly one handle is selected. // ii) The anchor is not selected. - let anchor = handles[0].to_manipulator_point().get_anchor(&vector)?; + let anchor = vector.anchor_of(handles[0].to_manipulator_point())?; let anchor_selected = state.is_point_selected(ManipulatorPointId::Anchor(anchor)); if anchor_selected { return None; @@ -1329,8 +1321,8 @@ impl ShapeState { _ => return None, }; - let opposing_handle_position = other.to_manipulator_point().get_position(&vector)?; - let anchor_position = vector.point_domain.position_from_id(anchor)?; + let opposing_handle_position = vector.position_of(other.to_manipulator_point())?; + let anchor_position = vector.position_from_id(anchor)?; let opposing_handle_length = transform.transform_vector2(opposing_handle_position - anchor_position).length(); Some((other, opposing_handle_length)) @@ -1341,7 +1333,7 @@ impl ShapeState { .collect::>() } - pub fn dissolve_segment(&self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &Vector, segment: SegmentId, points: [PointId; 2]) { + pub fn dissolve_segment(&self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &VectorGeometry, segment: SegmentId, points: [PointId; 2]) { // Checking which point is terminal point let is_point1_terminal = vector.connected_count(points[0]) == 1; let is_point2_terminal = vector.connected_count(points[1]) == 1; @@ -1349,7 +1341,7 @@ impl ShapeState { // Delete the segment and terminal points let modification_type = VectorModificationType::RemoveSegment { id: segment }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in vector.colinear_manipulators.iter().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { + for handles in vector.colinear_pairs().into_iter().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1364,27 +1356,30 @@ impl ShapeState { } } - fn dissolve_anchor(anchor: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &Vector) -> Option<[(HandleId, PointId); 2]> { + fn dissolve_anchor(anchor: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &VectorGeometry) -> Option<[(HandleId, PointId); 2]> { // Delete point let modification_type = VectorModificationType::RemovePoint { id: anchor }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Delete connected segments + let colinear_pairs = vector.colinear_pairs(); for HandleId { segment, .. } in vector.all_connected(anchor) { let modification_type = VectorModificationType::RemoveSegment { id: segment }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in vector.colinear_manipulators.iter().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { + for handles in colinear_pairs.iter().copied().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } - // Add in new segment if possible - let mut handles = ManipulatorPointId::Anchor(anchor).get_handle_pair(vector)?; - handles.reverse(); + // Add in new segment if possible, running on from the segment that arrives at the anchor into the one that leaves it + let mut handles = vector.handle_pair_of(ManipulatorPointId::Anchor(anchor))?; + if handles[0].ty != HandleType::End || handles[1].ty != HandleType::Primary { + handles.reverse(); + } let opposites = handles.map(|handle| handle.opposite()); - let [Some(start), Some(end)] = opposites.map(|opposite| opposite.to_manipulator_point().get_anchor(vector)) else { + let [Some(start), Some(end)] = opposites.map(|opposite| vector.anchor_of(opposite.to_manipulator_point())) else { return None; }; Some([(handles[0], start), (handles[1], end)]) @@ -1398,6 +1393,8 @@ impl ShapeState { let mut missing_anchors = HashMap::new(); let mut deleted_anchors = HashSet::new(); let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; + let colinear_pairs = vector.colinear_pairs(); + let path_beginnings = vector.path_beginnings(); let selected_segments = &state.selected_segments; @@ -1425,7 +1422,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Disable the g1 continuous - for &handles in &vector.colinear_manipulators { + for &handles in &colinear_pairs { if handles.contains(&handle) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); @@ -1463,8 +1460,8 @@ impl ShapeState { // Grab the handles from the opposite side of the segment(s) being deleted and make it relative to the anchor let [handle_start, handle_end] = [start, end].map(|(handle, _)| { let handle = handle.opposite(); - let handle_position = handle.to_manipulator_point().get_position(&vector); - let relative_position = handle.to_manipulator_point().get_anchor(&vector).and_then(|anchor| vector.point_domain.position_from_id(anchor)); + let handle_position = vector.position_of(handle.to_manipulator_point()); + let relative_position = vector.anchor_of(handle.to_manipulator_point()).and_then(|anchor| vector.position_from_id(anchor)); handle_position.and_then(|handle| relative_position.map(|relative| handle - relative)).unwrap_or_default() }); @@ -1478,12 +1475,18 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in vector.colinear_manipulators.iter() { + // Removing the segment dropped its mark as the beginning of a path, which the reconnection takes over + if path_beginnings.contains(&segment) { + let modification_type = VectorModificationType::SetPathBreak { segment, breaks: true }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } + + for &handles in &colinear_pairs { if !handles.iter().any(|&handle| handle == start.0.opposite() || handle == end.0.opposite()) { continue; } - let Some(anchor) = handles[0].to_manipulator_point().get_anchor(&vector) else { continue }; + let Some(anchor) = vector.anchor_of(handles[0].to_manipulator_point()) else { continue }; let Some(other) = handles.iter().find(|&&handle| handle != start.0.opposite() && handle != end.0.opposite()) else { continue; }; @@ -1551,15 +1554,16 @@ impl ShapeState { for (&layer, state) in &self.selected_shape_state { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; + let colinear_pairs = vector.colinear_pairs(); for &delete in &state.selected_points { - let Some(point) = delete.get_anchor(&vector) else { continue }; - let Some(pos) = vector.point_domain.position_from_id(point) else { continue }; + let Some(point) = vector.anchor_of(delete) else { continue }; + let Some(pos) = vector.position_from_id(point) else { continue }; let mut used_initial_point = false; for handle in vector.all_connected(point) { // Disable the g1 continuous - for &handles in &vector.colinear_manipulators { + for &handles in &colinear_pairs { if !transaction_started { responses.add(DocumentMessage::AddTransaction); transaction_started = true; @@ -1589,11 +1593,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Update segment - let HandleId { ty, segment } = handle; - let modification_type = match ty { - graphene_std::vector::misc::HandleType::Primary => VectorModificationType::SetStartPoint { segment, id }, - graphene_std::vector::misc::HandleType::End => VectorModificationType::SetEndPoint { segment, id }, - }; + let modification_type = VectorModificationType::SetEndpoint { handle, id }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1610,7 +1610,7 @@ impl ShapeState { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; for delete in std::mem::take(&mut state.selected_points) { - let Some(point) = delete.get_anchor(&vector) else { continue }; + let Some(point) = vector.anchor_of(delete) else { continue }; if !transaction_started { responses.add(DocumentMessage::AddTransaction); @@ -1635,19 +1635,20 @@ impl ShapeState { pub fn disable_colinear_handles_state_on_selected(&self, network_interface: &NodeNetworkInterface, responses: &mut VecDeque) { for (&layer, state) in &self.selected_shape_state { let Some(vector) = network_interface.compute_modified_vector(layer) else { continue }; + let colinear_pairs = vector.colinear_pairs(); for &point in &state.selected_points { if let ManipulatorPointId::Anchor(point) = point { for connected in vector.all_connected(point) { - if let Some(&handles) = vector.colinear_manipulators.iter().find(|target| target.contains(&connected)) { + if let Some(&handles) = colinear_pairs.iter().find(|pair| pair.contains(&connected)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } } else if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_manipulators.iter().find(|handles| handles[0] == handle || handles[1] == handle) + && let Some(handles) = vector.colinear_pair_containing(handle) { - let modification_type = VectorModificationType::SetG1Continuous { handles: *handles, enabled: false }; + let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } @@ -1750,7 +1751,7 @@ impl ShapeState { } // Anchors - for (&id, &point) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) { + for (id, point) in vector.anchors() { let point = viewspace.transform_point2(point); if point.distance_squared(pos) <= closest_distance_squared { @@ -1773,6 +1774,7 @@ impl ShapeState { let mut closest_distance_squared: f64 = tolerance * tolerance; let vector = network_interface.compute_modified_vector(layer)?; + let colinear_pairs = vector.colinear_pairs(); for (segment_id, mut segment, start, end) in vector.segment_iter() { let t = segment.nearest(dvec2_to_point(layer_pos), DEFAULT_ACCURACY).t; @@ -1793,16 +1795,17 @@ impl ShapeState { } } - let primary_handle = vector.colinear_manipulators.iter().find(|handles| handles.contains(&HandleId::primary(segment_id))); - let end_handle = vector.colinear_manipulators.iter().find(|handles| handles.contains(&HandleId::end(segment_id))); - let primary_handle = primary_handle.and_then(|&handles| handles.into_iter().find(|handle| handle.segment != segment_id)); - let end_handle = end_handle.and_then(|&handles| handles.into_iter().find(|handle| handle.segment != segment_id)); + let primary_handle = colinear_pairs.iter().copied().find(|handles| handles.contains(&HandleId::primary(segment_id))); + let end_handle = colinear_pairs.iter().copied().find(|handles| handles.contains(&HandleId::end(segment_id))); + let primary_handle = primary_handle.and_then(|handles| handles.into_iter().find(|handle| handle.segment != segment_id)); + let end_handle = end_handle.and_then(|handles| handles.into_iter().find(|handle| handle.segment != segment_id)); closest = Some(ClosestSegment { segment: segment_id, bezier: segment, points: [start, end], colinear: [primary_handle, end_handle], + begins_path: false, t, bezier_point_to_viewport: screenspace, layer, @@ -1810,6 +1813,10 @@ impl ShapeState { } } + if let Some(closest) = &mut closest { + closest.begins_path = vector.path_beginnings().contains(&closest.segment); + } + closest } @@ -1831,7 +1838,7 @@ impl ShapeState { if point.as_anchor().is_some() { return PointSelectState::Anchor; } - if point.get_handle_pair(&vector).is_some() { + if vector.handle_pair_of(*point).is_some() { return PointSelectState::HandleWithPair; } } @@ -1848,7 +1855,7 @@ impl ShapeState { if point.as_anchor().is_some() { return false; } - if point.get_handle_pair(&vector).is_some() { + if vector.handle_pair_of(*point).is_some() { return true; } } @@ -1869,9 +1876,9 @@ impl ShapeState { continue; } - if let Some(other_handles) = point.get_all_connected_handles(&vector) { - let Some(anchor) = point.get_anchor_position(&vector) else { continue }; - let Some(orig_handle_pos) = point.get_position(&vector) else { continue }; + if let Some(other_handles) = vector.all_connected_handles_of(*point) { + let Some(anchor) = vector.anchor_position_of(*point) else { continue }; + let Some(orig_handle_pos) = vector.position_of(*point) else { continue }; let Some(v_orig) = (orig_handle_pos - anchor).try_normalize() else { continue }; // Find the next closest handle in the clockwise sense @@ -1879,13 +1886,13 @@ impl ShapeState { // Skip handles with no position or with the same position as the anchor candidates.retain(|&handle| { - let Some(handle) = handle.to_manipulator_point().get_position(&vector) else { return false }; + let Some(handle) = vector.position_of(handle.to_manipulator_point()) else { return false }; (handle - anchor).is_non_zero() }); // Find the next handle let next_handle = candidates.into_iter().min_by(|&handle_a, &handle_b| { - let [Some(angle_a), Some(angle_b)] = [handle_a, handle_b].map(|handle| handle.to_manipulator_point().get_position(&vector).and_then(|pos| v_orig.try_angle_to(pos - anchor))) + let [Some(angle_a), Some(angle_b)] = [handle_a, handle_b].map(|handle| vector.position_of(handle.to_manipulator_point()).and_then(|pos| v_orig.try_angle_to(pos - anchor))) else { error!("invalid handles (e.g. no handle or zero length) should be filtered above"); return core::cmp::Ordering::Equal; @@ -1925,8 +1932,8 @@ impl ShapeState { let Some(vector) = network_interface.compute_modified_vector(layer) else { continue }; for point in self.selected_points().filter(|point| point.as_handle().is_some()) { - let anchor = point.get_anchor(&vector); - match point.get_handle_pair(&vector) { + let anchor = vector.anchor_of(*point); + match vector.handle_pair_of(*point) { Some(handles) => { points_to_select.push((layer, anchor, Some(handles[1].to_manipulator_point()))); } @@ -1961,10 +1968,10 @@ impl ShapeState { // Get the current point and its connected handles let selected_points = state.selected_points.clone(); if let Some(point) = selected_points.iter().next() { - if let Some(anchor) = point.get_anchor(&vector) { + if let Some(anchor) = vector.anchor_of(*point) { state.select_point(ManipulatorPointId::Anchor(anchor)); } - if let Some(handles) = point.get_handle_pair(&vector) { + if let Some(handles) = vector.handle_pair_of(*point) { state.select_point(handles[0].to_manipulator_point()); state.select_point(handles[1].to_manipulator_point()); } @@ -1995,12 +2002,12 @@ impl ShapeState { // Check by comparing the handle positions to the anchor if this manipulator group is a point for point in selected_points { let Some(point_id) = point.as_anchor() else { continue }; - let anchor = point.get_position(&vector)?; + let anchor = vector.position_of(*point)?; let handles = vector.all_connected(point_id); // TODO: Check if this method of finding non-colinear is really required let positions = handles - .filter_map(|handle| handle.to_manipulator_point().get_position(&vector)) + .filter_map(|handle| vector.position_of(handle.to_manipulator_point())) .filter(|&handle| anchor.abs_diff_eq(handle, 1e-5)) .count(); @@ -2010,6 +2017,7 @@ impl ShapeState { if positions != 0 || one_or_more_segment_linear { self.convert_manipulator_handles_to_colinear(&vector, point_id, responses, layer); } else { + let colinear_pairs = vector.colinear_pairs(); for handle in vector.all_connected(point_id) { let Some(path_segment) = vector.segment_from_id(handle.segment) else { continue }; @@ -2022,7 +2030,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Set the manipulator to have non-colinear handles - for &handles in &vector.colinear_manipulators { + for handles in colinear_pairs.iter().copied() { if handles.contains(&HandleId::primary(segment)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); @@ -2035,7 +2043,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Set the manipulator to have non-colinear handles - for &handles in &vector.colinear_manipulators { + for handles in colinear_pairs.iter().copied() { if handles.contains(&handle) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); @@ -2093,7 +2101,7 @@ impl ShapeState { (_, SelectionChange::Shrink) => state.deselect_point(point), (ManipulatorPointId::EndHandle(_) | ManipulatorPointId::PrimaryHandle(_), _) => { let handle = point.as_handle().expect("Handle cannot be converted"); - if handle.length(&vector) > 0. { + if vector.handle_length(handle) > 0. { state.select_point(point); } } @@ -2151,15 +2159,6 @@ impl ShapeState { let Some(vector) = vector else { continue }; let transform = network_interface.document_metadata().transform_to_viewport_if_feeds(layer, network_interface); - assert_eq!(vector.segment_domain.ids().len(), vector.start_point().count()); - assert_eq!(vector.segment_domain.ids().len(), vector.end_point().count()); - for start in vector.start_point() { - assert!(vector.point_domain.ids().contains(&start)); - } - for end in vector.end_point() { - assert!(vector.point_domain.ids().contains(&end)); - } - let polygon_bezpath = if let SelectionShape::Lasso(polygon) = selection_shape { if polygon.len() < 2 { return (points_inside, segments_inside); @@ -2237,7 +2236,7 @@ impl ShapeState { } // Checking for selection of anchor points - for (&id, &position) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) { + for (id, position) in vector.anchors() { let transformed_position = transform.transform_point2(position); let select = match selection_shape { diff --git a/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs b/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs index 33c740f43e..bf4480da7f 100644 --- a/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs @@ -53,13 +53,13 @@ impl ShapeGizmoHandler for ArcGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.sweep_angle_gizmo.is_dragging_or_snapped() { - self.sweep_angle_gizmo.update_arc(document, input, responses); + self.sweep_angle_gizmo.update_arc(view, snap_session, responses); } if self.arc_radius_handle.is_dragging() { - self.arc_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.arc_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs index 1eb4463095..95e0525c77 100644 --- a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs @@ -33,9 +33,9 @@ impl ShapeGizmoHandler for CircleGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.circle_radius_handle.is_dragging() { - self.circle_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.circle_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs b/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs index 9efeb13690..eae6124383 100644 --- a/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs @@ -35,9 +35,9 @@ impl ShapeGizmoHandler for GridGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, _snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.row_column_gizmo.is_dragging() { - self.row_column_gizmo.update(document, input, responses, drag_start); + self.row_column_gizmo.update(view.document, view.input, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs b/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs index db0cfc13d4..0c7331dea4 100644 --- a/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs @@ -1,4 +1,4 @@ -use super::shape_utility::{ShapeToolModifierKey, update_radius_sign}; +use super::shape_utility::{ShapeToolModifierKey, drawn_flipped}; use super::*; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type}; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; @@ -43,13 +43,13 @@ impl ShapeGizmoHandler for PolygonGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.number_of_points_dial.is_dragging() { - self.number_of_points_dial.update_number_of_sides(document, input, responses, drag_start); + self.number_of_points_dial.update_number_of_sides(view.document, view.input, responses, drag_start); } if self.point_radius_handle.is_dragging_or_snapped() { - self.point_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.point_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } @@ -128,11 +128,17 @@ impl Polygon { let document = view.document; let [center, lock_ratio, _] = modifier; - let vertices = extract_polygon_parameters(Some(layer), document).map(|(sides, _)| regular_polygon_points(sides)).unwrap_or_default(); + let sides = extract_polygon_parameters(Some(layer), document).map(|(sides, _)| sides); + let flipped = sides.is_some_and(|sides| drawn_flipped(sides, shape_tool_data.data.viewport_drag_start(document), view.input.mouse.position)); + let vertices: Vec = sides + .map(regular_polygon_points) + .unwrap_or_default() + .into_iter() + .map(|vertex| if flipped { -vertex } else { vertex }) + .collect(); + if let Some([start, end]) = shape_tool_data.data.calculate_points(snap_session, view, center, lock_ratio, &vertices) { // TODO: We need to determine how to allow the polygon node to make irregular shapes - update_radius_sign(end, start, layer, document, responses); - let dimensions = (start - end).abs(); // We keep the smaller dimension's scale at 1 and scale the other dimension accordingly @@ -146,6 +152,7 @@ impl Polygon { }; let radius = radius / viewport_zoom(document); + let radius = if flipped { -radius } else { radius }; let Some(node_id) = graph_modification_utils::get_polygon_id(layer, &document.network_interface) else { return; diff --git a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs index 6e82f3e31a..9c072f8ccd 100644 --- a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs +++ b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs @@ -6,15 +6,14 @@ use crate::messages::message::Message; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; 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, Responses}; +use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler}; use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer; use crate::messages::tool::common_functionality::shape_editor::ShapeState; +use crate::messages::tool::common_functionality::snap_session::{SnapSession, SnapView}; use crate::messages::tool::common_functionality::transformation_cage::BoundingBoxManager; use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::*; use glam::{DAffine2, DMat2, DVec2}; -use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; use graphene_std::core_types::misc::format_f64; use graphene_std::math::float_noise::round_away_float_noise; @@ -135,7 +134,7 @@ pub trait ShapeGizmoHandler { /// Called during a drag interaction to update the shape's parameters in real time. /// /// For example, a handle might calculate the distance from the drag start to determine a new radius or update the number of points. - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque); + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque); /// Draws the static or hover-dependent overlays associated with the gizmo. /// @@ -209,41 +208,9 @@ pub fn clicked_on_shape_endpoints(layer: LayerNodeIdentifier, document: &Documen endpoint_click } -/// Center, Lock Ratio, Lock Angle, Snap Angle, Increase/Decrease Side -pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier, document: &DocumentMessageHandler, responses: &mut VecDeque) { - let sign_num = if end[1] > start[1] { 1. } else { -1. }; - let new_layer = NodeGraphLayer::new(layer, &document.network_interface); - - if let Some(&TaggedValue::Integer(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::regular_polygon::SidesInput) - && sides % 2 != 0 - { - let Some(polygon_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::regular_polygon::IDENTIFIER)) else { - return; - }; - - responses.add(NodeGraphMessage::SetInput { - input_connector: InputConnector::node(polygon_node_id, graphene_std::vector::generator_nodes::regular_polygon::RadiusInput), - input: NodeInput::value(TaggedValue::Number(sign_num * 0.5), false), - }); - return; - } - - if let Some(&TaggedValue::Integer(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::star::SidesInput) - && sides % 2 != 0 - { - let Some(star_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::star::IDENTIFIER)) else { - return; - }; - - responses.add(NodeGraphMessage::SetInput { - input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius1Input), - input: NodeInput::value(TaggedValue::Number(sign_num * 0.5), false), - }); - responses.add(NodeGraphMessage::SetInput { - input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius2Input), - input: NodeInput::value(TaggedValue::Number(sign_num * 0.25), false), - }); - } +/// Whether an odd-sided polygon or star being drawn is flipped to point down, which it is when dragged upward. It's flipped by negating its radius. +pub fn drawn_flipped(sides: u32, viewport_drag_start: DVec2, pointer: DVec2) -> bool { + sides % 2 == 1 && pointer.y < viewport_drag_start.y } pub fn transform_cage_overlays(document: &DocumentMessageHandler, tool_data: &mut ShapeToolData, overlay_context: &mut OverlayContext) { @@ -293,7 +260,7 @@ pub fn anchor_overlays(document: &DocumentMessageHandler, overlay_context: &mut overlay_context.outline_vector(&vector, transform); - for (_, &position) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) { + for (_, position) in vector.anchors() { overlay_context.manipulator_anchor(transform.transform_point2(position), false, None); } } @@ -394,6 +361,19 @@ pub fn arc_end_points_ignore_layer(radius: f64, start_angle: f64, sweep_angle: f Some((start_point, end_point)) } +/// How far the pointer must move on screen to turn its angle about a layer's center, in the layer's own space, by a radian. +/// On a layer scaled evenly, that is its distance from the center. +pub fn pointer_travel_per_radian(layer_to_viewport: DAffine2, pointer: DVec2) -> f64 { + let from_center = pointer - layer_to_viewport.translation; + let determinant = layer_to_viewport.matrix2.determinant(); + if determinant == 0. { + return f64::NAN; + } + + let in_layer = layer_to_viewport.matrix2.inverse() * from_center; + in_layer.length_squared() * determinant.abs() / from_center.length() +} + /// Calculate the viewport position of a star vertex given its index /// Extract the node input values of Circle. /// Returns an option of (radius). diff --git a/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs b/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs index 693b35a154..c49478ec78 100644 --- a/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs @@ -38,9 +38,9 @@ impl ShapeGizmoHandler for SpiralGizmoHandler { } } - fn handle_update(&mut self, _drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, _drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.turns_handle.is_dragging() { - self.turns_handle.update_number_of_turns(document, input, responses); + self.turns_handle.update_number_of_turns(view, snap_session, responses); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/star_shape.rs b/editor/src/messages/tool/common_functionality/shapes/star_shape.rs index d64403b547..c4b9c6db45 100644 --- a/editor/src/messages/tool/common_functionality/shapes/star_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/star_shape.rs @@ -1,4 +1,4 @@ -use super::shape_utility::{ShapeToolModifierKey, update_radius_sign}; +use super::shape_utility::{ShapeToolModifierKey, drawn_flipped}; use super::*; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type}; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; @@ -43,13 +43,13 @@ impl ShapeGizmoHandler for StarGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.number_of_points_dial.is_dragging() { - self.number_of_points_dial.update_number_of_sides(document, input, responses, drag_start); + self.number_of_points_dial.update_number_of_sides(view.document, view.input, responses, drag_start); } if self.point_radius_handle.is_dragging_or_snapped() { - self.point_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.point_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } @@ -132,13 +132,17 @@ impl Star { let document = view.document; let [center, lock_ratio, _] = modifier; - let points = extract_star_parameters(Some(layer), document) - .map(|(sides, _, _)| star_points(sides, INNER_RADIUS_WHILE_DRAWING)) - .unwrap_or_default(); + let sides = extract_star_parameters(Some(layer), document).map(|(sides, _, _)| sides); + let flipped = sides.is_some_and(|sides| drawn_flipped(sides, shape_tool_data.data.viewport_drag_start(document), view.input.mouse.position)); + let points: Vec = sides + .map(|sides| star_points(sides, INNER_RADIUS_WHILE_DRAWING)) + .unwrap_or_default() + .into_iter() + .map(|point| if flipped { -point } else { point }) + .collect(); + if let Some([start, end]) = shape_tool_data.data.calculate_points(snap_session, view, center, lock_ratio, &points) { // TODO: We need to determine how to allow the polygon node to make irregular shapes - update_radius_sign(end, start, layer, document, responses); - let dimensions = (start - end).abs(); // We keep the smaller dimension's scale at 1 and scale the other dimension accordingly @@ -152,6 +156,7 @@ impl Star { }; let radius = radius / viewport_zoom(document); + let radius = if flipped { -radius } else { radius }; let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface) else { return; diff --git a/editor/src/messages/tool/common_functionality/snap_session.rs b/editor/src/messages/tool/common_functionality/snap_session.rs index 3067736dec..28825723d0 100644 --- a/editor/src/messages/tool/common_functionality/snap_session.rs +++ b/editor/src/messages/tool/common_functionality/snap_session.rs @@ -9,19 +9,19 @@ use crate::messages::input_mapper::utility_types::keyboard::Key; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::prelude::*; use crate::messages::tool::utility_types::{HintGroup, HintInfo}; -use glam::DVec2; +use glam::{DAffine2, DVec2}; use graphene_std::vector::PointId; use scene_mirror::layer_id; pub use scene_mirror::anchor_positions; use snapping::{ - AnchorId, Awake, Bounds, Candidate, Context, CrossingCache, Exclusions, Frame, Highlight, Incumbent, LayerId, LayerKind, Outcome, Request, Scene, Settings, Side, Snap, SpacedBox, Tunables, - ViewMapping, find_constructions, find_constructions_from, find_equal_sizes, find_spacing, + AnchorId, Awake, Bounds, Candidate, CandidateKey, Context, CrossingCache, Exclusions, Frame, Highlight, Incumbent, LayerId, LayerKind, Outcome, Request, Scene, Settings, Side, Snap, SpacedBox, + Tunables, ViewMapping, find_constructions, find_constructions_from, find_equal_sizes, find_spacing, }; use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; -pub use snapping::{FeatureMap, Locus}; +pub use snapping::{FeatureMap, Kind, Locus}; /// How long the pointer must rest on a target to wake it while a gesture is under way, in milliseconds. const WAKE_DWELL_IN_GESTURE: u64 = 250; @@ -104,6 +104,16 @@ pub struct BoxFeatures { pub sides: [[Option; 2]; 2], } +/// A value a gizmo's value may snap to. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ValueCandidate { + pub value: f64, + /// The relationship it gives, which names it in the label. + pub kind: Kind, + /// Tells it apart from others of its kind, so an engaged snap is recognized after the pointer moves. + pub identity: u64, +} + /// What the latest attempt to snap came to, kept for drawing. #[derive(Clone, Debug)] pub struct Shown { @@ -197,8 +207,8 @@ impl SnapSession { let SnapView { document, document_id, input } = view; // Held quiet, nothing is offered, so the scene can wait to be brought up to date - let quiet = !document.snapping_state.snapping_enabled || input.keyboard.key(Key::KeyQ); - if quiet { + let silenced = !document.snapping_state.snapping_enabled || input.keyboard.key(Key::KeyQ); + if silenced { self.follow_document(document_id); } else { self.bring_up_to_date(document, document_id); @@ -229,14 +239,9 @@ impl SnapSession { // A box is taken where the pointer asks for it, once any track it must stay on has had its say let asked = options.required.map_or(free, |track| track.nearest(free)); let kind = self.gesture.as_ref().map_or(LayerKind::Artwork, |gesture| gesture.kind); - let spaced = options.box_features.filter(|_| !quiet).and_then(|box_features| spaced_box(kind, &box_features, features, asked)); + let spaced = options.box_features.filter(|_| !silenced).and_then(|box_features| spaced_box(kind, &box_features, features, asked)); let awake = self.awake_around(spaced.as_ref()); - - // Nothing snaps until the pointer has moved past the drag threshold from where the gesture began - let within_threshold = self.gesture.as_mut().is_some_and(|gesture| { - gesture.dragged |= input.mouse.position.distance(gesture.pressed) > DRAG_THRESHOLD; - !gesture.dragged - }); + let (quiet, cycle) = self.steering(view); let (frame, tunables, nothing_moving) = (Frame::default(), Tunables::default(), Exclusions::default()); @@ -289,17 +294,12 @@ impl SnapSession { let probed: Option> = options.snapping.map(|count| (0..count.min(features.len()) as u32).collect()); - // A tap of the cycling key counts once, however long the key is held down - let cycle_key_held = input.keyboard.key(Key::KeyW); - let cycle = usize::from(cycle_key_held && !self.cycle_key_was_held); - self.cycle_key_was_held = cycle_key_held; - let request = Request { grid: grid.as_ref(), required: options.required, incumbent: self.incumbent, cycle, - quiet: quiet || within_threshold, + quiet, constructions: self.constructions.as_ref().map_or(&[], |(_, constructions)| constructions.as_slice()), lead_constructions: &self.constructions_from_previous, crossings: Some(&self.crossings), @@ -308,8 +308,8 @@ impl SnapSession { }; let outcome = snapping::snap_features(&context, &request, features, lead, free, options.previous); - // Until then, what a press landed somewhere stays there - let held = self.gesture.as_ref().and_then(|gesture| gesture.held).filter(|_| within_threshold); + // Until the pointer has moved past the drag threshold, what a press landed somewhere stays there + let held = self.gesture.as_ref().filter(|gesture| !gesture.dragged).and_then(|gesture| gesture.held); let held_parameters = held.and_then(|held| features.get(lead)?.parameters_for(held)).filter(|parameters| parameters.is_finite()); self.holding_press = held_parameters.is_some(); @@ -341,6 +341,67 @@ impl SnapSession { parameters } + /// Snaps one value that a gizmo's handle sets, such as an angle or a radius, and returns the value it lands on. + /// + /// The snap is shown where `position_of` puts the handle, in document space, for the value landed on. Reach is judged by `on_screen_per_unit`, how many viewport pixels the handle moves per unit of the value. + pub fn snap_value(&mut self, view: SnapView, position_of: impl Fn(f64) -> DVec2, free: f64, on_screen_per_unit: f64, candidates: &[ValueCandidate]) -> f64 { + // A value has no features in document space, which an empty list stands for + if !self.features.is_empty() { + self.features.clear(); + self.incumbent = None; + self.crossings.clear(); + } + + let (quiet, cycle) = self.steering(view); + let Some(view_mapping) = ViewMapping::from_affine(DAffine2::from_scale(DVec2::splat(on_screen_per_unit))) else { + self.forget(); + return free; + }; + + // The value is solved as a position along a line, with each candidate a spot on it and nothing else in the scene + let particular: Vec = candidates + .iter() + .map(|candidate| { + let key = CandidateKey { + kind: candidate.kind, + feature: 0, + identity: [candidate.identity, 0, 0], + }; + Candidate::spot(key, DVec2::new(candidate.value, 0.)) + }) + .collect(); + + let (scene, frame, tunables, settings, exclusions) = (Scene::new(), Frame::default(), Tunables::default(), Settings::default(), Exclusions::default()); + let context = Context { + scene: &scene, + view: &view_mapping, + frame: &frame, + tunables: &tunables, + settings: &settings, + exclusions: &exclusions, + awake: &[], + }; + let request = Request { + required: Locus::line(DVec2::ZERO, DVec2::X), + incumbent: self.incumbent, + cycle, + quiet, + particular: &particular, + ..Default::default() + }; + let outcome = snapping::snap_point(&context, &request, DVec2::new(free, 0.), None); + + self.incumbent = outcome.incumbent(); + let snapped = outcome.parameters.x; + self.shown = Some(Shown { + features: vec![position_of(snapped)], + lead: 0, + outcome, + }); + + snapped + } + /// Starts a gesture, which goes on snapping to the scene as it is now and to none of what it moves. /// /// What the pointer was snapped to on the approach is let go, so a press should take what was shown before starting the gesture. @@ -534,6 +595,25 @@ impl SnapSession { &self.awake } + /// Whether this attempt is quiet, as with the master switch off, Q held, or the pointer not yet past the drag threshold, and how many candidates W steps on by. + fn steering(&mut self, view: SnapView) -> (bool, usize) { + let SnapView { document, input, .. } = view; + + // Nothing snaps until the pointer has moved past the drag threshold from where the gesture began + let within_threshold = self.gesture.as_mut().is_some_and(|gesture| { + gesture.dragged |= input.mouse.position.distance(gesture.pressed) > DRAG_THRESHOLD; + !gesture.dragged + }); + + // A tap of the cycling key counts once, however long the key is held down + let cycle_key_held = input.keyboard.key(Key::KeyW); + let cycle = usize::from(cycle_key_held && !self.cycle_key_was_held); + self.cycle_key_was_held = cycle_key_held; + + let quiet = !document.snapping_state.snapping_enabled || input.keyboard.key(Key::KeyQ) || within_threshold; + (quiet, cycle) + } + /// The woken targets, joined while a box is moved by the nearest of the boxes sharing its parent, by any such box the snap is relying on, and by its artboard. fn awake_around(&mut self, spaced: Option<&SpacedBox>) -> Vec { let mut awake = self.awake.clone(); @@ -581,9 +661,9 @@ impl SnapSession { // A midpoint, or a place where paths cross, is a point of its own rather than the curves it was found on let engaged: Vec<&Candidate> = shown.outcome.engaged_candidates().collect(); - let on_a_path = |candidate: &&Candidate| matches!(candidate.key.kind, snapping::Kind::OnCurve | snapping::Kind::OnBoxEdge | snapping::Kind::OnArtboardEdge); + let on_a_path = |candidate: &&Candidate| matches!(candidate.key.kind, Kind::OnCurve | Kind::OnBoxEdge | Kind::OnArtboardEdge); let point_of_its_own = match engaged.as_slice() { - [midpoint] => midpoint.key.kind == snapping::Kind::Midpoint, + [midpoint] => midpoint.key.kind == Kind::Midpoint, [first, second] => first.key.feature == second.key.feature && on_a_path(first) && on_a_path(second), _ => false, }; @@ -1720,4 +1800,76 @@ mod tests { } } } + + /// Angles in degrees a gizmo might offer. + const ANGLES: [ValueCandidate; 2] = [ + ValueCandidate { + value: 90., + kind: Kind::RightAngle, + identity: 90, + }, + ValueCandidate { + value: 135., + kind: Kind::AngleStep, + identity: 135, + }, + ]; + + /// Where the handle of the gizmo snapping its angle sits for an angle, in document space. + fn handle_at(angle: f64) -> DVec2 { + DVec2::new(10., 20.) + DVec2::from_angle(angle.to_radians()) * 50. + } + + fn snap_angle(session: &mut SnapSession, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, free: f64, on_screen_per_degree: f64) -> f64 { + session.snap_value(SnapView::new(document, DOCUMENT, input), handle_at, free, on_screen_per_degree, &ANGLES) + } + + #[test] + fn a_value_lands_on_a_candidate_within_reach_on_screen_and_stays_where_it_is_asked_for_beyond_it() { + let (document, input) = (DocumentMessageHandler::default(), InputPreprocessorMessageHandler::default()); + let mut session = SnapSession::default(); + + // Three degrees short of a right angle is six pixels at two pixels a degree, which is within reach, and the snap is shown where the handle lands + assert_eq!(snap_angle(&mut session, &document, &input, 87., 2.), 90.); + assert_eq!(engaged_kinds(&session), vec![Kind::RightAngle]); + assert_eq!(session.shown_position(), Some(handle_at(90.))); + + // At four pixels a degree the same three degrees are twelve pixels, which is beyond reach + session.forget(); + assert_eq!(snap_angle(&mut session, &document, &input, 87., 4.), 87.); + assert!(!session.caught()); + } + + #[test] + fn holding_q_or_turning_snapping_off_leaves_a_value_where_it_is_asked_for() { + let mut document = DocumentMessageHandler::default(); + let mut input = InputPreprocessorMessageHandler::default(); + let mut session = SnapSession::default(); + + input.keyboard.set(Key::KeyQ as usize); + assert_eq!(snap_angle(&mut session, &document, &input, 88., 2.), 88.); + assert!(!session.caught()); + + input.keyboard.unset(Key::KeyQ as usize); + document.snapping_state.snapping_enabled = false; + assert_eq!(snap_angle(&mut session, &document, &input, 88., 2.), 88.); + assert!(!session.caught()); + + document.snapping_state.snapping_enabled = true; + assert_eq!(snap_angle(&mut session, &document, &input, 88., 2.), 90.); + } + + #[test] + fn an_engaged_value_holds_beyond_the_reach_until_the_release_distance() { + let (document, input) = (DocumentMessageHandler::default(), InputPreprocessorMessageHandler::default()); + let mut session = SnapSession::default(); + + // At two pixels a degree, five degrees away is ten pixels, past the reach of eight but short of the release at twelve + assert_eq!(snap_angle(&mut session, &document, &input, 89.5, 2.), 90.); + assert_eq!(snap_angle(&mut session, &document, &input, 85., 2.), 90.); + + // Seven degrees away is fourteen pixels, where it lets go, and coming back to ten pixels does not catch it again + assert_eq!(snap_angle(&mut session, &document, &input, 83., 2.), 83.); + assert_eq!(snap_angle(&mut session, &document, &input, 85., 2.), 85.); + } } diff --git a/editor/src/messages/tool/common_functionality/snap_session/presenter.rs b/editor/src/messages/tool/common_functionality/snap_session/presenter.rs index fae320e04e..a16b4eb8af 100644 --- a/editor/src/messages/tool/common_functionality/snap_session/presenter.rs +++ b/editor/src/messages/tool/common_functionality/snap_session/presenter.rs @@ -185,6 +185,8 @@ fn name(kind: Kind) -> &'static str { Kind::AngleStep => "Angle", Kind::Spacing => "Evenly Spaced", Kind::EqualSize => "Equal Size", + Kind::EqualRadius => "Equal Radius", + Kind::WholeValue => "Whole Number", } } @@ -200,6 +202,8 @@ mod tests { assert_eq!(label(&[Kind::Extension, Kind::Extension]), "Extension"); assert_eq!(label(&[Kind::OnCurve, Kind::Alignment]), "On Path and Aligned"); assert_eq!(label(&[Kind::TangentLine, Kind::Extension]), "Tangent and Extension"); + assert_eq!(label(&[Kind::EqualRadius]), "Equal Radius"); + assert_eq!(label(&[Kind::WholeValue]), "Whole Number"); } #[test] diff --git a/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs b/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs index 54e1ea7dc1..08d22caa88 100644 --- a/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs +++ b/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs @@ -130,7 +130,7 @@ fn mirror_layer(document: &DocumentMessageHandler, layer: LayerNodeIdentifier) - let curves_drawn: HashSet<[[i64; 2]; 4]> = drawn_curves.iter().map(rounded_curve).collect(); let role = |drawn: bool| if drawn { GeometryRole::Source } else { GeometryRole::Undrawn }; - anchors.extend(vector.point_domain.iter().map(|(id, position)| { + anchors.extend(vector.anchors().map(|(id, position)| { let position = to_document.transform_point2(position); SceneAnchor { position, diff --git a/editor/src/messages/tool/common_functionality/utility_functions.rs b/editor/src/messages/tool/common_functionality/utility_functions.rs index c70f44b0b2..754b3defd1 100644 --- a/editor/src/messages/tool/common_functionality/utility_functions.rs +++ b/editor/src/messages/tool/common_functionality/utility_functions.rs @@ -14,7 +14,7 @@ use graph_craft::document::value::TaggedValue; use graphene_std::renderer::Quad; use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table; use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; -use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModification, VectorModificationType}; +use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModificationType}; use kurbo::{CubicBez, DEFAULT_ACCURACY, ParamCurve, PathSeg, Point, Shape}; /// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable. @@ -49,7 +49,7 @@ fn closest_candidate_point( goal: DVec2, max_distance: f64, layers: impl Iterator, - candidates: impl Fn(&Vector) -> Vec, + candidates: impl Fn(&VectorGeometry) -> Vec, ) -> Option<(LayerNodeIdentifier, PointId, DVec2)> { let mut best = None; let mut best_distance_squared = max_distance * max_distance; @@ -63,7 +63,7 @@ fn closest_candidate_point( let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; for id in candidates(&vector) { - let Some(point) = vector.point_domain.position_from_id(id) else { continue }; + let Some(point) = vector.position_from_id(id) else { continue }; let distance_squared = viewspace.transform_point2(point).distance_squared(goal); if distance_squared < best_distance_squared { @@ -92,16 +92,16 @@ pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageH Quad::from_box([DVec2::ZERO, far]) } -pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector: &Vector, prefer_handle_direction: bool) -> Option { +pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector: &VectorGeometry, prefer_handle_direction: bool) -> Option { let is_start = |point: PointId, segment: SegmentId| vector.segment_start_from_id(segment) == Some(point); - let anchor_position = vector.point_domain.position_from_id(anchor)?; - let end_handle = ManipulatorPointId::EndHandle(segment).get_position(vector); - let start_handle = ManipulatorPointId::PrimaryHandle(segment).get_position(vector); + let anchor_position = vector.position_from_id(anchor)?; + let end_handle = vector.position_of(ManipulatorPointId::EndHandle(segment)); + let start_handle = vector.position_of(ManipulatorPointId::PrimaryHandle(segment)); let start_point = if is_start(anchor, segment) { - vector.segment_end_from_id(segment).and_then(|id| vector.point_domain.position_from_id(id)) + vector.segment_end_from_id(segment).and_then(|id| vector.position_from_id(id)) } else { - vector.segment_start_from_id(segment).and_then(|id| vector.point_domain.position_from_id(id)) + vector.segment_start_from_id(segment).and_then(|id| vector.position_from_id(id)) }; let required_handle = if is_start(anchor, segment) { @@ -119,9 +119,9 @@ pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector: &Vec required_handle.map(|handle| handle - anchor_position).and_then(|vector| DVec2::X.try_angle_to(vector)) } -pub fn adjust_handle_colinearity(handle: HandleId, anchor_position: DVec2, target_control_point: DVec2, vector: &Vector, layer: LayerNodeIdentifier, responses: &mut VecDeque) { +pub fn adjust_handle_colinearity(handle: HandleId, anchor_position: DVec2, target_control_point: DVec2, vector: &VectorGeometry, layer: LayerNodeIdentifier, responses: &mut VecDeque) { let Some(other_handle) = vector.other_colinear_handle(handle) else { return }; - let Some(handle_position) = other_handle.to_manipulator_point().get_position(vector) else { + let Some(handle_position) = vector.position_of(other_handle.to_manipulator_point()) else { return; }; let Some(direction) = (anchor_position - target_control_point).try_normalize() else { return }; @@ -136,12 +136,12 @@ pub fn restore_previous_handle_position( handle: HandleId, original_c: DVec2, anchor_position: DVec2, - vector: &Vector, + vector: &VectorGeometry, layer: LayerNodeIdentifier, responses: &mut VecDeque, ) -> Option { let other_handle = vector.other_colinear_handle(handle)?; - let handle_position = other_handle.to_manipulator_point().get_position(vector)?; + let handle_position = vector.position_of(other_handle.to_manipulator_point())?; let direction = (anchor_position - original_c).try_normalize()?; let old_relative_position = (handle_position - anchor_position).length() * direction; @@ -155,8 +155,16 @@ pub fn restore_previous_handle_position( Some(other_handle) } -pub fn restore_g1_continuity(handle: HandleId, other_handle: HandleId, control_point: DVec2, anchor_position: DVec2, vector: &Vector, layer: LayerNodeIdentifier, responses: &mut VecDeque) { - let Some(handle_position) = other_handle.to_manipulator_point().get_position(vector) else { +pub fn restore_g1_continuity( + handle: HandleId, + other_handle: HandleId, + control_point: DVec2, + anchor_position: DVec2, + vector: &VectorGeometry, + layer: LayerNodeIdentifier, + responses: &mut VecDeque, +) { + let Some(handle_position) = vector.position_of(other_handle.to_manipulator_point()) else { return; }; let Some(direction) = (anchor_position - control_point).try_normalize() else { return }; @@ -173,7 +181,7 @@ pub fn restore_g1_continuity(handle: HandleId, other_handle: HandleId, control_p /// Check whether a point is visible in the current overlay mode. pub fn is_visible_point( manipulator_point_id: ManipulatorPointId, - vector: &Vector, + vector: &VectorGeometry, path_overlay_mode: PathOverlayMode, frontier_handles_for_layer: Option<&HashMap>>, selected_segments: &[SegmentId], @@ -190,14 +198,14 @@ pub fn is_visible_point( } // Either the segment is a part of selected segments or the opposite handle is a part of existing selection - let Some(handle_pair) = manipulator_point_id.get_handle_pair(vector) else { return false }; + let Some(handle_pair) = vector.handle_pair_of(manipulator_point_id) else { return false }; let other_handle = handle_pair[1].to_manipulator_point(); // Return whether the list of selected points contain the other handle selected_points.contains(&other_handle) } (PathOverlayMode::FrontierHandles, false) => { - let Some(anchor) = manipulator_point_id.get_anchor(vector) else { + let Some(anchor) = vector.anchor_of(manipulator_point_id) else { warn!("No anchor for selected handle"); return false; }; @@ -610,7 +618,7 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac // Must not already have an existing Path node, in the right-most part of the layer chain, which has an empty set of modifications // (otherwise users could repeatedly keep running this command and stacking up empty Path nodes) if let Some(TaggedValue::VectorModification(modifications)) = NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::Network("Path".into()), 1) - && modifications.as_ref() == &VectorModification::default() + && modifications.is_empty() { return None; } diff --git a/editor/src/messages/tool/tool_message_handler.rs b/editor/src/messages/tool/tool_message_handler.rs index 9196dba4e4..dab9598047 100644 --- a/editor/src/messages/tool/tool_message_handler.rs +++ b/editor/src/messages/tool/tool_message_handler.rs @@ -162,8 +162,9 @@ impl ToolMessageHandler { } }; - send_abort_to_tool(old_tool, tool_type, true); + // The old tool goes first so it can finish its edit before the new tool's abort, which also leaves the new tool's hints and cursor showing send_abort_to_tool(old_tool, old_tool, false); + send_abort_to_tool(old_tool, tool_type, true); // Nothing a tool was snapping, or had woken, carries over to the next tool self.snap_session.end_gesture(); diff --git a/editor/src/messages/tool/tool_messages/artboard_tool.rs b/editor/src/messages/tool/tool_messages/artboard_tool.rs index 8f566c59c0..146d79bee1 100644 --- a/editor/src/messages/tool/tool_messages/artboard_tool.rs +++ b/editor/src/messages/tool/tool_messages/artboard_tool.rs @@ -237,6 +237,14 @@ impl ArtboardToolData { } } + /// The selected artboard, unless it's locked or hidden, which puts it out of reach of the tool as on the canvas. + fn editable_artboard(&self, document: &DocumentMessageHandler) -> Option { + let artboard = self.selected_artboard?; + let selected_nodes = document.network_interface.selected_nodes(); + let editable = selected_nodes.layer_visible(artboard, &document.network_interface) && !selected_nodes.layer_locked(artboard, &document.network_interface); + editable.then_some(artboard) + } + fn hovered_artboard(document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> Option { document.click_xray(input, viewport).find(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[])) } @@ -329,14 +337,14 @@ impl Fsm for ArtboardToolFsmState { (state, ArtboardToolMessage::Overlays { context: mut overlay_context }) => { let display_transform_cage = overlay_context.visibility_settings.transform_cage(); if display_transform_cage && state != ArtboardToolFsmState::Drawing { - if let Some(bounds) = tool_data.selected_artboard.and_then(|layer| document.metadata().bounding_box_document(layer)) { + if let Some(bounds) = tool_data.editable_artboard(document).and_then(|layer| document.metadata().bounding_box_document(layer)) { let bounding_box_manager = tool_data.bounding_box_manager.get_or_insert(BoundingBoxManager::default()); bounding_box_manager.bounds = bounds; bounding_box_manager.transform = document.metadata().document_to_viewport; bounding_box_manager.render_overlays(&mut overlay_context, true); } else { - // If the bounding box is not resolved (e.g. if the artboard is deleted), then discard the bounding box. + // Without an editable artboard (one deleted, locked, or hidden), discard the bounding box tool_data.bounding_box_manager.take(); } } else { @@ -387,7 +395,8 @@ impl Fsm for ArtboardToolFsmState { self } (ArtboardToolFsmState::Ready { .. }, ArtboardToolMessage::PointerDown) => { - let state = if let Some(selected_edges) = tool_data.check_dragging_bounds(input.mouse.position) { + let resize_edges = tool_data.editable_artboard(document).and_then(|_| tool_data.check_dragging_bounds(input.mouse.position)); + let state = if let Some(selected_edges) = resize_edges { tool_data.start_resizing(selected_edges, document, input); // The artboard's own box follows the resize, while what is inside it stays put and can be snapped to @@ -580,7 +589,7 @@ impl Fsm for ArtboardToolFsmState { let Some(bounds) = &tool_data.bounding_box_manager else { return ArtboardToolFsmState::Ready { hovered }; }; - let Some(selected_artboard) = tool_data.selected_artboard else { + let Some(selected_artboard) = tool_data.editable_artboard(document) else { return ArtboardToolFsmState::Ready { hovered }; }; if selected_artboard == LayerNodeIdentifier::ROOT_PARENT { @@ -1127,4 +1136,53 @@ mod test_artboard { assert_bounds(&editor, artboard, [DVec2::new(104., 32.), DVec2::new(164., 76.)]); } + + #[tokio::test] + async fn a_locked_artboard_selected_in_the_layers_panel_cant_be_nudged_or_resized() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let artboard = draw_artboard(&mut editor, DVec2::new(100., 100.), DVec2::new(200., 160.)).await; + editor + .handle_message(NodeGraphMessage::SetLocked { + node_id: artboard.to_node(), + network_path: Vec::new(), + locked: true, + }) + .await; + + // Selected in the Layers panel, as the canvas leaves locked artboards out of reach + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![artboard.to_node()] }).await; + editor.handle_message(ArtboardToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.press(Key::ArrowRight, ModifierKeys::SHIFT).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + + // Where its bottom edge's handle would be + drag(&mut editor, DVec2::new(150., 160.), DVec2::new(150., 220.), ModifierKeys::empty()).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + } + + #[tokio::test] + async fn an_artboard_locked_while_its_cage_is_shown_cant_be_nudged_or_resized_before_the_overlays_redraw() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let artboard = draw_artboard(&mut editor, DVec2::new(100., 100.), DVec2::new(200., 160.)).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![artboard.to_node()] }).await; + editor.handle_message(ArtboardToolMessage::Overlays { context: OverlayContext::default() }).await; + + // No overlay pass follows the lock, so the cage drawn before it is still there to grab + editor + .handle_message(NodeGraphMessage::SetLocked { + node_id: artboard.to_node(), + network_path: Vec::new(), + locked: true, + }) + .await; + + editor.press(Key::ArrowRight, ModifierKeys::SHIFT).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + + drag(&mut editor, DVec2::new(150., 160.), DVec2::new(150., 220.), ModifierKeys::empty()).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + } } diff --git a/editor/src/messages/tool/tool_messages/fill_tool.rs b/editor/src/messages/tool/tool_messages/fill_tool.rs index 17e42582fc..48a2435922 100644 --- a/editor/src/messages/tool/tool_messages/fill_tool.rs +++ b/editor/src/messages/tool/tool_messages/fill_tool.rs @@ -190,7 +190,8 @@ impl Fsm for FillToolFsmState { _ => return self, }; - responses.add(DocumentMessage::AddTransaction); + // Left open until the release, so Esc or right-click while the button is held can still roll the fill back + responses.add(DocumentMessage::StartTransaction); if route_to_color_chain { responses.add(GraphOperationMessage::ColorValueSet { layer: layer_identifier, color }); } else { @@ -202,7 +203,11 @@ impl Fsm for FillToolFsmState { FillToolFsmState::Filling } - (FillToolFsmState::Filling, FillToolMessage::PointerUp) => FillToolFsmState::Ready, + (FillToolFsmState::Filling, FillToolMessage::PointerUp) => { + responses.add(DocumentMessage::EndTransaction); + + FillToolFsmState::Ready + } (FillToolFsmState::Filling, FillToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); @@ -328,6 +333,30 @@ mod test_fill { assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW)); } + #[tokio::test] + async fn esc_while_held_cancels_the_fill() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + let original = *get_fills(&mut editor).await.first().expect("the rectangle should have a fill").element(); + + editor.select_primary_color(Color::GREEN).await; + editor.select_tool(ToolType::Fill).await; + editor.left_mousedown(50., 50., ModifierKeys::empty()).await; + editor.press(Key::Escape, ModifierKeys::empty()).await; + editor.left_mouseup(50., 50., ModifierKeys::empty()).await; + + let fills = get_fills(&mut editor).await; + assert_eq!(fills.len(), 1); + assert_eq!(SRGBA8::from(*fills[0].element()), SRGBA8::from(original), "Esc while the button is held should undo the fill"); + + // Without the Esc, the fill sticks and is one undo step + editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(50., 50.), ModifierKeys::empty()).await; + assert_eq!(SRGBA8::from(*get_fills(&mut editor).await[0].element()), SRGBA8::from(Color::GREEN)); + editor.handle_message(DocumentMessage::Undo).await; + assert_eq!(SRGBA8::from(*get_fills(&mut editor).await[0].element()), SRGBA8::from(original), "one undo should take the fill back"); + } + #[tokio::test] async fn blank_layer_gets_whole_expanse_color() { use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_color_value_node_id; @@ -542,6 +571,63 @@ mod test_fill { ); } + #[tokio::test] + async fn a_layer_drawing_shared_geometry_keeps_it() { + use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector}; + use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_color_value_node_id; + use graph_craft::document::NodeId; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + let rectangle = editor.active_document().metadata().all_layers().next().unwrap(); + + // A new layer above the rectangle, whose content is wired from the end of the rectangle's chain so both draw it + let sharing_id = NodeId::new(); + editor + .handle_message(GraphOperationMessage::NewCustomLayer { + id: sharing_id, + nodes: Vec::new(), + parent: LayerNodeIdentifier::ROOT_PARENT, + insert_index: 0, + }) + .await; + let sharing = LayerNodeIdentifier::new_unchecked(sharing_id); + let shared_id = editor + .active_document() + .network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(rectangle.to_node()), &[]) + .and_then(|output| output.node_id()) + .expect("the rectangle should have a chain"); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(shared_id), &InputConnector::layer_secondary_input(sharing_id), &[]); + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![sharing_id] }).await; + + editor.select_primary_color(Color::GREEN).await; + editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(50., 50.), ModifierKeys::empty()).await; + + let network_interface = &editor.active_document().network_interface; + assert!( + get_upstream_color_value_node_id(sharing, network_interface).is_none(), + "a layer drawing shared geometry isn't blank, so it mustn't get a whole-expanse color" + ); + assert_eq!( + network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(sharing_id), &[]) + .and_then(|output| output.node_id()), + Some(shared_id), + "the layer should still draw the shared rectangle" + ); + + let fills = get_fills(&mut editor).await; + assert!( + fills.iter().any(|fill| SRGBA8::from(*fill.element()) == SRGBA8::from(Color::GREEN)), + "the shared rectangle's Fill should take the color" + ); + } + #[tokio::test] async fn nudged_blank_layer_keeps_its_transform() { use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; diff --git a/editor/src/messages/tool/tool_messages/freehand_tool.rs b/editor/src/messages/tool/tool_messages/freehand_tool.rs index 7751093cfb..31f2c0f4f6 100644 --- a/editor/src/messages/tool/tool_messages/freehand_tool.rs +++ b/editor/src/messages/tool/tool_messages/freehand_tool.rs @@ -441,9 +441,9 @@ mod test_freehand { use crate::messages::tool::tool_messages::freehand_tool::FreehandOptionsUpdate; use crate::test_utils::test_prelude::*; use glam::{DAffine2, DMat2, DVec2}; - use graphene_std::vector::Vector; + use graphene_std::vector::VectorGeometry; - async fn get_vector_and_transform_list(editor: &mut EditorTestUtils) -> Vec<(Vector, DAffine2)> { + async fn get_vector_and_transform_list(editor: &mut EditorTestUtils) -> Vec<(VectorGeometry, DAffine2)> { let document = editor.active_document(); let layers = document.metadata().all_layers(); @@ -460,18 +460,18 @@ mod test_freehand { .collect() } - fn verify_path_points(vector_and_transform_list: &[(Vector, DAffine2)], expected_captured_points: &[DVec2], tolerance: f64) -> Result<(), String> { + fn verify_path_points(vector_and_transform_list: &[(VectorGeometry, DAffine2)], expected_captured_points: &[DVec2], tolerance: f64) -> Result<(), String> { assert_eq!(vector_and_transform_list.len(), 1, "There should be one item of Vector geometry"); let (vector, transform) = vector_and_transform_list .iter() - .find(|(data, _)| !data.point_domain.ids().is_empty()) + .find(|(data, _)| data.anchor_points().next().is_some()) .ok_or("Could not find path data")?; - let point_count = vector.point_domain.ids().len(); - let segment_count = vector.segment_domain.ids().len(); + let point_count = vector.anchor_points().count(); + let segment_count = vector.segment_ids().len(); - let actual_positions: Vec = vector.point_domain.positions().iter().map(|&position| transform.transform_point2(position)).collect(); + let actual_positions: Vec = vector.anchor_positions().iter().map(|&position| transform.transform_point2(position)).collect(); if segment_count != point_count - 1 { return Err(format!("Expected segments to be one less than points, got {segment_count} segments for {point_count} points")); @@ -555,8 +555,8 @@ mod test_freehand { assert!(!initial_vector_and_transform.is_empty(), "No vector geometry found after initial drawing"); let (initial_vector, _) = &initial_vector_and_transform[0]; - let initial_point_count = initial_vector.point_domain.ids().len(); - let initial_segment_count = initial_vector.segment_domain.ids().len(); + let initial_point_count = initial_vector.anchor_points().count(); + let initial_segment_count = initial_vector.segment_ids().len(); let existing_layer_id = { let document = editor.active_document(); @@ -613,8 +613,8 @@ mod test_freehand { assert_eq!(layer_count, 1, "Expected only one layer after drawing with Shift key"); let (final_vector, _) = &final_vector_and_transform[0]; - let final_point_count = final_vector.point_domain.ids().len(); - let final_segment_count = final_vector.segment_domain.ids().len(); + let final_point_count = final_vector.anchor_points().count(); + let final_segment_count = final_vector.segment_ids().len(); assert!( final_point_count > initial_point_count, @@ -704,7 +704,7 @@ mod test_freehand { fn point_and_segment_counts(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> (usize, usize) { let vector = editor.active_document().network_interface.compute_modified_vector(layer).expect("Layer should have vector geometry"); - (vector.point_domain.ids().len(), vector.segment_domain.ids().len()) + (vector.anchor_points().count(), vector.segment_ids().len()) } /// The viewport positions of the layer's anchors, split into the endpoints of its open paths and every other anchor. @@ -714,7 +714,7 @@ mod test_freehand { let transform = document.metadata().transform_to_viewport(layer); let endpoints: Vec<_> = vector.anchor_endpoints().collect(); - let viewport_position = |id| vector.point_domain.position_from_id(id).map(|position| transform.transform_point2(position)); + let viewport_position = |id| vector.position_from_id(id).map(|position| transform.transform_point2(position)); let endpoint_positions = endpoints.iter().filter_map(|&id| viewport_position(id)).collect(); let other_positions = vector.anchor_points().filter(|id| !endpoints.contains(id)).filter_map(viewport_position).collect(); @@ -833,11 +833,7 @@ mod test_freehand { let vector = document.network_interface.compute_modified_vector(layer).expect("Layer should have vector geometry"); let transform = document.metadata().transform_to_viewport(layer); for &pointer_position in &continuation[1..] { - let under_pointer = vector - .point_domain - .positions() - .iter() - .any(|&position| transform.transform_point2(position).distance(pointer_position) < 1.); + let under_pointer = vector.anchor_positions().iter().any(|&position| transform.transform_point2(position).distance(pointer_position) < 1.); assert!(under_pointer, "Expected a point under the pointer at {pointer_position:?}"); } } diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index 3cdc466eb1..e779f93fb5 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -619,14 +619,18 @@ impl SelectedGradient { lock_angle: bool, gradient_form: GradientForm, drag_start: DVec2, + press_unsnapped: DVec2, snap_session: &mut SnapSession, view: SnapView, gradient_angle: &mut f64, ) { - if mouse.distance(drag_start) < DRAG_THRESHOLD { - self.gradient = self.initial_gradient.clone(); - self.appearance.transform = self.initial_gradient_transform; - self.render_gradient(responses); + if mouse.distance(press_unsnapped) <= DRAG_THRESHOLD { + // A new gradient's initial line is only a placeholder, so nothing is written until the drag passes the threshold + if self.dragging != GradientDragTarget::New { + self.gradient = self.initial_gradient.clone(); + self.appearance.transform = self.initial_gradient_transform; + self.render_gradient(responses); + } return; } @@ -1181,9 +1185,10 @@ impl Fsm for GradientToolFsmState { return ready_default; } - // If we're in the middle of a drag, abort it first and revert to the initial gradient + // If we're in the middle of a drag, abort it first and revert to the gradient as it began if matches!(state, GradientToolFsmState::Drawing { .. }) { selected_gradient.gradient = selected_gradient.initial_gradient.clone(); + selected_gradient.appearance.transform = selected_gradient.initial_gradient_transform; selected_gradient.render_gradient(responses); responses.add(DocumentMessage::AbortTransaction); } @@ -1559,6 +1564,7 @@ impl Fsm for GradientToolFsmState { // Convert drag_start from document space to effective viewport space let document_to_viewport = document.metadata().document_to_viewport; let drag_start_viewport = document_to_viewport.transform_point2(tool_data.drag_start) + tool_data.auto_pan_shift; + let press_unsnapped_viewport = document_to_viewport.transform_point2(tool_data.drag_start_unsnapped) + tool_data.auto_pan_shift; tool_data.auto_pan_shift = DVec2::ZERO; selected_gradient.update_gradient( @@ -1568,6 +1574,7 @@ impl Fsm for GradientToolFsmState { input.keyboard.get(lock_angle as usize), selected_gradient.appearance.gradient_form, drag_start_viewport, + press_unsnapped_viewport, snap_session, SnapView::new(document, *document_id, input), &mut tool_data.gradient_angle, @@ -1604,7 +1611,13 @@ impl Fsm for GradientToolFsmState { state } (GradientToolFsmState::Drawing { .. }, GradientToolMessage::PointerUp) => { - responses.add(DocumentMessage::EndTransaction); + // A new gradient released where it was pressed is a click, so anything its drag wrote along the way is taken back + if tool_data.selected_gradient.as_ref().is_some_and(|selected| selected.dragging == GradientDragTarget::New) { + let press = document.metadata().document_to_viewport.transform_point2(tool_data.drag_start_unsnapped); + input.mouse.finish_transaction(press, responses); + } else { + responses.add(DocumentMessage::EndTransaction); + } // Clear the selection if we were dragging an endpoint of the gradient which isn't a stop if tool_data.selected_gradient.as_ref().is_some_and(|selected| match selected.dragging { @@ -2717,6 +2730,87 @@ mod test_gradient { assert!(!final_positions.iter().any(|pos| (pos - 0.75).abs() < 0.05), "Stop at position 0.75 should have been deleted"); } + #[tokio::test] + async fn a_click_slipping_under_the_drag_threshold_draws_no_gradient() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.active_document_mut().snapping_state.snapping_enabled = false; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + editor.drag_tool(ToolType::Gradient, 30., 40., 30.5, 40., ModifierKeys::empty()).await; + + assert!( + get_gradients_from_fill(&mut editor).await.is_empty(), + "a click that barely moves shouldn't replace the fill with a gradient" + ); + } + + #[tokio::test] + async fn a_new_gradient_drag_released_back_where_it_was_pressed_draws_no_gradient() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.active_document_mut().snapping_state.snapping_enabled = false; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + editor.select_tool(ToolType::Gradient).await; + editor.move_mouse(30., 40., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(30., 40., ModifierKeys::empty()).await; + editor.move_mouse(60., 40., ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.move_mouse(30.5, 40., ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(30.5, 40., ModifierKeys::empty()).await; + + assert!( + get_gradients_from_fill(&mut editor).await.is_empty(), + "a drag that comes back to where it was pressed shouldn't replace the fill with a gradient" + ); + } + + #[tokio::test] + async fn a_click_beside_a_snap_target_slipping_under_the_drag_threshold_draws_no_gradient() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + // The press lands a few pixels inside the left edge, which it snaps onto + editor.drag_tool(ToolType::Gradient, 3., 50., 3.5, 50., ModifierKeys::empty()).await; + + assert!( + get_gradients_from_fill(&mut editor).await.is_empty(), + "a click that snaps and barely moves shouldn't replace the fill with a gradient" + ); + } + + #[tokio::test] + async fn delete_mid_drag_of_an_end_restores_its_line() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.active_document_mut().snapping_state.snapping_enabled = false; + + editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await; + editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await; + + // A middle stop, so deleting an end leaves a gradient + editor.move_mouse(60., 0., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(60., 0., ModifierKeys::empty()).await; + editor.left_mouseup(60., 0., ModifierKeys::empty()).await; + + // Drag the end down, then press Delete before releasing + editor.move_mouse(100., 0., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(100., 0., ModifierKeys::empty()).await; + editor.move_mouse(100., 50., ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.press(Key::Delete, ModifierKeys::empty()).await; + editor.left_mouseup(100., 50., ModifierKeys::empty()).await; + + let (gradient, transform) = get_gradient_from_fill(&mut editor).await; + assert_eq!(gradient.stops.len(), 2, "the end stop should be deleted"); + let (start, end) = (transform.transform_point2(gradient.start()), transform.transform_point2(gradient.end())); + assert!(start.abs_diff_eq(DVec2::new(0., 0.), 1e-6), "the start should stay put, got {start:?}"); + assert!(end.abs_diff_eq(DVec2::new(60., 0.), 1e-6), "the line should end at the middle stop on the undragged line, got {end:?}"); + } + #[tokio::test] async fn delete_removes_layer_when_no_stop_selected() { let mut editor = EditorTestUtils::create(); @@ -3296,6 +3390,63 @@ mod test_gradient { assert_eq!(stops.len(), 2); } + #[tokio::test] + async fn drag_on_a_layer_drawing_shared_geometry_paints_its_fill() { + use graph_craft::document::NodeId; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + let rectangle = editor.active_document().metadata().all_layers().next().unwrap(); + + // A new layer above the rectangle, whose content is wired from the end of the rectangle's chain so both draw it + let sharing_id = NodeId::new(); + editor + .handle_message(GraphOperationMessage::NewCustomLayer { + id: sharing_id, + nodes: Vec::new(), + parent: LayerNodeIdentifier::ROOT_PARENT, + insert_index: 0, + }) + .await; + let sharing = LayerNodeIdentifier::new_unchecked(sharing_id); + let shared_id = editor + .active_document() + .network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(rectangle.to_node()), &[]) + .and_then(|output| output.node_id()) + .expect("the rectangle should have a chain"); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(shared_id), &InputConnector::layer_secondary_input(sharing_id), &[]); + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![sharing_id] }).await; + + editor.drag_tool(ToolType::Gradient, 10., 50., 90., 50., ModifierKeys::empty()).await; + + let network_interface = &editor.active_document().network_interface; + assert!( + get_upstream_gradient_value_node_id(sharing, network_interface).is_none(), + "a layer drawing shared geometry isn't blank, so it mustn't get a whole-expanse gradient" + ); + assert_eq!( + network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(sharing_id), &[]) + .and_then(|output| output.node_id()), + Some(shared_id), + "the layer should still draw the shared rectangle" + ); + + let fill_node_id = get_fill_node_id_with_direct_fill_input(rectangle, network_interface).expect("the rectangle should have a Fill node"); + let paint = network_interface + .document_network() + .nodes + .get(&fill_node_id) + .and_then(|node| node.input(fill::PaintInput)) + .and_then(|input| input.as_value()); + assert!(matches!(paint, Some(TaggedValue::GradientRamp(_))), "the shared rectangle's Fill should take the gradient"); + } + #[tokio::test] async fn replaces_a_whole_expanse_color_with_a_gradient() { use crate::messages::tool::common_functionality::graph_modification_utils::{get_gradient_stops, get_upstream_color_value_node_id}; diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index 51f099bb8f..ab10565fda 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -23,6 +23,7 @@ use crate::messages::tool::common_functionality::shape_editor::{ use crate::messages::tool::common_functionality::snap_session::{FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView, nudge_translation, snapping_hints}; use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, find_two_param_best_approximate, make_path_editable_is_allowed}; use graphene_std::Color; +use graphene_std::list::List; use graphene_std::renderer::Quad; use graphene_std::transform::ReferencePoint; use graphene_std::uuid::NodeId; @@ -30,7 +31,7 @@ use graphene_std::vector::algorithms::util::pathseg_tangent; use graphene_std::vector::click_target::ClickTargetType; use graphene_std::vector::misc::pathseg_points; use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2, segment_to_handles}; -use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModificationType}; +use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorGeometry, VectorModification, VectorModificationType, WorkingVector}; use kurbo::{DEFAULT_ACCURACY, ParamCurve, ParamCurveNearest, PathSeg, Rect}; use std::vec; @@ -678,8 +679,8 @@ impl PathToolData { SelectionStatus::None => false, SelectionStatus::One(single_selected_point) => { let vector = document.network_interface.compute_modified_vector(single_selected_point.layer).unwrap(); - if single_selected_point.id.get_handle_pair(&vector).is_some() { - let anchor = single_selected_point.id.get_anchor(&vector).expect("Cannot find connected anchor"); + if vector.handle_pair_of(single_selected_point.id).is_some() { + let anchor = vector.anchor_of(single_selected_point.id).expect("Cannot find connected anchor"); vector.all_connected(anchor).count() <= 2 } else { false @@ -828,27 +829,28 @@ impl PathToolData { shape_editor.disable_colinear_handles_state_on_selected(&document.network_interface, responses); } - if handle_drag_from_anchor && let Some((layer, point)) = shape_editor.find_nearest_point_indices(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD) { - // Check that selected point is an anchor - if let (Some(point_id), Some(vector)) = (point.as_anchor(), document.network_interface.compute_modified_vector(layer)) { - let handles = vector.all_connected(point_id).collect::>(); - self.alt_clicked_on_anchor = true; - for handle in &handles { - let modification_type = handle.set_relative_position(DVec2::ZERO); - responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in &vector.colinear_manipulators { - if handles.contains(handle) { - let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; - responses.add(GraphOperationMessage::Vector { layer, modification_type }); - } + // Alt held at drag start on an anchor makes it sharp, unless it's a lone anchor with no handles to retract + if handle_drag_from_anchor + && let Some((layer, point)) = shape_editor.find_nearest_point_indices(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD) + && let (Some(point_id), Some(vector)) = (point.as_anchor(), document.network_interface.compute_modified_vector(layer)) + && let Some(first_handle) = vector.all_connected(point_id).next() + { + self.alt_clicked_on_anchor = true; + let colinear_pairs = vector.colinear_pairs(); + for handle in vector.all_connected(point_id) { + let modification_type = handle.set_relative_position(DVec2::ZERO); + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + for &handles in &colinear_pairs { + if handles.contains(&handle) { + let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } - - let manipulator_point_id = handles[0].to_manipulator_point(); - shape_editor.deselect_all_points(); - shape_editor.select_point_by_layer_and_id(manipulator_point_id, layer); - responses.add(PathToolMessage::SelectedPointUpdated); } + + shape_editor.deselect_all_points(); + shape_editor.select_point_by_layer_and_id(first_handle.to_manipulator_point(), layer); + responses.add(PathToolMessage::SelectedPointUpdated); } if let Some((Some(point), Some(vector), layer)) = shape_editor @@ -857,7 +859,7 @@ impl PathToolData { { let handles = vector .all_connected(point) - .filter(|handle| handle.length(&vector) < 1e-6) + .filter(|handle| vector.handle_length(*handle) < 1e-6) .map(|handle| handle.to_manipulator_point()) .collect::>(); let endpoint = vector.anchor_endpoints().any(|anchor| point == anchor); @@ -964,15 +966,15 @@ impl PathToolData { } for point in state.selected_points() { - let Some(anchor) = point.get_anchor(&vector) else { continue }; + let Some(anchor) = vector.anchor_of(point) else { continue }; moving.anchors.push((layer, anchor)); - let Some([handle1, handle2]) = point.get_handle_pair(&vector) else { continue }; + let Some([handle1, handle2]) = vector.handle_pair_of(point) else { continue }; let Some(handle) = point.as_handle() else { continue }; // Check which handle is selected and which is opposite let opposite = if handle == handle1 { handle2 } else { handle1 }; self.opposite_handle_position = if self.opposite_handle_position.is_none() { - opposite.to_manipulator_point().get_position(&vector) + vector.position_of(opposite.to_manipulator_point()) } else { self.opposite_handle_position }; @@ -998,7 +1000,7 @@ impl PathToolData { let to_document = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface); for point in state.selected_points() { - let Some(position) = point.get_position(&vector) else { continue }; + let Some(position) = vector.position_of(point) else { continue }; let point_start = to_document.transform_point2(position) - slid_so_far; starts.push(point_start); @@ -1104,11 +1106,11 @@ impl PathToolData { }; // Check if handle has a pair (to ignore handles of edges of open paths) - if let Some(handle_pair) = selected_handle_id.get_handle_pair(&vector) { + if let Some(handle_pair) = vector.handle_pair_of(selected_handle_id) { let opposite_handle_length = handle_pair.iter().filter(|&&h| h.to_manipulator_point() != selected_handle_id).find_map(|&h| { - let opp_handle_pos = h.to_manipulator_point().get_position(&vector)?; - let opp_anchor_id = h.to_manipulator_point().get_anchor(&vector)?; - let opp_anchor_pos = vector.point_domain.position_from_id(opp_anchor_id)?; + let opp_handle_pos = vector.position_of(h.to_manipulator_point())?; + let opp_anchor_id = vector.anchor_of(h.to_manipulator_point())?; + let opp_anchor_pos = vector.position_from_id(opp_anchor_id)?; Some((opp_handle_pos - opp_anchor_pos).length()) }); @@ -1141,9 +1143,9 @@ impl PathToolData { let layer_to_document = document.metadata().transform_to_document_if_feeds(*layer, &document.network_interface); let vector = document.network_interface.compute_modified_vector(*layer)?; - let handle_position_local = selected_handle.to_manipulator_point().get_position(&vector)?; - let anchor_id = selected_handle.to_manipulator_point().get_anchor(&vector)?; - let anchor_position_local = vector.point_domain.position_from_id(anchor_id)?; + let handle_position_local = vector.position_of(selected_handle.to_manipulator_point())?; + let anchor_id = vector.anchor_of(selected_handle.to_manipulator_point())?; + let anchor_position_local = vector.position_from_id(anchor_id)?; let handle_position_document = layer_to_document.transform_point2(handle_position_local); let anchor_position_document = layer_to_document.transform_point2(anchor_position_local); @@ -1177,13 +1179,13 @@ impl PathToolData { // If the handle is dragged over one of its adjacent anchors while holding down the Ctrl key, compute the angle based on the tangent formed with the neighboring anchor points. if adjacent_anchor.is_some() && lock_angle && !self.angle_locked { - let anchor = handle_id.get_anchor(&vector); + let anchor = vector.anchor_of(handle_id); let (angle, anchor_position) = calculate_adjacent_anchor_tangent(handle_id, anchor, adjacent_anchor, &vector); let layer_to_document = document.metadata().transform_to_document_if_feeds(*layer, &document.network_interface); - self.adjacent_anchor_offset = handle_id - .get_anchor_position(&vector) + self.adjacent_anchor_offset = vector + .anchor_position_of(handle_id) .and_then(|handle_anchor| anchor_position.map(|adjacent_anchor| layer_to_document.transform_point2(adjacent_anchor) - layer_to_document.transform_point2(handle_anchor))); required_angle = angle; @@ -1229,17 +1231,17 @@ impl PathToolData { handle_angle } - fn get_normalized_tangent(&mut self, point: PointId, segment: SegmentId, vector: &Vector) -> Option { + fn get_normalized_tangent(&mut self, point: PointId, segment: SegmentId, vector: &VectorGeometry) -> Option { let other_point = vector.other_point(segment, point)?; - let position = ManipulatorPointId::Anchor(point).get_position(vector)?; + let position = vector.position_of(ManipulatorPointId::Anchor(point))?; let mut handles = vector.all_connected(other_point); let other_handle = handles.find(|handle| handle.segment == segment)?; - let target_position = if other_handle.length(vector) == 0. { - ManipulatorPointId::Anchor(other_point).get_position(vector)? + let target_position = if vector.handle_length(other_handle) == 0. { + vector.position_of(ManipulatorPointId::Anchor(other_point))? } else { - other_handle.to_manipulator_point().get_position(vector)? + vector.position_of(other_handle.to_manipulator_point())? }; let tangent_vector = target_position - position; @@ -1269,7 +1271,7 @@ impl PathToolData { // Check if that segment exists or it has been removed if let Some(vector_data) = document.network_interface.compute_modified_vector(layer) - && !(vector_data.segment_domain.ids().contains(&segment_id)) + && !(vector_data.segment_ids().contains(&segment_id)) { self.segment = None; } @@ -1346,7 +1348,7 @@ impl PathToolData { }; // Move the anchor to the new position - let Some(current_position) = ManipulatorPointId::Anchor(anchor).get_position(&vector) else { + let Some(current_position) = vector.position_of(ManipulatorPointId::Anchor(anchor)) else { return; }; let delta = new_position - current_position; @@ -1510,7 +1512,7 @@ impl PathToolData { return; }; let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - let Some(point_id) = shape_editor.selected_points().next().unwrap().get_anchor(&vector) else { + let Some(point_id) = vector.anchor_of(*shape_editor.selected_points().next().unwrap()) else { return; }; @@ -1739,7 +1741,7 @@ impl Fsm for PathToolFsmState { } } - // TODO: find the segment ids of which the selected points are a part of + // TODO: find the segment IDs of which the selected points are a part of match tool_options.path_overlay_mode { PathOverlayMode::AllHandles => { @@ -1833,7 +1835,7 @@ impl Fsm for PathToolFsmState { let Some((layer, manipulator_point_id)) = nearest_visible_point_indices else { return }; let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - let Some(position) = manipulator_point_id.get_position(&vector) else { + let Some(position) = vector.position_of(manipulator_point_id) else { error!("No position for hovered point"); return; }; @@ -1960,7 +1962,7 @@ impl Fsm for PathToolFsmState { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; for point in points { - let Some(position) = point.get_position(&vector) else { continue }; + let Some(position) = vector.position_of(point) else { continue }; let transform = document.metadata().transform_to_viewport(layer); let position = transform.transform_point2(position); @@ -2712,16 +2714,13 @@ impl Fsm for PathToolFsmState { // Find points by their positions (with small tolerance for floating point comparison) const POSITION_TOLERANCE: f64 = 1e-6; - let positions = vector.point_domain.positions(); - let point_ids = vector.point_domain.ids(); - let mut start_point_id = None; let mut end_point_id = None; // Get the merged layer's transform to convert local positions to document space let layer_transform = document.metadata().transform_to_document(layer); - for (i, &local_pos) in positions.iter().enumerate() { + for (point_id, local_pos) in vector.anchors() { // Transform the local position to document space for comparison let doc_pos = layer_transform.transform_point2(local_pos); @@ -2729,10 +2728,10 @@ impl Fsm for PathToolFsmState { let end_distance = (doc_pos - end_position).length(); if start_point_id.is_none() && start_distance < POSITION_TOLERANCE { - start_point_id = Some(point_ids[i]); + start_point_id = Some(point_id); } if end_point_id.is_none() && end_distance < POSITION_TOLERANCE { - end_point_id = Some(point_ids[i]); + end_point_id = Some(point_id); } if start_point_id.is_some() && end_point_id.is_some() { break; @@ -2780,7 +2779,7 @@ impl Fsm for PathToolFsmState { // Also get the transform node that is applied on the layer if it exists let transform = document.metadata().transform_to_document(layer); - let mut new_vector = Vector::default(); + let mut new_vector = WorkingVector::default(); let mut selected_points_by_segment = HashSet::new(); old_vector @@ -2792,13 +2791,15 @@ impl Fsm for PathToolFsmState { }); // Add all the selected points - for (point, position) in old_vector.point_domain.iter() { + for (point, position) in old_vector.anchors() { if layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(point)) || selected_points_by_segment.contains(&point) { - new_vector.point_domain.push(point, position); + new_vector.point_ids.push(point); + new_vector.point_positions.push(position); } } - let find_index = |id: PointId| new_vector.point_domain.iter().enumerate().find(|(_, (point_id, _))| *point_id == id).map(|(index, _)| index); + let find_index = |new_vector: &WorkingVector, id: PointId| new_vector.point_ids.iter().position(|&point_id| point_id == id); + let path_beginnings = old_vector.path_beginnings(); // Add segments which have selected ends for (segment_id, segment, start, end) in old_vector.segment_iter() { @@ -2807,21 +2808,28 @@ impl Fsm for PathToolFsmState { let segment_selected = layer_selection_state.is_segment_selected(segment_id); if both_ends_selected || segment_selected { - let Some((start_index, end_index)) = find_index(start).zip(find_index(end)) else { - error!("Point does not exist in point domain"); + let Some((start_index, end_index)) = find_index(&new_vector, start).zip(find_index(&new_vector, end)) else { + error!("Point does not exist in the copied selection"); return PathToolFsmState::Ready; }; - new_vector.segment_domain.push(segment_id, start_index, end_index, segment_to_handles(&segment)); + new_vector.segment_ids.push(segment_id); + new_vector.segment_start.push(start_index); + new_vector.segment_end.push(end_index); + new_vector.segment_handles.push(segment_to_handles(&segment)); + new_vector.segment_begins_path.push(path_beginnings.contains(&segment_id)); } } - for handles in old_vector.colinear_manipulators { - if new_vector.segment_domain.ids().contains(&handles[0].segment) && new_vector.segment_domain.ids().contains(&handles[1].segment) { - new_vector.colinear_manipulators.push(handles); + for handles in old_vector.colinear_pairs() { + if new_vector.segment_ids.contains(&handles[0].segment) && new_vector.segment_ids.contains(&handles[1].segment) { + new_vector.colinear.push(handles); } } - buffer.push((layer, new_vector, transform)); + // The clipboard stores a modification that rebuilds the copied selection from nothing + let (mut copied, mut copied_paths) = (Vector::default(), List::new()); + new_vector.reweave(&mut copied, &mut copied_paths); + buffer.push((layer, VectorModification::create_from_vector(&copied, &copied_paths), transform)); } responses.add(ClipboardMessage::WriteItems { @@ -2875,9 +2883,14 @@ impl Fsm for PathToolFsmState { layer }; - // Create new point ids and add those into the existing vector content + // 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); + let pasted = VectorGeometry::new(pasted_vector, pasted_paths); + + // Create new point IDs and add those into the existing vector content let mut points_map = HashMap::new(); - for (point, position) in new_vector.point_domain.iter() { + for (point, position) in pasted.anchors() { let new_point_id = PointId::generate(); points_map.insert(point, new_point_id); @@ -2886,9 +2899,10 @@ impl Fsm for PathToolFsmState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); } - // Create new segment ids and add the segments into the existing vector content + // Create new segment IDs and add the segments into the existing vector content let mut segments_map = HashMap::new(); - for (segment_id, bezier, start, end) in new_vector.segment_iter() { + let path_beginnings = pasted.path_beginnings(); + for (segment_id, bezier, start, end) in pasted.segment_iter() { let new_segment_id = SegmentId::generate(); segments_map.insert(segment_id, new_segment_id); @@ -2900,10 +2914,19 @@ impl Fsm for PathToolFsmState { 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.colinear_pairs() { let to_new_handle = |handle: HandleId| -> HandleId { HandleId { ty: handle.ty, @@ -2973,7 +2996,7 @@ impl Fsm for PathToolFsmState { }); let mut points_map = HashMap::new(); - for (point, position) in old_vector.point_domain.iter() { + for (point, position) in old_vector.anchors() { // TODO: Either the point is selected or it is an endpoint of a selected segment if layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(point)) || selected_points_by_segment.contains(&point) { @@ -2988,6 +3011,7 @@ impl Fsm for PathToolFsmState { } let mut segments_map = HashMap::new(); + let path_beginnings = old_vector.path_beginnings(); for (segment_id, bezier, start, end) in old_vector.segment_iter() { let both_ends_selected = layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(start)) && layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(end)); @@ -3005,10 +3029,16 @@ impl Fsm for PathToolFsmState { let modification_type = VectorModificationType::InsertSegment { id: new_id, points, handles }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + + // Every duplicated 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_id, breaks: true }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } } } - for handles in old_vector.colinear_manipulators { + for handles in old_vector.colinear_pairs() { let to_new_handle = |handle: HandleId| -> HandleId { HandleId { ty: handle.ty, @@ -3311,7 +3341,7 @@ fn get_selection_status(network_interface: &NodeNetworkInterface, shape_state: & let Some(&point) = shape_state.selected_points().next() else { return SelectionStatus::None; }; - let Some(local_position) = point.get_position(&vector) else { + let Some(local_position) = vector.position_of(point) else { return SelectionStatus::None; }; @@ -3344,12 +3374,12 @@ fn calculate_lock_angle( shape_state: &mut ShapeState, responses: &mut VecDeque, document: &DocumentMessageHandler, - vector: &Vector, + vector: &VectorGeometry, handle_id: ManipulatorPointId, tangent_to_neighboring_tangents: bool, ) -> Option { - let anchor = handle_id.get_anchor(vector)?; - let anchor_position = vector.point_domain.position_from_id(anchor); + let anchor = vector.anchor_of(handle_id)?; + let anchor_position = vector.position_from_id(anchor); let current_segment = handle_id.get_segment(); let points_connected = vector.connected_count(anchor); @@ -3357,17 +3387,17 @@ fn calculate_lock_angle( if points_connected == 1 { calculate_segment_angle(anchor, segment, vector, false) } else { - let opposite_handle = handle_id - .get_handle_pair(vector) + let opposite_handle = vector + .handle_pair_of(handle_id) .iter() .flatten() .find(|&h| h.to_manipulator_point() != handle_id) .copied() .map(|h| h.to_manipulator_point()); - let opposite_handle_position = opposite_handle.and_then(|h| h.get_position(vector)).filter(|pos| (pos - anchor_position).length() > 1e-6); + let opposite_handle_position = opposite_handle.and_then(|h| vector.position_of(h)).filter(|pos| (pos - anchor_position).length() > 1e-6); if let Some(opposite_pos) = opposite_handle_position { - if !vector.colinear_manipulators.iter().flatten().map(|h| h.to_manipulator_point()).any(|h| h == handle_id) { + if !vector.colinear(handle_id) { shape_state.convert_selected_manipulators_to_colinear_handles(responses, document); tool_data.temporary_colinear_handles = true; } @@ -3398,7 +3428,7 @@ fn calculate_lock_angle( } /// The position of the one unselected anchor joined to `anchor`, if the segment joining them has no handles to bend it as `anchor` moves. -fn unselected_neighbor_joined_straight(anchor: PointId, state: &SelectedLayerState, vector: &Vector) -> Option { +fn unselected_neighbor_joined_straight(anchor: PointId, state: &SelectedLayerState, vector: &VectorGeometry) -> Option { let mut unselected = vector.connected_points(anchor).filter(|&neighbor| !state.is_point_selected(ManipulatorPointId::Anchor(neighbor))); let (Some(neighbor), None) = (unselected.next(), unselected.next()) else { return None }; @@ -3411,7 +3441,7 @@ fn unselected_neighbor_joined_straight(anchor: PointId, state: &SelectedLayerSta return None; } - vector.point_domain.position_from_id(neighbor) + vector.position_from_id(neighbor) } /// The document positions of the selected points, along with both ends of each selected segment. @@ -3427,18 +3457,18 @@ fn selected_positions_in_document(shape_editor: &ShapeState, document: &Document .segment_iter() .filter(|&(segment, ..)| state.is_segment_selected(segment)) .flat_map(|(_, _, start, end)| [start, end]); - let positions = selected_points.filter_map(|point| point.get_position(&vector)); - let positions = positions.chain(segment_ends.filter_map(|point| vector.point_domain.position_from_id(point))); + let positions = selected_points.filter_map(|point| vector.position_of(point)); + let positions = positions.chain(segment_ends.filter_map(|point| vector.position_from_id(point))); positions.map(|position| to_document.transform_point2(position)).collect() }) } -fn check_handle_over_adjacent_anchor(handle_id: ManipulatorPointId, vector: &Vector) -> Option { - let (anchor, handle_position) = handle_id.get_anchor(vector).zip(handle_id.get_position(vector))?; +fn check_handle_over_adjacent_anchor(handle_id: ManipulatorPointId, vector: &VectorGeometry) -> Option { + let (anchor, handle_position) = vector.anchor_of(handle_id).zip(vector.position_of(handle_id))?; let check_if_close = |point_id: &PointId| { - let Some(anchor_position) = vector.point_domain.position_from_id(*point_id) else { + let Some(anchor_position) = vector.position_from_id(*point_id) else { return false; }; (anchor_position - handle_position).length() < 10. @@ -3446,15 +3476,15 @@ fn check_handle_over_adjacent_anchor(handle_id: ManipulatorPointId, vector: &Vec vector.connected_points(anchor).find(check_if_close) } -fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointId, anchor: Option, adjacent_anchor: Option, vector: &Vector) -> (Option, Option) { +fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointId, anchor: Option, adjacent_anchor: Option, vector: &VectorGeometry) -> (Option, Option) { // Early return if no anchor or no adjacent anchors let Some((dragged_handle_anchor, adjacent_anchor)) = anchor.zip(adjacent_anchor) else { return (None, None); }; - let adjacent_anchor_position = vector.point_domain.position_from_id(adjacent_anchor); + let adjacent_anchor_position = vector.position_from_id(adjacent_anchor); - let handles: Vec<_> = vector.all_connected(adjacent_anchor).filter(|handle| handle.length(vector) > 1e-6).collect(); + let handles: Vec<_> = vector.all_connected(adjacent_anchor).filter(|handle| vector.handle_length(*handle) > 1e-6).collect(); match handles.len() { 0 => { @@ -3494,8 +3524,8 @@ fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointI return (None, None); }; - let angle = shared_segment_handle - .get_position(vector) + let angle = vector + .position_of(shared_segment_handle) .zip(adjacent_anchor_position) .and_then(|(handle, anchor)| DVec2::X.try_angle_to(handle - anchor)); @@ -3765,7 +3795,7 @@ mod test_path_tool { let vector = document.network_interface.compute_modified_vector(layer).expect("the path should have a vector"); let to_viewport = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); - vector.point_domain.positions().iter().map(|&position| to_viewport.transform_point2(position)).collect() + vector.anchor_positions().iter().map(|&position| to_viewport.transform_point2(position)).collect() } fn assert_anchors(editor: &EditorTestUtils, layer: LayerNodeIdentifier, expected: &[DVec2]) { @@ -3777,6 +3807,10 @@ mod test_path_tool { } } + fn selected_points(editor: &EditorTestUtils) -> Vec { + editor.editor.dispatcher.message_handlers.tool_message_handler.shape_editor.selected_points().copied().collect() + } + /// Presses the Path tool at a viewport position, which picks up whatever point is there. async fn press_at(editor: &mut EditorTestUtils, position: DVec2) { editor.select_tool(ToolType::Path).await; @@ -3877,8 +3911,8 @@ mod test_path_tool { let handle_position = |editor: &EditorTestUtils| { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("the path should have a vector"); - let segment = vector.segment_domain.ids()[0]; - let handle = ManipulatorPointId::EndHandle(segment).get_position(&vector).expect("the segment should have a handle at its end"); + let segment = vector.segment_ids()[0]; + let handle = vector.position_of(ManipulatorPointId::EndHandle(segment)).expect("the segment should have a handle at its end"); document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface).transform_point2(handle) }; let handle = anchor * 2. - dragged_out; @@ -4015,4 +4049,119 @@ mod test_path_tool { let moved = DVec2::new(3., 0.); assert_anchors(&editor, layer, &[first + moved, second + moved, unselected]); } + + #[tokio::test] + async fn alt_clicking_an_anchor_without_segments_selects_it() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_path(&mut editor, &[A, B, C]).await; + + // Deleting the middle anchor without joining its neighbors leaves both ends without segments + editor.click_tool(ToolType::Path, MouseKeys::LEFT, B, ModifierKeys::empty()).await; + editor.handle_message(PathToolMessage::DeleteAndBreakPath).await; + assert_anchors(&editor, layer, &[A, C]); + + editor.click_tool(ToolType::Path, MouseKeys::LEFT, A, ModifierKeys::ALT).await; + let selected = selected_points(&editor); + assert!( + matches!(selected[..], [ManipulatorPointId::Anchor(_)]), + "only the Alt-clicked anchor should be selected, not {selected:?}" + ); + } + + #[tokio::test] + async fn copied_points_paste_back_as_the_same_curves_and_smooth_pairs() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + // Dragging out of the middle anchor with the Pen gives it a smooth pair of handles + let dragged_out = B + DVec2::new(60., 25.); + editor.click_tool(ToolType::Pen, MouseKeys::LEFT, A, ModifierKeys::empty()).await; + editor.move_mouse(B.x, B.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(B.x, B.y, ModifierKeys::empty()).await; + editor.move_mouse(dragged_out.x, dragged_out.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(dragged_out.x, dragged_out.y, ModifierKeys::empty()).await; + editor.click_tool(ToolType::Pen, MouseKeys::LEFT, C, ModifierKeys::empty()).await; + editor.press(Key::Enter, ModifierKeys::empty()).await; + + let layer = editor.get_selected_layer().await.expect("the drawn path should be selected"); + let geometry = |editor: &EditorTestUtils| editor.active_document().network_interface.compute_modified_vector(layer).expect("the path should have a vector"); + let original = geometry(&editor); + assert_eq!(original.colinear_pairs().len(), 1, "the dragged-out anchor should be smooth"); + + // Copy every point and paste them back into the same layer + editor.select_tool(ToolType::Path).await; + editor.handle_message(PathToolMessage::SelectAll).await; + let clipboard = editor + .handle_message(ClipboardMessage::CopyLayers) + .await + .into_iter() + .find_map(|message| match message { + FrontendMessage::TriggerClipboardWrite { content } => Some(content), + _ => None, + }) + .expect("copying points should write a payload to the clipboard"); + editor + .handle_message(ClipboardMessage::ReadClipboard { + content: ClipboardContentRaw::Text(clipboard), + }) + .await; + + // Each curve now appears a second time under a new ID + let control_points = |segment: kurbo::PathSeg| match segment { + kurbo::PathSeg::Line(line) => vec![line.p0, line.p1], + kurbo::PathSeg::Quad(quad) => vec![quad.p0, quad.p1, quad.p2], + kurbo::PathSeg::Cubic(cubic) => vec![cubic.p0, cubic.p1, cubic.p2, cubic.p3], + }; + let same_curve = |a: kurbo::PathSeg, b: kurbo::PathSeg| { + let (a, b) = (control_points(a), control_points(b)); + a.len() == b.len() && a.iter().zip(&b).all(|(a, b)| a.distance(*b) < 1e-9) + }; + + let pasted = geometry(&editor); + let original_ids = original.segment_ids(); + let pasted_segments: Vec<_> = pasted.segment_iter().filter(|(id, ..)| !original_ids.contains(id)).map(|(_, segment, ..)| segment).collect(); + assert_eq!(pasted_segments.len(), original_ids.len()); + for (_, segment, ..) in original.segment_iter() { + assert!( + pasted_segments.iter().any(|&pasted| same_curve(pasted, segment)), + "no pasted copy of {segment:?} among {pasted_segments:?}" + ); + } + + assert_eq!(pasted.colinear_pairs().len(), 2, "the pasted copy of the smooth anchor should be smooth too"); + } + + // The ellipse's handles come from its generator, so the first typed position is the Path node's first edit to the handle + #[tokio::test] + async fn a_typed_handle_position_moves_the_handle_there() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_ellipse(100., 100., 300., 200.).await; + let layer = editor.get_selected_layer().await.expect("the drawn ellipse should be selected"); + + let handle_in_document = |editor: &EditorTestUtils, handle: ManipulatorPointId| { + let document = editor.active_document(); + let vector = document.network_interface.compute_modified_vector(layer).expect("the ellipse should have a vector"); + let to_document = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface); + to_document.transform_point2(vector.position_of(handle).expect("the handle should exist")) + }; + + let segment = { + let document = editor.active_document(); + let vector = document.network_interface.compute_modified_vector(layer).expect("the ellipse should have a vector"); + vector.segment_ids()[0] + }; + let handle = ManipulatorPointId::PrimaryHandle(segment); + let before = handle_in_document(&editor, handle); + + editor.select_tool(ToolType::Path).await; + editor.editor.dispatcher.message_handlers.tool_message_handler.shape_editor.select_point_by_layer_and_id(handle, layer); + editor.handle_message(PathToolMessage::SelectedPointUpdated).await; + editor.handle_message(PathToolMessage::SelectedPointXChanged { new_x: before.x + 5. }).await; + + let after = handle_in_document(&editor, handle); + assert!(after.distance(before + DVec2::new(5., 0.)) < 1e-6, "the handle moved from {before} to {after}"); + } } diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs index 418a07a2ef..1c30beb7d0 100644 --- a/editor/src/messages/tool/tool_messages/pen_tool.rs +++ b/editor/src/messages/tool/tool_messages/pen_tool.rs @@ -22,7 +22,7 @@ use graphene_std::Color; use graphene_std::vector::misc::pathseg_points; use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; use graphene_std::vector::style::FillChoice; -use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType}; +use graphene_std::vector::{PointId, SegmentId, VectorGeometry, VectorModificationType}; use kurbo::{BezPath, CubicBez, PathSeg}; #[derive(Default, ExtractField)] @@ -531,7 +531,7 @@ impl PenToolData { } /// Check whether target handle is primary, end, or `self.handle_end` - fn check_end_handle_type(&self, vector: &Vector) -> TargetHandle { + fn check_end_handle_type(&self, vector: &VectorGeometry) -> TargetHandle { match (self.handle_end, self.prior_segment_endpoint, self.prior_segment, self.path_closed) { (Some(_), _, _, false) => TargetHandle::PreviewInHandle, (None, Some(point), Some(segment), false) | (Some(_), Some(point), Some(segment), true) => { @@ -545,7 +545,7 @@ impl PenToolData { } } - fn check_grs_end_handle(&self, vector: &Vector) -> TargetHandle { + fn check_grs_end_handle(&self, vector: &VectorGeometry) -> TargetHandle { let Some(point) = self.latest_point().map(|point| point.id) else { return TargetHandle::None }; let Some(segment) = self.prior_segment else { return TargetHandle::None }; @@ -556,7 +556,7 @@ impl PenToolData { } } - fn get_opposite_handle_type(&self, handle_type: TargetHandle, vector: &Vector) -> TargetHandle { + fn get_opposite_handle_type(&self, handle_type: TargetHandle, vector: &VectorGeometry) -> TargetHandle { match handle_type { TargetHandle::FuturePreviewOutHandle => self.check_end_handle_type(vector), TargetHandle::PreviewInHandle => match (self.path_closed, self.prior_segment_endpoint, self.prior_segment) { @@ -596,22 +596,28 @@ impl PenToolData { } TargetHandle::PriorInHandle(segment) => { let relative_position = delta - anchor_pos; - let modification_type = VectorModificationType::SetEndHandle { segment, relative_position }; + let modification_type = VectorModificationType::SetHandlePosition { + handle: HandleId::end(segment), + relative_position, + }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } TargetHandle::PriorOutHandle(segment) => { let relative_position = delta - anchor_pos; - let modification_type = VectorModificationType::SetPrimaryHandle { segment, relative_position }; + let modification_type = VectorModificationType::SetHandlePosition { + handle: HandleId::primary(segment), + relative_position, + }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } TargetHandle::None => {} } } - fn target_handle_position(&self, handle_type: TargetHandle, vector: &Vector) -> Option { + fn target_handle_position(&self, handle_type: TargetHandle, vector: &VectorGeometry) -> Option { match handle_type { - TargetHandle::PriorOutHandle(segment) => ManipulatorPointId::PrimaryHandle(segment).get_position(vector), - TargetHandle::PriorInHandle(segment) => ManipulatorPointId::EndHandle(segment).get_position(vector), + TargetHandle::PriorOutHandle(segment) => vector.position_of(ManipulatorPointId::PrimaryHandle(segment)), + TargetHandle::PriorInHandle(segment) => vector.position_of(ManipulatorPointId::EndHandle(segment)), TargetHandle::PreviewInHandle => self.handle_end, TargetHandle::FuturePreviewOutHandle => Some(self.next_handle_start), TargetHandle::None => None, @@ -663,7 +669,7 @@ impl PenToolData { let into_merged = self.merging_from.map_or(DAffine2::IDENTITY, |previous| layer_to_document.inverse() * previous); for point in &mut self.latest_points { - let Some(pos) = vector.point_domain.position_from_id(point.id) else { continue }; + let Some(pos) = vector.position_from_id(point.id) else { continue }; point.handle_start = pos + into_merged.transform_vector2(point.handle_start - point.pos); point.pos = pos; } @@ -671,7 +677,7 @@ impl PenToolData { } /// Re-anchors the in-progress preview segment on the current anchor after undo or redo moved it, using the re-evaluated layer transform. - fn resume_preview_from_current_anchor(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, vector: &Vector, responses: &mut VecDeque) { + fn resume_preview_from_current_anchor(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, vector: &VectorGeometry, responses: &mut VecDeque) { // The segments meeting the current anchor are the ones whose handles the overlays show and the angle lock references let connected_segments: Vec = self .latest_point() @@ -757,9 +763,9 @@ impl PenToolData { } } - fn close_path_on_point(&mut self, vector: &Vector, document: &DocumentMessageHandler, id: PointId, transform: &DAffine2) -> bool { + fn close_path_on_point(&mut self, vector: &VectorGeometry, document: &DocumentMessageHandler, id: PointId, transform: &DAffine2) -> bool { for id in vector.anchor_points().filter(|&point| point != id) { - let Some(pos) = vector.point_domain.position_from_id(id) else { continue }; + let Some(pos) = vector.position_from_id(id) else { continue }; let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(self.next_point)); let snap_point_tolerance_squared = crate::consts::SNAP_POINT_TOLERANCE.powi(2); @@ -815,7 +821,7 @@ impl PenToolData { let start = self.latest_point()?.id; let transform = document.metadata().document_to_viewport * transform; for id in vector.anchor_points().filter(|&point| point != start) { - let Some(pos) = vector.point_domain.position_from_id(id) else { continue }; + let Some(pos) = vector.position_from_id(id) else { continue }; let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point)); let snap_point_tolerance_squared = crate::consts::SNAP_POINT_TOLERANCE.powi(2); if transformed_distance_between_squared < snap_point_tolerance_squared { @@ -839,12 +845,12 @@ impl PenToolData { && let Some((handles, handle1_pos)) = match self.get_opposite_handle_type(TargetHandle::PreviewInHandle, &vector) { TargetHandle::PriorOutHandle(segment) => { let handles = [HandleId::end(id), HandleId::primary(segment)]; - let handle1_pos = handles[1].to_manipulator_point().get_position(&vector); + let handle1_pos = vector.position_of(handles[1].to_manipulator_point()); handle1_pos.map(|pos| (handles, pos)) } TargetHandle::PriorInHandle(segment) => { let handles = [HandleId::end(id), HandleId::end(segment)]; - let handle1_pos = handles[1].to_manipulator_point().get_position(&vector); + let handle1_pos = vector.position_of(handles[1].to_manipulator_point()); handle1_pos.map(|pos| (handles, pos)) } _ => None, @@ -872,7 +878,7 @@ impl PenToolData { [HandleId::primary(last_segment), HandleId::primary(id)] }; - if let Some(h1) = handles[0].to_manipulator_point().get_position(&vector) { + if let Some(h1) = vector.position_of(handles[0].to_manipulator_point()) { let colinear = is_almost_colinear(last_point.pos, h1, last_point.handle_start); responses.add(GraphOperationMessage::Vector { layer, @@ -894,7 +900,7 @@ impl PenToolData { } /// Snaps the slide of the anchor and its handles while Space is held, and returns how far they move in layer space. - fn space_anchor_handle_snap(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, mouse: DVec2, vector: &Vector) -> Option { + fn space_anchor_handle_snap(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, mouse: DVec2, vector: &VectorGeometry) -> Option { let reference_handle = if self.path_closed { TargetHandle::PreviewInHandle } else { TargetHandle::FuturePreviewOutHandle }; let reference_position = transform.transform_point2(self.target_handle_position(reference_handle, vector)?); @@ -996,7 +1002,7 @@ impl PenToolData { Some(PenToolFsmState::DraggingHandle(self.handle_mode)) } - fn move_anchor_and_handles(&mut self, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque, vector: &Vector) { + fn move_anchor_and_handles(&mut self, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque, vector: &VectorGeometry) { if self.handle_end.is_none() && let Some(latest_pt) = self.latest_point_mut() { @@ -1122,7 +1128,7 @@ impl PenToolData { } /// Makes the opposite handle equidistant or locks its length. - fn adjust_handle_length(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &Vector) { + fn adjust_handle_length(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &VectorGeometry) { let opposite_handle_type = self.get_opposite_handle_type(self.handle_type, vector); match self.handle_mode { HandleMode::ColinearEquidistant => { @@ -1159,7 +1165,7 @@ impl PenToolData { } } - fn apply_colinear_constraint(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, anchor_pos: DVec2, vector: &Vector) { + fn apply_colinear_constraint(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, anchor_pos: DVec2, vector: &VectorGeometry) { let Some(handle) = self.target_handle_position(self.handle_type, vector) else { return }; if (anchor_pos - handle).length() < 1e-6 && self.modifiers.lock_angle { @@ -1193,7 +1199,7 @@ impl PenToolData { if let Some(vector) = document.network_interface.compute_modified_vector(layer) { let transform = document.metadata().document_to_viewport * transform; for point in vector.anchor_points() { - let Some(pos) = vector.point_domain.position_from_id(point) else { continue }; + let Some(pos) = vector.position_from_id(point) else { continue }; let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(self.next_point)); let snap_point_tolerance_squared = crate::consts::SNAP_POINT_TOLERANCE.powi(2); if transformed_distance_between_squared < snap_point_tolerance_squared { @@ -1367,7 +1373,7 @@ impl PenToolData { /// Perform extension of an existing path fn extend_existing_path(&mut self, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, point: PointId, position: DVec2) { - let vector: Option = document.network_interface.compute_modified_vector(layer); + let vector: Option = document.network_interface.compute_modified_vector(layer); let (handle_start, in_segment) = if let Some(vector) = &vector && vector.connected_count(point) <= 1 { @@ -1437,8 +1443,8 @@ impl PenToolData { } } - fn set_lock_angle(&mut self, vector: &Vector, anchor: PointId, segment: Option) { - let anchor_position = vector.point_domain.position_from_id(anchor); + fn set_lock_angle(&mut self, vector: &VectorGeometry, anchor: PointId, segment: Option) { + let anchor_position = vector.position_from_id(anchor); let Some((anchor_position, segment)) = anchor_position.zip(segment) else { self.handle_mode = HandleMode::Free; @@ -1825,7 +1831,7 @@ impl Fsm for PenToolFsmState { && let Some(mut vector) = document.network_interface.compute_modified_vector(layer) { let closest_point = vector.anchor_points().filter(|&id| id != start).find(|&id| { - vector.point_domain.position_from_id(id).is_some_and(|pos| { + vector.position_from_id(id).is_some_and(|pos| { let dist_sq = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point)); dist_sq < crate::consts::SNAP_POINT_TOLERANCE.powi(2) }) @@ -1843,10 +1849,8 @@ impl Fsm for PenToolFsmState { for path in closed_paths { let segments = path.edges.iter().filter_map(|edge| { vector - .segment_domain - .iter() - .find(|(id, _, _, _)| id == &edge.id) - .map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) }) + .segment_with_pool_endpoints(edge.id) + .map(|(segment, start, end)| if start == edge.start { (segment, start, end) } else { (segment.reverse(), end, start) }) }); if let Some(bezpath) = vector.bezpath_from_segments_ignore_discontinuities(segments) { fill_region.extend(bezpath.elements().iter().copied()); @@ -1972,7 +1976,7 @@ impl Fsm for PenToolFsmState { } (PenToolFsmState::PlacingAnchor, PenToolMessage::Undo) => { let vector = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)); - let anchor_exists = |point: &LastPoint| vector.as_ref().is_some_and(|vector| vector.point_domain.position_from_id(point.id).is_some()); + let anchor_exists = |point: &LastPoint| vector.as_ref().is_some_and(|vector| vector.position_from_id(point.id).is_some()); // Rewind past the anchors the reverted path no longer contains, remembering them so redo can advance back through them while tool_data.point_index > 0 && !tool_data.latest_point().is_some_and(anchor_exists) { @@ -1998,7 +2002,7 @@ impl Fsm for PenToolFsmState { }; // Advance only through the remembered anchors the re-applied step actually brought back - let anchor_exists = |point: &LastPoint| vector.point_domain.position_from_id(point.id).is_some(); + let anchor_exists = |point: &LastPoint| vector.position_from_id(point.id).is_some(); let mut advanced = false; while tool_data.latest_points.get(tool_data.point_index + 1).is_some_and(anchor_exists) { tool_data.point_index += 1; @@ -2240,7 +2244,7 @@ impl Fsm for PenToolFsmState { (PenToolFsmState::DraggingHandle(..), PenToolMessage::Confirm) => { // Confirm to end path if let Some((vector, layer)) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)).zip(layer) { - let single_point_in_layer = vector.point_domain.ids().len() == 1; + let single_point_in_layer = vector.anchor_points().count() == 1; tool_data.finish_placing_handle(snap_session, view, transform, responses); let latest_points = tool_data.point_index == 0; @@ -2292,7 +2296,7 @@ impl Fsm for PenToolFsmState { } (PenToolFsmState::PlacingAnchor, PenToolMessage::Abort) => { let should_delete_layer = if let Some(vector) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)) { - vector.point_domain.ids().len() == 1 + vector.anchor_points().count() == 1 } else { false }; @@ -2398,10 +2402,10 @@ mod test_pen_tool { use crate::test_utils::test_prelude::*; use glam::DAffine2; use graphene_std::vector::misc::ManipulatorPointId; - use graphene_std::vector::{PointId, SegmentId, Vector}; + use graphene_std::vector::{PointId, SegmentId, VectorGeometry}; /// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away. - fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, Vector)> { + fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> { let document = editor.active_document(); let path_identifier = DefinitionIdentifier::Network("Path".into()); let mut path_layers = document @@ -2417,8 +2421,8 @@ mod test_pen_tool { fn assert_path_shape(editor: &EditorTestUtils, points: usize, segments: usize) { let (_, vector) = drawn_path(editor).expect("Expected a drawn path"); - assert_eq!(vector.point_domain.ids().len(), points, "Unexpected point count"); - assert_eq!(vector.segment_domain.ids().len(), segments, "Unexpected segment count"); + assert_eq!(vector.anchor_points().count(), points, "Unexpected point count"); + assert_eq!(vector.segment_ids().len(), segments, "Unexpected segment count"); } /// Asserts the path's anchors sit at the given viewport positions, in placement order, and that each segment joins consecutive anchors. @@ -2426,17 +2430,17 @@ mod test_pen_tool { let (layer, vector) = drawn_path(editor).expect("Expected a drawn path"); let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); - let anchor_ids = vector.point_domain.ids(); + let anchor_ids = vector.anchor_points().collect::>(); assert_eq!(anchor_ids.len(), expected.len(), "Unexpected point count"); for (index, (&id, &expected_position)) in anchor_ids.iter().zip(expected).enumerate() { - let position = layer_to_viewport.transform_point2(vector.point_domain.position_from_id(id).unwrap()); + let position = layer_to_viewport.transform_point2(vector.position_from_id(id).unwrap()); assert!( position.distance(expected_position) < 1e-6, "Anchor {index} is at {position:?} but was expected at {expected_position:?}" ); } - let segment_ids = vector.segment_domain.ids(); + let segment_ids = vector.segment_ids(); assert_eq!(segment_ids.len(), expected.len().saturating_sub(1), "Unexpected segment count"); for (index, &segment) in segment_ids.iter().enumerate() { assert_eq!(vector.segment_start_from_id(segment), Some(anchor_ids[index]), "Segment {index} does not start at anchor {index}"); @@ -2643,7 +2647,7 @@ mod test_pen_tool { fn anchor_positions(editor: &EditorTestUtils) -> Vec { let (layer, vector) = drawn_path(editor).expect("Expected a drawn path"); let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); - vector.point_domain.positions().iter().map(|&position| layer_to_viewport.transform_point2(position)).collect() + vector.anchor_positions().into_iter().map(|position| layer_to_viewport.transform_point2(position)).collect() } async fn set_space_held(editor: &mut EditorTestUtils, held: bool) { @@ -2759,8 +2763,8 @@ mod test_pen_tool { // The last segment runs from C back to A rather than to a new anchor beside it let (_, vector) = drawn_path(&editor).expect("Expected a drawn path"); - let anchors = vector.point_domain.ids(); - let closing = vector.segment_domain.ids()[2]; + let anchors: Vec<_> = vector.anchor_points().collect(); + let closing = vector.segment_ids()[2]; assert_eq!(vector.segment_start_from_id(closing), Some(anchors[2])); assert_eq!(vector.segment_end_from_id(closing), Some(anchors[0])); assert!(anchor_positions(&editor)[0].distance(A) < 1e-6); @@ -2851,16 +2855,13 @@ mod test_pen_tool { let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); let handles = vector - .segment_domain - .ids() - .iter() - .flat_map(|&segment| [ManipulatorPointId::PrimaryHandle(segment), ManipulatorPointId::EndHandle(segment)]) - .filter_map(|handle| handle.get_position(&vector)); + .segment_ids() + .into_iter() + .flat_map(|segment| [ManipulatorPointId::PrimaryHandle(segment), ManipulatorPointId::EndHandle(segment)]) + .filter_map(|handle| vector.position_of(handle)); let mut positions: Vec = vector - .point_domain - .positions() - .iter() - .copied() + .anchor_positions() + .into_iter() .chain(handles) .map(|position| layer_to_viewport.transform_point2(position)) .collect(); @@ -2937,7 +2938,7 @@ mod test_pen_tool { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("The second path should have a vector"); - let first = document.metadata().transform_to_viewport(layer).transform_point2(vector.point_domain.positions()[0]); + let first = document.metadata().transform_to_viewport(layer).transform_point2(vector.anchor_positions()[0]); // Its next anchor has a handle dragged out of it let (anchor, handle) = (DVec2::new(260., 240.), DVec2::new(300., 270.)); @@ -2958,42 +2959,34 @@ mod test_pen_tool { let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path"); let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); let leaves_the_anchor = |&segment: &SegmentId| { - let start = vector.segment_start_from_id(segment).and_then(|point| vector.point_domain.position_from_id(point)); + let start = vector.segment_start_from_id(segment).and_then(|point| vector.position_from_id(point)); start.is_some_and(|start| layer_to_viewport.transform_point2(start).distance(anchor) < 1e-6) }; let joining = vector - .segment_domain - .ids() + .segment_ids() .iter() .copied() .find(|segment| leaves_the_anchor(segment)) .expect("A segment should leave the anchor"); - let leaving = ManipulatorPointId::PrimaryHandle(joining).get_position(&vector).expect("The joining segment should have a handle"); + let leaving = vector.position_of(ManipulatorPointId::PrimaryHandle(joining)).expect("The joining segment should have a handle"); let leaving = layer_to_viewport.transform_point2(leaving); assert!(leaving.distance(handle) < 1e-6, "the joining segment's handle is at {leaving}"); } /// Finds the point ID whose viewport position is within tolerance of `target`. - fn get_anchor_near(vector: &Vector, layer_to_viewport: DAffine2, target: DVec2) -> PointId { + fn get_anchor_near(vector: &VectorGeometry, layer_to_viewport: DAffine2, target: DVec2) -> PointId { vector - .point_domain - .ids() - .iter() - .copied() - .find(|&id| { - let pos = vector.point_domain.position_from_id(id).unwrap(); - layer_to_viewport.transform_point2(pos).distance(target) < 1e-6 - }) + .anchors() + .find(|&(_id, pos)| layer_to_viewport.transform_point2(pos).distance(target) < 1e-6) + .map(|(id, _pos)| id) .unwrap_or_else(|| panic!("No anchor found near {target}")) } /// Finds the segment that connects two given point IDs (in either direction). - fn get_segment_between(vector: &Vector, point_a: PointId, point_b: PointId) -> SegmentId { + fn get_segment_between(vector: &VectorGeometry, point_a: PointId, point_b: PointId) -> SegmentId { vector - .segment_domain - .ids() - .iter() - .copied() + .segment_ids() + .into_iter() .find(|&segment| { let start = vector.segment_start_from_id(segment); let end = vector.segment_end_from_id(segment); @@ -3003,11 +2996,11 @@ mod test_pen_tool { } /// Finds the handle position on `segment` that corresponds to `point`. - fn get_handle_at(vector: &Vector, segment: SegmentId, point: PointId) -> Option { + fn get_handle_at(vector: &VectorGeometry, segment: SegmentId, point: PointId) -> Option { if vector.segment_start_from_id(segment) == Some(point) { - ManipulatorPointId::PrimaryHandle(segment).get_position(vector) + vector.position_of(ManipulatorPointId::PrimaryHandle(segment)) } else { - ManipulatorPointId::EndHandle(segment).get_position(vector) + vector.position_of(ManipulatorPointId::EndHandle(segment)) } } @@ -3038,12 +3031,43 @@ mod test_pen_tool { // The incoming handle stays opposite the outgoing one, which was dragged out from the anchor before it moved let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path"); - let segment = vector.segment_domain.ids()[0]; - let incoming = ManipulatorPointId::EndHandle(segment).get_position(&vector).expect("The segment should have an incoming handle"); + let segment = vector.segment_ids()[0]; + let incoming = vector.position_of(ManipulatorPointId::EndHandle(segment)).expect("The segment should have an incoming handle"); let incoming = editor.active_document().metadata().transform_to_viewport(layer).transform_point2(incoming); assert!(incoming.distance(corner + anchor - handle) < 1e-6, "the incoming handle is at {incoming}"); } + #[tokio::test] + async fn a_handle_grabbed_with_g_follows_the_pointer_when_zoomed() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.handle_message(NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }).await; + let zoom = editor.active_document().metadata().document_to_viewport.matrix2.x_axis.length(); + assert!((zoom - 1.).abs() > 0.1, "the view should be zoomed, not at {zoom}"); + + // The second anchor's outgoing handle is dragged out, then grabbed and moved by as much as the pointer + let (start, anchor, handle) = (DVec2::new(100., 300.), DVec2::new(250., 220.), DVec2::new(330., 230.)); + click_pen(&mut editor, start).await; + editor.move_mouse(anchor.x, anchor.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(anchor.x, anchor.y, ModifierKeys::empty()).await; + editor.move_mouse(handle.x, handle.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(handle.x, handle.y, ModifierKeys::empty()).await; + + let (grip, travel) = (DVec2::new(500., 150.), DVec2::new(40., 70.)); + editor.move_mouse(grip.x, grip.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.press(Key::KeyG, ModifierKeys::empty()).await; + editor.move_mouse(grip.x + travel.x, grip.y + travel.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.press(Key::Enter, ModifierKeys::empty()).await; + + // The next segment starts with the moved handle + click_pen(&mut editor, DVec2::new(450., 400.)).await; + let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path"); + let segment = vector.segment_ids()[1]; + let outgoing = vector.position_of(ManipulatorPointId::PrimaryHandle(segment)).expect("The segment should have an outgoing handle"); + let outgoing = editor.active_document().metadata().transform_to_viewport(layer).transform_point2(outgoing); + assert!(outgoing.distance(handle + travel) < 1e-6, "the handle is at {outgoing} rather than {}", handle + travel); + } + #[tokio::test] async fn extending_from_anchor_with_multiple_segments_does_not_create_colinear_handle() { let mut editor = EditorTestUtils::create(); diff --git a/editor/src/messages/tool/tool_messages/select_tool.rs b/editor/src/messages/tool/tool_messages/select_tool.rs index 66ce265b73..8d5b16e254 100644 --- a/editor/src/messages/tool/tool_messages/select_tool.rs +++ b/editor/src/messages/tool/tool_messages/select_tool.rs @@ -17,7 +17,7 @@ use crate::messages::tool::common_functionality::color_selector::{ use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::measure; -use crate::messages::tool::common_functionality::pivot::{PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget}; +use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget}; use crate::messages::tool::common_functionality::shape_editor::SelectionShapeType; use crate::messages::tool::common_functionality::snap_session::{BoxFeatures, FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView, snapping_hints}; use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget}; @@ -545,6 +545,8 @@ struct SelectToolData { bounding_box_manager: Option, cursor: MouseCursorIcon, pivot_gizmo: PivotGizmo, + /// The pivot as it was when a drag of it began, restored if the drag is aborted. + pivot_before_drag: Option, pivot_gizmo_start: Option, pivot_gizmo_shift: Option, compass_rose: CompassRose, @@ -1358,6 +1360,7 @@ impl Fsm for SelectToolFsmState { let state = if let Some(state) = tool_data.state_from_pivot_gizmo(input.mouse.position) { responses.add(DocumentMessage::StartTransaction); + tool_data.pivot_before_drag = Some(tool_data.pivot_gizmo.pivot.clone()); // The pivot snaps to the selected layers too, since they stay put while it moves snap_session.begin_gesture(SnapView::new(document, *document_id, input), Moving::default()); @@ -1463,6 +1466,19 @@ impl Fsm for SelectToolFsmState { (SelectToolFsmState::DraggingPivot, SelectToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); + // The pivot lives in the tool rather than the document, so aborting the transaction doesn't put it back + if let Some(pivot) = tool_data.pivot_before_drag.take() { + let reported = tool_data.pivot_gizmo.pivot.old_pivot_position; + tool_data.pivot_gizmo.pivot = pivot; + + let pivot_gizmo = tool_data.pivot_gizmo(); + responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo }); + responses.add(OverlaysMessage::Draw); + + // Only the tool keeps its last reported reference point, which makes the control bar refresh + tool_data.pivot_gizmo.pivot.old_pivot_position = reported; + } + let selection = tool_data.nested_selection_behavior; SelectToolFsmState::Ready { selection } } @@ -1817,6 +1833,7 @@ impl Fsm for SelectToolFsmState { let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON; let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction }; + tool_data.pivot_before_drag = None; let pivot_gizmo = tool_data.pivot_gizmo(); responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo }); @@ -3030,6 +3047,34 @@ mod test_select_tool { assert_bounds(&editor, layer, turned_bounds([from, to], middle, FRAC_PI_2)); } + #[tokio::test] + async fn a_typed_turn_after_escaping_a_pivot_drag_and_panning_goes_about_the_restored_pivot() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (from, to) = (DVec2::new(300., 300.), DVec2::new(420., 380.)); + let layer = draw_rectangle(&mut editor, from, to).await; + turn_on_the_pivot(&mut editor).await; + + // The pivot is taken out of the way, put back in the middle by Esc, then followed by a pan of the view + let middle = DVec2::new(360., 340.); + press_cage_at(&mut editor, middle).await; + move_to(&mut editor, DVec2::new(500., 220.), ModifierKeys::empty()).await; + editor.press(Key::Escape, ModifierKeys::empty()).await; + editor.left_mouseup(500., 220., ModifierKeys::empty()).await; + let pan = DVec2::new(40., -30.); + editor.handle_message(NavigationMessage::CanvasPan { delta: pan }).await; + editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.move_mouse(600., 500., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.handle_message(TransformLayerMessage::BeginRotate).await; + for digit in [9, 0] { + editor.handle_message(TransformLayerMessage::TypeDigit { digit }).await; + } + editor.handle_message(TransformLayerMessage::ApplyTransformOperation { final_transform: true }).await; + + assert_bounds(&editor, layer, turned_bounds([from + pan, to + pan], middle + pan, FRAC_PI_2)); + } + fn snap_session(editor: &EditorTestUtils) -> &SnapSession { &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session } diff --git a/editor/src/messages/tool/tool_messages/shape_tool.rs b/editor/src/messages/tool/tool_messages/shape_tool.rs index 482a1331aa..3bef7104bc 100644 --- a/editor/src/messages/tool/tool_messages/shape_tool.rs +++ b/editor/src/messages/tool/tool_messages/shape_tool.rs @@ -22,7 +22,7 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::{ShapeTo use crate::messages::tool::common_functionality::shapes::spiral_shape::Spiral; use crate::messages::tool::common_functionality::shapes::star_shape::Star; use crate::messages::tool::common_functionality::shapes::{Ellipse, Line, Rectangle}; -use crate::messages::tool::common_functionality::snap_session::{Drawn, Moving, PointOptions, SnapView, snapping_hints}; +use crate::messages::tool::common_functionality::snap_session::{Drawn, Moving, PointOptions, SnapSession, SnapView, snapping_hints}; use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget}; use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, EdgeBool}; use crate::messages::tool::common_functionality::utility_functions::{closest_point, resize_bounds, rotate_bounds, skew_bounds, transforming_transform_cage}; @@ -583,6 +583,7 @@ impl<'a> MessageHandler> for Shap | ShapeToolFsmState::RotatingBounds | ShapeToolFsmState::SkewingBounds { .. } | ShapeToolFsmState::DraggingLineEndpoints + | ShapeToolFsmState::ModifyingGizmo ); if in_gesture && self.fsm_state != previous_state { if let Some(bounds) = &mut self.tool_data.bounding_box_manager { @@ -592,7 +593,8 @@ impl<'a> MessageHandler> for Shap responses.add(OverlaysMessage::Draw); } - if is_set_shape { + // A shape's own key pressed mid-drag leaves the drag as it is + if is_set_shape && matches!(self.fsm_state, ShapeToolFsmState::Ready(_)) { handle_shape_mode_change(&mut self.options, self.tool_data.current_shape, shape_before, context.global_tool_data, context.document); self.send_layout(responses, LayoutTarget::ToolOptions); } @@ -917,6 +919,9 @@ impl Fsm for ShapeToolFsmState { Arrow::overlays(document, tool_data, input.mouse.position, &mut overlay_context); if all_selected_layers_line_or_arrow { + // Lines, arrows, and an empty selection have no cage, so an earlier selection's cage mustn't stay behind to catch presses + tool_data.bounding_box_manager = None; + let cursor = if hovering_over_endpoint { MouseCursorIcon::Default } else { MouseCursorIcon::Crosshair }; tool_data.cursor = cursor; responses.add(FrontendMessage::UpdateMouseCursor { cursor }); @@ -1050,8 +1055,10 @@ impl Fsm for ShapeToolFsmState { tool_data.line_data.drag_current = mouse_pos; - if tool_data.gizmo_manager.handle_click() && !input.keyboard.key(Key::Accel) { + // The modifiers are checked first in these, as the gizmo and line end checks mark what they find as being dragged + if !input.keyboard.key(Key::Accel) && tool_data.gizmo_manager.handle_click() { tool_data.data.drag_start = document.metadata().document_to_viewport.inverse().transform_point2(mouse_pos); + snap_session.begin_gesture(SnapView::new(document, *document_id, input), Moving::default()); responses.add(DocumentMessage::StartTransaction); let cursor = tool_data.gizmo_manager.mouse_cursor_icon().unwrap_or(MouseCursorIcon::Crosshair); @@ -1068,14 +1075,14 @@ impl Fsm for ShapeToolFsmState { } // If clicked on endpoints of a selected line or arrow, drag its endpoints - if let Some((layer, _, _)) = closest_point( - document, - mouse_pos, - SNAP_POINT_TOLERANCE, - document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface), - |_| false, - ) && clicked_on_shape_endpoints(layer, document, input, tool_data) - && !input.keyboard.key(Key::Control) + if !input.keyboard.key(Key::Control) + && let Some((layer, _, _)) = closest_point( + document, + mouse_pos, + SNAP_POINT_TOLERANCE, + document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface), + |_| false, + ) && clicked_on_shape_endpoints(layer, document, input, tool_data) { responses.add(DocumentMessage::StartTransaction); @@ -1088,6 +1095,11 @@ impl Fsm for ShapeToolFsmState { return ShapeToolFsmState::DraggingLineEndpoints; } + // The overlay pass that clears it may not have run since the selection changed + if all_selected_layers_line_or_arrow { + tool_data.bounding_box_manager = None; + } + let (resize, rotate, skew) = transforming_transform_cage(document, &mut tool_data.bounding_box_manager, input, responses, &mut tool_data.layers_dragging, None); if !input.keyboard.key(Key::Control) { @@ -1253,7 +1265,8 @@ impl Fsm for ShapeToolFsmState { self } (ShapeToolFsmState::ModifyingGizmo, ShapeToolMessage::PointerMove { .. }) => { - tool_data.gizmo_manager.handle_update(tool_data.data.viewport_drag_start(document), document, input, responses); + let drag_start = tool_data.data.viewport_drag_start(document); + tool_data.gizmo_manager.handle_update(drag_start, SnapView::new(document, *document_id, input), snap_session, responses); responses.add(OverlaysMessage::Draw); @@ -1400,22 +1413,7 @@ impl Fsm for ShapeToolFsmState { | ShapeToolFsmState::ModifyingGizmo, ShapeToolMessage::Abort, ) => { - responses.add(DocumentMessage::AbortTransaction); - tool_data.data.cleanup(); - snap_session.end_gesture(); - responses.add(OverlaysMessage::Draw); - tool_data.line_data.dragging_endpoint = None; - tool_data.line_data.editing_layer = None; - - tool_data.gizmo_manager.handle_cleanup(); - - if let Some(bounds) = &mut tool_data.bounding_box_manager { - bounds.original_transforms.clear(); - } - - tool_data.cursor = MouseCursorIcon::Crosshair; - responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair }); - + cancel_drag(tool_data, snap_session, responses); ShapeToolFsmState::Ready(tool_data.current_shape) } (_, ShapeToolMessage::WorkingColorChanged) => { @@ -1424,22 +1422,10 @@ impl Fsm for ShapeToolFsmState { }); self } - (_, ShapeToolMessage::SetShape { shape }) => { - responses.add(DocumentMessage::AbortTransaction); - tool_data.data.cleanup(); - snap_session.end_gesture(); - responses.add(OverlaysMessage::Draw); - tool_data.current_shape = shape; - // Update hints for the new shape (without updating options.shape_type) - update_dynamic_hints(&ShapeToolFsmState::Ready(shape), responses, tool_data); - ShapeToolFsmState::Ready(shape) - } - (_, ShapeToolMessage::SyncShapeWithOptions) => { - // Sync current_shape with the dropdown selection when returning from alias tools - tool_data.current_shape = tool_options.shape_type; - update_dynamic_hints(&ShapeToolFsmState::Ready(tool_options.shape_type), responses, tool_data); - ShapeToolFsmState::Ready(tool_options.shape_type) - } + // The Line, Rectangle, and Ellipse tools set their own shape (without updating options.shape_type) + (_, ShapeToolMessage::SetShape { shape }) => switch_shape(self, shape, tool_data, snap_session, responses), + // Returning to the Shape tool from one of those draws the dropdown's shape again + (_, ShapeToolMessage::SyncShapeWithOptions) => switch_shape(self, tool_options.shape_type, tool_data, snap_session, responses), (_, ShapeToolMessage::HideShapeTypeWidget { hide }) => { tool_data.hide_shape_option_widget = hide; responses.add(ToolMessage::RefreshToolOptions); @@ -1458,6 +1444,39 @@ impl Fsm for ShapeToolFsmState { } } +/// Ends a drag without keeping anything it changed. +fn cancel_drag(tool_data: &mut ShapeToolData, snap_session: &mut SnapSession, responses: &mut VecDeque) { + responses.add(DocumentMessage::AbortTransaction); + tool_data.data.cleanup(); + snap_session.end_gesture(); + responses.add(OverlaysMessage::Draw); + tool_data.line_data.dragging_endpoint = None; + tool_data.line_data.editing_layer = None; + + tool_data.gizmo_manager.handle_cleanup(); + + if let Some(bounds) = &mut tool_data.bounding_box_manager { + bounds.original_transforms.clear(); + } + + tool_data.cursor = MouseCursorIcon::Crosshair; + responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair }); +} + +/// Switches to drawing another shape. Mid-drag, this cancels the drag as changing tools does, unless the shape is the one already being drawn, whose key is ignored as other tools ignore their own. +fn switch_shape(state: ShapeToolFsmState, shape: ShapeType, tool_data: &mut ShapeToolData, snap_session: &mut SnapSession, responses: &mut VecDeque) -> ShapeToolFsmState { + if !matches!(state, ShapeToolFsmState::Ready(_)) { + if shape == tool_data.current_shape { + return state; + } + cancel_drag(tool_data, snap_session, responses); + } + + tool_data.current_shape = shape; + update_dynamic_hints(&ShapeToolFsmState::Ready(shape), responses, tool_data); + ShapeToolFsmState::Ready(shape) +} + fn update_dynamic_hints(state: &ShapeToolFsmState, responses: &mut VecDeque, tool_data: &ShapeToolData) { let hint_data = match state { ShapeToolFsmState::Ready(_) => { @@ -1574,7 +1593,10 @@ fn update_dynamic_hints(state: &ShapeToolFsmState, responses: &mut VecDeque HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), + ShapeToolFsmState::ModifyingGizmo => HintData(vec![ + HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), + snapping_hints(), + ]), }; hint_data.send_layout(responses); } @@ -1582,11 +1604,25 @@ fn update_dynamic_hints(state: &ShapeToolFsmState, responses: &mut VecDeque Vec { @@ -1696,6 +1732,21 @@ mod test_shape_tool { } } + #[tokio::test] + async fn an_odd_polygon_or_star_dragged_upward_is_drawn_flipped_to_point_down() { + for (shape, point_count) in [(ShapeType::Polygon, 5), (ShapeType::Star, 10)] { + for (from, to, flipped) in [(DVec2::new(300., 300.), DVec2::new(380., 380.), false), (DVec2::new(300., 380.), DVec2::new(380., 300.), true)] { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_checking_shape_points(&mut editor, shape, from, to, ModifierKeys::empty(), point_count).await; + + // The tip of an upright shape is in the middle of the top of its box, and a flipped one's is in the middle of the bottom + let tip = DVec2::new(340., if flipped { 380. } else { 300. }); + assert_has_anchor_at(&drawn_anchors(&editor, layer), tip); + } + } + } + /// Where the second vertex of a pentagon dragged out from `start` lands for a pointer at `pointer`, in the viewport. fn second_vertex(start: DVec2, pointer: DVec2) -> DVec2 { let vertex = regular_polygon_points(5)[1]; @@ -1814,4 +1865,459 @@ mod test_shape_tool { assert_bounds(&editor, layer, [DVec2::new(300., 300.), DVec2::new(480., 380.)]); } + + /// Draws a shape between two viewport positions, and returns its layer. + async fn draw_shape(editor: &mut EditorTestUtils, shape: ShapeType, from: DVec2, to: DVec2) -> LayerNodeIdentifier { + press_drawing(editor, shape, from, ModifierKeys::empty()).await; + editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await; + editor.get_selected_layer().await.expect("the shape drawn should be selected") + } + + /// Takes hold of a gizmo's handle at a viewport position, once drawing the overlays has found it under the pointer, and drags it along a path without letting go. + async fn drag_gizmo_handle(editor: &mut EditorTestUtils, handle: DVec2, path: &[DVec2]) { + editor.move_mouse(handle.x, handle.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + editor.left_mousedown(handle.x, handle.y, ModifierKeys::empty()).await; + for position in path { + editor.move_mouse(position.x, position.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + } + } + + fn engaged_kinds(editor: &EditorTestUtils) -> Vec { + let session = &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session; + let shown = session.shown().expect("the gizmo should have tried to snap"); + shown.outcome.engaged_candidates().map(|candidate| candidate.key.kind).collect() + } + + #[tokio::test] + async fn an_arc_with_its_end_dragged_to_a_few_degrees_from_a_right_angle_sweeps_a_right_angle() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + + // The end of the arc, which sweeps 270° from its start, is carried around the center by way of 180° to 93° + let document = editor.active_document(); + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + let center = document.metadata().transform_to_viewport(layer).transform_point2(DVec2::ZERO); + let at_sweep = |degrees: f64| center + DVec2::from_angle(degrees.to_radians()) * end.distance(center); + drag_gizmo_handle(&mut editor, end, &[at_sweep(180.), at_sweep(93.)]).await; + + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), editor.active_document()).expect("the arc should have its parameters"); + assert!((sweep - 90.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::RightAngle]); + + editor.left_mouseup(at_sweep(93.).x, at_sweep(93.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_star_with_its_inner_radius_dragged_near_the_one_giving_right_angled_tips_lands_on_it() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Star, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + + let document = editor.active_document(); + let (sides, outer_radius, inner_radius) = extract_star_parameters(Some(layer), document).expect("the star should have its parameters"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let handle = star_vertex_position(to_viewport, 1, sides, outer_radius, inner_radius); + + // A tip is right-angled where the inner vertices on either side lie at right angles from it, which takes this inner radius + let half_point = PI / sides as f64; + let right_angled = outer_radius / (half_point.sin() + half_point.cos()); + + // The inner vertex is drawn out along its spoke to a radius one and a half short of that + let spoke = star_vertex_position(DAffine2::IDENTITY, 1, sides, 1., 1.); + let pointer = to_viewport.transform_point2(spoke * (right_angled - 1.5)); + drag_gizmo_handle(&mut editor, handle, &[pointer]).await; + + let (_, _, dragged) = extract_star_parameters(Some(layer), editor.active_document()).expect("the star should have its parameters"); + assert!((dragged - right_angled).abs() < 1e-9, "the inner radius is {dragged} rather than {right_angled}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::RightAngle]); + + editor.left_mouseup(pointer.x, pointer.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_circle_with_its_radius_dragged_near_that_of_another_circle_comes_to_the_same_radius() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let other = draw_shape(&mut editor, ShapeType::Circle, DVec2::new(100., 100.), DVec2::new(180., 180.)).await; + let layer = draw_shape(&mut editor, ShapeType::Circle, DVec2::new(300., 300.), DVec2::new(360., 360.)).await; + + // The rim of the smaller circle is taken hold of on its right and drawn out to one and a half short of the other's radius + let document = editor.active_document(); + let radius_of = |layer: LayerNodeIdentifier, document: &DocumentMessageHandler| extract_circle_radius(layer, document).expect("the circle should have a radius"); + let (radius, other_radius) = (radius_of(layer, document), radius_of(other, document)); + let to_viewport = document.metadata().transform_to_viewport(layer); + let (rim, pointer) = (to_viewport.transform_point2(DVec2::X * radius), to_viewport.transform_point2(DVec2::X * (other_radius - 1.5))); + drag_gizmo_handle(&mut editor, rim, &[pointer]).await; + + let dragged = radius_of(layer, editor.active_document()); + assert!((dragged - other_radius).abs() < 1e-9, "the radius is {dragged} rather than {other_radius}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::EqualRadius]); + + editor.left_mouseup(pointer.x, pointer.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_spiral_with_its_end_turned_to_just_short_of_a_whole_number_of_turns_lands_on_it() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + + let document = editor.active_document(); + let turns_of = |document: &DocumentMessageHandler| extract_spiral_parameters(layer, document).expect("the spiral should have its parameters").4; + let turns = turns_of(document); + let whole = turns.floor() + 1.; + let to_viewport = document.metadata().transform_to_viewport(layer); + let end = calculate_spiral_endpoints(layer, document, to_viewport, TAU).expect("the spiral should have an end"); + let center = to_viewport.transform_point2(DVec2::ZERO); + + // The end is carried around the center in four steps to a hundredth of a turn short of the next whole number of turns + let step = (whole - 0.01 - turns) * 360. / 4.; + let path: Vec = (1..=4).map(|i| center + DVec2::from_angle(-(step * i as f64).to_radians()).rotate(end - center)).collect(); + drag_gizmo_handle(&mut editor, end, &path).await; + + let dragged = turns_of(editor.active_document()); + assert!((dragged - whole).abs() < 1e-9, "the spiral has {dragged} turns rather than {whole}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::WholeValue]); + + let last = path.last().copied().unwrap_or(end); + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } + + /// Takes hold of a spiral's start and draws the pointer out to 100 pixels from the center, then around it by a number of turns, which the start takes away. + /// Returns where the pointer ends up, still pressed. + async fn turn_spiral_start(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, turns_taken_away: f64) -> DVec2 { + let document = editor.active_document(); + let to_viewport = document.metadata().transform_to_viewport(layer); + let start = calculate_spiral_endpoints(layer, document, to_viewport, 0.).expect("the spiral should have a start"); + let center = to_viewport.transform_point2(DVec2::ZERO); + let out = center + (start - center).normalize_or(DVec2::X) * 100.; + + let step = turns_taken_away * 360. / 4.; + let mut path = vec![out]; + path.extend((1..=4).map(|i| center + DVec2::from_angle(-(step * i as f64).to_radians()).rotate(out - center))); + drag_gizmo_handle(editor, start, &path).await; + + path.last().copied().unwrap_or(out) + } + + #[tokio::test] + async fn a_spiral_with_its_start_turned_well_short_of_a_half_turn_keeps_the_turns_it_was_turned_to() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + let turns_of = |document: &DocumentMessageHandler| extract_spiral_parameters(layer, document).expect("the spiral should have its parameters").4; + let turns = turns_of(editor.active_document()); + + // A fifth of a turn from the nearest half turn is far beyond reach for a pointer circling 100 pixels out + let free = turns.floor() - 0.3; + let last = turn_spiral_start(&mut editor, layer, turns - free).await; + + let dragged = turns_of(editor.active_document()); + assert!((dragged - free).abs() < 1e-6, "the spiral has {dragged} turns rather than {free}"); + assert!(engaged_kinds(&editor).is_empty()); + + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_spiral_with_its_start_turned_to_just_past_a_whole_number_of_turns_lands_on_it_and_marks_the_start_where_it_went() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + let turns_of = |document: &DocumentMessageHandler| extract_spiral_parameters(layer, document).expect("the spiral should have its parameters").4; + let turns = turns_of(editor.active_document()); + + let whole = turns.ceil() - 1.; + let last = turn_spiral_start(&mut editor, layer, turns - (whole + 0.01)).await; + + let document = editor.active_document(); + let dragged = turns_of(document); + assert!((dragged - whole).abs() < 1e-9, "the spiral has {dragged} turns rather than {whole}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::WholeValue]); + + let to_viewport = document.metadata().transform_to_viewport(layer); + let start = calculate_spiral_endpoints(layer, document, to_viewport, 0.).expect("the spiral should have a start"); + let session = &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session; + let marked = document.metadata().document_to_viewport.transform_point2(session.shown_position().expect("the snap should be shown")); + assert!(marked.distance(start) < 1e-6, "the snap is marked at {marked} rather than at the start, {start}"); + + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn on_a_flipped_canvas_an_arc_end_dragged_near_a_half_turn_sweeps_one_and_is_marked_where_it_went() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + editor.handle_message(NavigationMessage::CanvasFlip).await; + + // The end is carried around the arc in its own space, which the flip mirrors on screen + let document = editor.active_document(); + let (radius, start_angle, _, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let at_sweep = |degrees: f64| to_viewport.transform_point2(DVec2::from_angle((start_angle + degrees).to_radians()) * radius); + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + drag_gizmo_handle(&mut editor, end, &[at_sweep(225.), at_sweep(183.)]).await; + + // A half turn is no right angle + let document = editor.active_document(); + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + assert!((sweep - 180.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::AngleStep]); + + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + let session = &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session; + let marked = document.metadata().document_to_viewport.transform_point2(session.shown_position().expect("the snap should be shown")); + assert!(marked.distance(end) < 1e-6, "the snap is marked at {marked} rather than at the end, {end}"); + + editor.left_mouseup(at_sweep(183.).x, at_sweep(183.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_circle_with_its_radius_dragged_near_the_rim_of_a_stretched_arc_meets_that_rim_in_the_direction_it_is_pulled() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + // Drawn twice as wide as it is tall, the arc reaches twice as far from its center across as it does up and down + let arc = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(100., 100.), DVec2::new(300., 200.)).await; + + // With the arc left selected, the Shape tool would go on drawing arcs + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + let layer = draw_shape(&mut editor, ShapeType::Circle, DVec2::new(400., 400.), DVec2::new(460., 460.)).await; + + let document = editor.active_document(); + let (arc_radius, ..) = extract_arc_parameters(Some(arc), document).expect("the arc should have its parameters"); + let arc_to_document = document.metadata().transform_to_document(arc); + let arc_rim = arc_to_document.transform_vector2(DVec2::X * arc_radius).length(); + + // The circle's rim is taken hold of on its right and drawn out to one and a half short of how far the arc reaches across + let radius = extract_circle_radius(layer, document).expect("the circle should have a radius"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let (rim, pointer) = (to_viewport.transform_point2(DVec2::X * radius), to_viewport.transform_point2(DVec2::X * (arc_rim - 1.5))); + drag_gizmo_handle(&mut editor, rim, &[pointer]).await; + + let dragged = extract_circle_radius(layer, editor.active_document()).expect("the circle should have a radius"); + assert!((dragged - arc_rim).abs() < 1e-9, "the radius is {dragged} rather than {arc_rim}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::EqualRadius]); + + editor.left_mouseup(pointer.x, pointer.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_stretched_arc_with_its_end_dragged_a_few_degrees_from_a_half_turn_where_it_crosses_the_screen_slowest_sweeps_one() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(500., 400.)).await; + + let document = editor.active_document(); + let (radius, start_angle, _, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let at_sweep = |degrees: f64| to_viewport.transform_point2(DVec2::from_angle((start_angle + degrees).to_radians()) * radius); + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + + // Seven degrees short of a half turn, the end lies a hundred pixels from the center but only six pixels from where a half turn takes it + drag_gizmo_handle(&mut editor, end, &[at_sweep(200.), at_sweep(173.)]).await; + + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), editor.active_document()).expect("the arc should have its parameters"); + assert!((sweep - 180.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::AngleStep]); + + editor.left_mouseup(at_sweep(173.).x, at_sweep(173.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn an_arc_with_its_start_dragged_to_just_inside_a_larger_snap_angle_grows_to_it_and_keeps_its_far_end() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + + // The arc sweeps two degrees short of a three-quarter turn + let node_id = get_arc_id(layer, &editor.active_document().network_interface).expect("the arc should have its node"); + editor + .handle_message(NodeGraphMessage::SetInput { + input_connector: InputConnector::node(node_id, arc::SweepAngleInput), + input: NodeInput::value(TaggedValue::Number(268.), false), + }) + .await; + editor.handle_message(NodeGraphMessage::RunDocumentGraph).await; + + let document = editor.active_document(); + let (radius, start_angle, _, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + let (start, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let at_angle = |degrees: f64| to_viewport.transform_point2(DVec2::from_angle((start_angle + degrees).to_radians()) * radius); + + // The start is carried along the arc and back to two degrees on, which shrinks the sweep to four short of the three-quarter turn + drag_gizmo_handle(&mut editor, start, &[at_angle(30.), at_angle(2.)]).await; + + let document = editor.active_document(); + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + assert!((sweep - 270.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::RightAngle]); + + let (_, dragged_end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + assert!(dragged_end.distance(end) < 1e-6, "the far end moved from {end} to {dragged_end}"); + + editor.left_mouseup(at_angle(2.).x, at_angle(2.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_logarithmic_spiral_with_a_turn_taken_off_its_start_winds_as_tightly_as_before() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Shape).await; + editor + .handle_message(ShapeToolMessage::UpdateOptions { + options: ShapeOptionsUpdate::SpiralType(SpiralType::Logarithmic), + }) + .await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + + let turns_and_growth_factor_of = |document: &DocumentMessageHandler| { + let (spiral_type, _, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document).expect("the spiral should have its parameters"); + (turns, calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type)) + }; + let (turns, growth_factor) = turns_and_growth_factor_of(editor.active_document()); + + // The start lands on a whole turn fewer, and the outer radius shrinks so the spiral keeps winding as it did + let whole = turns.ceil() - 1.; + let last = turn_spiral_start(&mut editor, layer, turns - (whole + 0.01)).await; + + let (dragged, dragged_growth_factor) = turns_and_growth_factor_of(editor.active_document()); + assert!((dragged - whole).abs() < 1e-9, "the spiral has {dragged} turns rather than {whole}"); + assert!( + (dragged_growth_factor - growth_factor).abs() < 1e-9, + "the growth factor is {dragged_growth_factor} rather than {growth_factor}" + ); + + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_drag_from_where_a_cage_was_draws_once_the_selection_has_no_cage() { + for leave_cage in [DocumentMessage::Undo, DocumentMessage::DeselectAllLayers] { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(300., 300., 400., 380.).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.handle_message(leave_cage).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.draw_rect(400., 380., 480., 440.).await; + let layer = editor.get_selected_layer().await.expect("the drag should draw a rectangle"); + assert_bounds(&editor, layer, [DVec2::new(400., 380.), DVec2::new(480., 440.)]); + } + } + + #[tokio::test] + async fn a_drag_from_where_a_cage_was_draws_before_the_overlays_next_update() { + for leave_cage in [DocumentMessage::Undo, DocumentMessage::DeselectAllLayers, DocumentMessage::DeleteSelectedLayers] { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(300., 300., 400., 380.).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + // The press comes within the same frame, or with overlays hidden, so no overlay pass clears the cage first + editor.handle_message(leave_cage).await; + + editor.draw_rect(400., 380., 480., 440.).await; + let layer = editor.get_selected_layer().await.expect("the drag should draw a rectangle"); + assert_bounds(&editor, layer, [DVec2::new(400., 380.), DVec2::new(480., 440.)]); + } + } + + #[tokio::test] + async fn a_drag_from_where_a_cage_was_draws_once_only_a_line_is_selected() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(300., 300., 400., 380.).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.drag_tool(ToolType::Line, 100., 100., 200., 100., ModifierKeys::empty()).await; + let line = editor.get_selected_layer().await.expect("the line drawn should be selected"); + let line_bounds = editor.active_document().metadata().bounding_box_viewport(line); + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.draw_rect(400., 380., 480., 440.).await; + let layer = editor.get_selected_layer().await.expect("the drag should draw a rectangle"); + assert_ne!(layer, line, "the drag should draw a new layer rather than change the line"); + assert_bounds(&editor, layer, [DVec2::new(400., 380.), DVec2::new(480., 440.)]); + assert_eq!(editor.active_document().metadata().bounding_box_viewport(line), line_bounds, "the line should be left as it was"); + } + + /// Presses at one viewport position, drags halfway to another, sends a tool key's message, then finishes the drag. + async fn drag_pressing_mid_way(editor: &mut EditorTestUtils, from: DVec2, to: DVec2, key_message: ToolMessage) { + let halfway = from.midpoint(to); + editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await; + editor.move_mouse(halfway.x, halfway.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.handle_message(key_message).await; + editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await; + } + + fn layer_count(editor: &EditorTestUtils) -> usize { + editor.active_document().metadata().all_layers().count() + } + + #[tokio::test] + async fn the_shape_tools_own_key_mid_drag_is_ignored_and_leaves_nothing_to_undo_later() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Shape).await; + drag_pressing_mid_way(&mut editor, DVec2::new(300., 300.), DVec2::new(400., 380.), ToolMessage::ActivateToolShape).await; + + // The pentagon reaches nearly the right of the drag's box, as its side vertices sit at 95% of the box's half width + let layer = editor.get_selected_layer().await.expect("the pentagon drawn should be selected"); + let [_, max] = editor.active_document().metadata().bounding_box_viewport(layer).expect("the pentagon should have a bounding box"); + assert!(max.x > 395., "the pentagon reaches only {max} rather than the release"); + + // Switching to another of the Shape tool's modes finds no drawing left to cancel + let count = layer_count(&editor); + editor.select_tool(ToolType::Ellipse).await; + assert_eq!(layer_count(&editor), count, "the pentagon should survive switching to the Ellipse tool"); + } + + #[tokio::test] + async fn switching_to_the_shape_tool_mid_drag_cancels_the_rectangle() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Rectangle).await; + let count = layer_count(&editor); + drag_pressing_mid_way(&mut editor, DVec2::new(300., 300.), DVec2::new(400., 380.), ToolMessage::ActivateToolShape).await; + + assert_eq!(layer_count(&editor), count, "switching tools mid-drag should cancel the rectangle"); + } + + #[tokio::test] + async fn a_line_ctrl_dragged_from_a_selected_lines_start_runs_from_the_press_to_the_release() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Line, 100., 100., 300., 100., ModifierKeys::empty()).await; + + // Ctrl is let go once the press starts a new line, so its angle isn't locked + editor.move_mouse(100., 100., ModifierKeys::CONTROL, MouseKeys::empty()).await; + editor.left_mousedown(100., 100., ModifierKeys::CONTROL).await; + editor.move_mouse(100., 300., ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(100., 300., ModifierKeys::empty()).await; + + let layer = editor.get_selected_layer().await.expect("the new line should be selected"); + let document = editor.active_document(); + let Some(&TaggedValue::DVec2(line_to)) = graph_modification_utils::NodeGraphLayer::new(layer, &document.network_interface) + .find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::line::IDENTIFIER)) + .and_then(|inputs| inputs[1].as_value()) + else { + panic!("the new layer should be a line") + }; + let to_viewport = document.metadata().transform_to_viewport(layer); + let (start, end) = (to_viewport.transform_point2(DVec2::ZERO), to_viewport.transform_point2(line_to)); + assert!( + start.distance(DVec2::new(100., 100.)) < 1e-6 && end.distance(DVec2::new(100., 300.)) < 1e-6, + "the line runs from {start} to {end}" + ); + } } diff --git a/editor/src/messages/tool/tool_messages/spline_tool.rs b/editor/src/messages/tool/tool_messages/spline_tool.rs index 7ec6c579be..4b25b369c7 100644 --- a/editor/src/messages/tool/tool_messages/spline_tool.rs +++ b/editor/src/messages/tool/tool_messages/spline_tool.rs @@ -565,7 +565,15 @@ impl Fsm for SplineToolFsmState { SplineToolFsmState::MergingEndpoints } (SplineToolFsmState::Drawing, SplineToolMessage::Abort) => { - responses.add(DocumentMessage::AbortTransaction); + // Switching tools keeps the spline drawn so far, like the Pen tool, but leaves its ends unjoined as the tool won't be active to finish them + if tool_data.points.len() <= 1 { + responses.add(DocumentMessage::AbortTransaction); + } else { + delete_preview(tool_data, responses); + responses.add(DocumentMessage::EndTransaction); + } + + tool_data.cleanup(); SplineToolFsmState::Ready } (SplineToolFsmState::Ready, SplineToolMessage::Confirm | SplineToolMessage::Abort) => { @@ -690,15 +698,13 @@ mod test_spline_tool { use crate::test_utils::test_prelude::*; use glam::DAffine2; use graphene_std::vector::PointId; - use graphene_std::vector::Vector; + use graphene_std::vector::VectorGeometry; - fn assert_point_positions(vector: &Vector, layer_to_viewport: DAffine2, expected_points: &[DVec2], epsilon: f64) { + fn assert_point_positions(vector: &VectorGeometry, layer_to_viewport: DAffine2, expected_points: &[DVec2], epsilon: f64) { let points_in_viewport: Vec = vector - .point_domain - .ids() - .iter() - .filter_map(|&point_id| { - let position = vector.point_domain.position_from_id(point_id)?; + .anchor_points() + .filter_map(|point_id| { + let position = vector.position_from_id(point_id)?; Some(layer_to_viewport.transform_point2(position)) }) .collect(); @@ -726,7 +732,7 @@ mod test_spline_tool { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("The spline should have a path"); - assert_eq!(vector.point_domain.ids().len(), expected.len(), "Unexpected point count"); + assert_eq!(vector.anchor_points().count(), expected.len(), "Unexpected point count"); assert_point_positions(&vector, document.metadata().transform_to_viewport(layer), expected, 1e-6); } @@ -763,8 +769,8 @@ mod test_spline_tool { let first_vector = document.network_interface.compute_modified_vector(spline_layer).expect("Vector not found for the spline layer"); // Verify initial spline has correct number of points and segments - let initial_point_count = first_vector.point_domain.ids().len(); - let initial_segment_count = first_vector.segment_domain.ids().len(); + let initial_point_count = first_vector.anchor_points().count(); + let initial_segment_count = first_vector.segment_ids().len(); assert_eq!(initial_point_count, 3, "Expected 3 points in initial spline, found {initial_point_count}"); assert_eq!(initial_segment_count, 2, "Expected 2 segments in initial spline, found {initial_segment_count}"); @@ -772,7 +778,7 @@ mod test_spline_tool { let endpoints: Vec<(PointId, DVec2)> = first_vector .anchor_endpoints() - .filter_map(|point_id| first_vector.point_domain.position_from_id(point_id).map(|pos| (point_id, layer_to_viewport.transform_point2(pos)))) + .filter_map(|point_id| first_vector.position_from_id(point_id).map(|pos| (point_id, layer_to_viewport.transform_point2(pos)))) .collect(); assert_eq!(endpoints.len(), 2, "Expected 2 endpoints in the initial spline"); @@ -797,8 +803,8 @@ mod test_spline_tool { .expect("Vector not found for the extended spline layer"); // Verify extended spline has correct number of points and segments - let extended_point_count = extended_vector.point_domain.ids().len(); - let extended_segment_count = extended_vector.segment_domain.ids().len(); + let extended_point_count = extended_vector.anchor_points().count(); + let extended_segment_count = extended_vector.segment_ids().len(); assert_eq!(extended_point_count, 5, "Expected 5 points in extended spline, found {extended_point_count}"); assert_eq!(extended_segment_count, 4, "Expected 4 segments in extended spline, found {extended_segment_count}"); @@ -989,8 +995,8 @@ mod test_spline_tool { let vector = document.network_interface.compute_modified_vector(spline_layer).expect("Vector not found for the spline layer"); // Verify we have the correct number of points and segments - let point_count = vector.point_domain.ids().len(); - let segment_count = vector.segment_domain.ids().len(); + let point_count = vector.anchor_points().count(); + let segment_count = vector.segment_ids().len(); assert_eq!(point_count, 3, "Expected 3 points in the spline, found {point_count}"); assert_eq!(segment_count, 2, "Expected 2 segments in the spline, found {segment_count}"); @@ -1132,8 +1138,9 @@ mod test_spline_tool { editor.draw_spline(&ARCH).await; let first = spline_layers(&editor)[0]; + // Aborted before placing a point of its own, the extension is dropped editor.click_tool(ToolType::Spline, MouseKeys::LEFT, ARCH[2], ModifierKeys::empty()).await; - editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(500., 200.), ModifierKeys::empty()).await; + editor.move_mouse(500., 200., ModifierKeys::empty(), MouseKeys::empty()).await; editor.handle_message(SplineToolMessage::Abort).await; assert_spline_points(&editor, first, &ARCH); @@ -1144,4 +1151,41 @@ mod test_spline_tool { let second = spline_layers(&editor).into_iter().find(|&layer| layer != first).expect("A second spline should have been drawn"); assert_spline_points(&editor, second, &[center, points[1], points[2]]); } + + #[tokio::test] + async fn switching_tools_mid_spline_keeps_the_spline() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Spline).await; + for point in ARCH { + editor.click_tool(ToolType::Spline, MouseKeys::LEFT, point, ModifierKeys::empty()).await; + } + editor.move_mouse(500., 200., ModifierKeys::empty(), MouseKeys::empty()).await; + + // The Select tool's own abort, which runs as it becomes active, would otherwise cancel the spline's open edit + editor.select_tool(ToolType::Select).await; + + let splines = spline_layers(&editor); + assert_eq!(splines.len(), 1); + assert_spline_points(&editor, splines[0], &ARCH); + + // The finished spline is one step of history + editor.press(Key::KeyZ, ModifierKeys::CONTROL).await; + assert!(spline_layers(&editor).is_empty(), "Undo should remove the whole spline"); + } + + #[tokio::test] + async fn an_extension_is_kept_when_switching_tools() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_spline(&ARCH).await; + let first = spline_layers(&editor)[0]; + + editor.click_tool(ToolType::Spline, MouseKeys::LEFT, ARCH[2], ModifierKeys::empty()).await; + let extension = DVec2::new(500., 200.); + editor.click_tool(ToolType::Spline, MouseKeys::LEFT, extension, ModifierKeys::empty()).await; + editor.select_tool(ToolType::Rectangle).await; + + assert_spline_points(&editor, first, &[ARCH[0], ARCH[1], ARCH[2], extension]); + } } diff --git a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs index de3ca5f008..b29847431f 100644 --- a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs +++ b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs @@ -20,7 +20,7 @@ use glam::{DAffine2, DVec2}; use graphene_std::renderer::Quad; use graphene_std::vector::click_target::ClickTargetType; use graphene_std::vector::misc::ManipulatorPointId; -use graphene_std::vector::{Vector, VectorModificationType}; +use graphene_std::vector::{VectorGeometry, VectorModificationType}; use std::f64::consts::{PI, TAU}; const TRANSFORM_GRS_OVERLAY_PROVIDER: OverlayProvider = |context| TransformLayerMessage::Overlays { context }.into(); @@ -184,7 +184,7 @@ impl MessageHandler> for let affected_point_refs = affected_points.iter().collect(); - let get_location = |point: &&ManipulatorPointId| point.get_position(&vector).map(|position| viewspace.transform_point2(position)); + let get_location = |point: &&ManipulatorPointId| vector.position_of(**point).map(|position| viewspace.transform_point2(position)); if let (Some((new_pivot, grab_target)), bounds) = calculate_pivot( document, &affected_point_refs, @@ -400,6 +400,7 @@ impl MessageHandler> for self.grs_pen_handle = true; self.mouse_position = input.mouse.position; self.start_mouse = input.mouse.position; + self.initial_transform = document_to_viewport; let top_left = DVec2::new(last_point.x, handle.y); let bottom_right = DVec2::new(handle.x, last_point.y); @@ -479,9 +480,9 @@ impl MessageHandler> for && let [point] = selected_points.as_slice() { if matches!(point, ManipulatorPointId::Anchor(_)) { - if let Some([handle1, handle2]) = point.get_handle_pair(&vector) { - let handle1_length = handle1.length(&vector); - let handle2_length = handle2.length(&vector); + if let Some([handle1, handle2]) = vector.handle_pair_of(**point) { + let handle1_length = vector.handle_length(handle1); + let handle2_length = vector.handle_length(handle2); if (handle1_length == 0. && handle2_length == 0. && !using_select_tool) || (handle1_length == f64::MAX && handle2_length == f64::MAX && !using_select_tool) { // G should work for this point but not R and S @@ -492,7 +493,7 @@ impl MessageHandler> for } } } else { - let handle_length = point.as_handle().map(|handle| handle.length(&vector)); + let handle_length = point.as_handle().map(|handle| vector.handle_length(handle)); if handle_length == Some(0.) { selected.original_transforms.clear(); @@ -799,10 +800,10 @@ impl Snapping { moving.edited.push(layer); for point in points { - if let Some(anchor) = point.get_anchor(&vector) { + if let Some(anchor) = vector.anchor_of(point) { moving.anchors.push((layer, anchor)); } - if let Some(position) = point.get_position(&vector) { + if let Some(position) = vector.position_of(point) { starts.push(to_document.transform_point2(position)); } } @@ -951,7 +952,7 @@ fn snap_again(operation: &mut TransformOperation, snapping: Option<&Snapping>, s fn calculate_pivot( document: &DocumentMessageHandler, selected_points: &Vec<&ManipulatorPointId>, - vector: &Vector, + vector: &VectorGeometry, viewspace: DAffine2, get_location: impl Fn(&ManipulatorPointId) -> Option, gizmo: &mut PivotGizmo, @@ -994,8 +995,8 @@ fn calculate_pivot( ManipulatorPointId::PrimaryHandle(_) | ManipulatorPointId::EndHandle(_) => { // Get the anchor position and transform it to the pivot let (Some(pivot_position), Some(position)) = ( - point.get_anchor_position(vector).map(|anchor_position| viewspace.transform_point2(anchor_position)), - point.get_position(vector), + vector.anchor_position_of(**point).map(|anchor_position| viewspace.transform_point2(anchor_position)), + vector.position_of(**point), ) else { return (None, None); }; @@ -1014,18 +1015,18 @@ fn update_colinear_handles(selected_layers: &[LayerNodeIdentifier], document: &D for &layer in selected_layers { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; - for [handle1, handle2] in &vector.colinear_manipulators { + for [handle1, handle2] in vector.colinear_pairs() { let manipulator1 = handle1.to_manipulator_point(); let manipulator2 = handle2.to_manipulator_point(); - let Some(anchor_pos) = manipulator1.get_anchor_position(&vector) else { continue }; - let Some(handle1_pos) = manipulator1.get_position(&vector) else { continue }; - let Some(handle2_pos) = manipulator2.get_position(&vector) else { continue }; + let Some(anchor_pos) = vector.anchor_position_of(manipulator1) else { continue }; + let Some(handle1_pos) = vector.position_of(manipulator1) else { continue }; + let Some(handle2_pos) = vector.position_of(manipulator2) else { continue }; // Check if handles are not colinear (not approximately equal to +/- PI) if !is_almost_colinear(anchor_pos, handle1_pos, handle2_pos) { let modification_type = VectorModificationType::SetG1Continuous { - handles: [*handle1, *handle2], + handles: [handle1, handle2], enabled: false, }; @@ -1839,7 +1840,7 @@ mod test_transform_layer { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("the path should have a vector"); let to_viewport = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); - let anchors: Vec = vector.point_domain.positions().iter().map(|&position| to_viewport.transform_point2(position)).collect(); + let anchors: Vec = vector.anchor_positions().iter().map(|&position| to_viewport.transform_point2(position)).collect(); assert_eq!(anchors.len(), 2, "unexpected anchors {anchors:?}"); assert!( anchors[0].distance(first) < 1e-6 && anchors[1].distance(DVec2::new(400., 300.)) < 1e-6, diff --git a/editor/src/messages/tool/utility_types.rs b/editor/src/messages/tool/utility_types.rs index a23a0610f3..811cdc1155 100644 --- a/editor/src/messages/tool/utility_types.rs +++ b/editor/src/messages/tool/utility_types.rs @@ -556,7 +556,7 @@ impl HintData { } for shortcut in &hint.key_groups { - widgets.push(ShortcutLabel::new(Some(ActionShortcut::Shortcut(shortcut.clone()))).widget_instance()); + widgets.push(ShortcutLabel::new(Some(ActionShortcut::Keys(shortcut.clone()))).widget_instance()); } if let Some(mouse_movement) = hint.mouse { let mouse_movement = LabeledShortcut(vec![LabeledKeyOrMouseMotion::MouseMotion(mouse_movement)]); @@ -598,10 +598,10 @@ pub struct HintInfo { /// A `KeysGroup` specifies all the keys pressed simultaneously to perform an action (like "Ctrl C" to copy). /// Usually at most one is given, but less commonly, multiple can be used to describe additional hotkeys not used simultaneously (like the four different arrow keys to nudge a layer). #[serde(rename = "keyGroups")] - pub key_groups: Vec, + pub key_groups: Vec, /// `None` means that the regular `key_groups` should be used for all platforms, `Some` is an override for a Mac-only input hint. #[serde(rename = "keyGroupsMac")] - pub key_groups_mac: Option>, + pub key_groups_mac: Option>, /// An optional `MouseMotion` that can indicate the mouse action, like which mouse button is used and whether a drag occurs. /// No such icon is shown if `None` is given, and it can be combined with `key_groups` if desired. pub mouse: Option, @@ -621,7 +621,7 @@ impl HintInfo { pub fn keys(keys: impl IntoIterator, label: impl Into>) -> Self { let keys = keys.into_iter().collect(); Self { - key_groups: vec![KeysGroup(keys).into()], + key_groups: vec![KeysGroup(keys)], key_groups_mac: None, mouse: None, label: label.into(), @@ -635,7 +635,7 @@ impl HintInfo { /// - The four arrow keys can be used to nudge a layer in different directions /// - The G, R, and S keys can be used to enter GRS transformation mode pub fn multi_keys(multi_keys: impl IntoIterator>, label: impl Into>) -> Self { - let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect()).into()).collect(); + let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect())).collect(); Self { key_groups, key_groups_mac: None, @@ -671,7 +671,7 @@ impl HintInfo { pub fn keys_and_mouse(keys: impl IntoIterator, mouse_motion: MouseMotion, label: impl Into>) -> Self { let keys = keys.into_iter().collect(); Self { - key_groups: vec![KeysGroup(keys).into()], + key_groups: vec![KeysGroup(keys)], key_groups_mac: None, mouse: Some(mouse_motion), label: label.into(), @@ -681,7 +681,7 @@ impl HintInfo { } pub fn multi_keys_and_mouse(multi_keys: impl IntoIterator>, mouse_motion: MouseMotion, label: impl Into>) -> Self { - let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect()).into()).collect(); + let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect())).collect(); Self { key_groups, key_groups_mac: None, @@ -709,7 +709,7 @@ impl HintInfo { pub fn add_mac_keys(mut self, keys: impl IntoIterator) -> Self { let mac_keys = keys.into_iter().collect(); - self.key_groups_mac = Some(vec![KeysGroup(mac_keys).into()]); + self.key_groups_mac = Some(vec![KeysGroup(mac_keys)]); self } } diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 50ccce48d4..ee83c8bdc9 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -1,4 +1,5 @@ -use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage}; +use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus}; +use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::prelude::*; use glam::{DAffine2, DVec2, UVec2}; @@ -6,7 +7,7 @@ use graph_craft::application_io::EditorPreferences; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; use graph_craft::proto::GraphErrors; -use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderConfig, TimingInformation}; +use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::bounds::RenderBoundingBox; use graphene_std::color::SRGBA8; use graphene_std::list::List; @@ -14,19 +15,19 @@ use graphene_std::memo::IORecord; use graphene_std::raster::{CPU, Raster}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::transform::Footprint; -use graphene_std::vector::{Vector, graphic_types}; +use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes}; use graphene_std::{ATTR_TRANSFORM, Context, Graphic}; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use std::any::Any; use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender}; -mod runtime_io; -pub use runtime_io::NodeRuntimeIO; - +#[cfg(test)] +mod recompile_tests; mod runtime; pub use runtime::*; -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct ExecutionRequest { execution_id: u64, render_config: RenderConfig, @@ -34,13 +35,26 @@ pub struct ExecutionRequest { pub struct ExecutionResponse { execution_id: u64, - result: Result, + result: ExecutionResult, responses: VecDeque, - vector_modify: HashMap, + /// The layers whose thumbnails the runtime let go of, which it renders anew if they're monitored again. + dropped_thumbnails: Vec, + vector_modify: HashMap, /// The resulting value from the temporary inspected during execution inspect_result: Option, } +#[derive(Debug)] +pub enum ExecutionResult { + Pending, + Value(TaggedValue), + Fallback(TaggedValue, EvaluationError), + Error(EvaluationError), + Panic(Box), +} + +pub type EvaluationError = Box<[(Arc, Box<[NodeId]>)]>; + #[derive(serde::Serialize, serde::Deserialize)] pub struct CompilationResponse { result: Result, @@ -51,14 +65,15 @@ pub enum NodeGraphUpdate { ExecutionResponse(Box), CompilationResponse(CompilationResponse), EyedropperPreview(Raster), - NodeGraphUpdateMessage(NodeGraphUpdateMessage), } -#[derive(Debug, Default)] +#[derive(Debug)] pub struct NodeGraphExecutor { - runtime_io: NodeRuntimeIO, + sender: Sender, + receiver: Receiver, current_execution_id: u64, futures: VecDeque<(u64, ExecutionContext)>, + pending: Option<(u64, ExecutionContext)>, node_graph_hash: u64, /// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected. /// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in, @@ -100,23 +115,23 @@ struct GradientMigration { } impl NodeGraphExecutor { - /// A local runtime is useful on threads since having global state causes flakes - #[cfg(test)] - pub(crate) fn new_with_local_runtime() -> (NodeRuntime, Self) { + pub(crate) fn new(editor_wake: Wake) -> (Self, NodeRuntime) { let (request_sender, request_receiver) = std::sync::mpsc::channel(); let (response_sender, response_receiver) = std::sync::mpsc::channel(); - let node_runtime = NodeRuntime::new(request_receiver, response_sender); + let node_runtime = NodeRuntime::new(request_receiver, response_sender, editor_wake); let node_executor = Self { futures: Default::default(), - runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver), + sender: request_sender, + receiver: response_receiver, node_graph_hash: 0, current_execution_id: 0, previous_node_to_inspect: Vec::new(), gradient_migration: None, gradient_migration_attempted: HashSet::new(), + pending: None, }; - (node_runtime, node_executor) + (node_executor, node_runtime) } /// Allows the test runner to see if any more executions have been queued. @@ -130,13 +145,13 @@ impl NodeGraphExecutor { let execution_id = self.current_execution_id; self.current_execution_id += 1; let request = ExecutionRequest { execution_id, render_config }; - self.runtime_io.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request"); + self.sender.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request"); execution_id } pub fn update_editor_preferences(&self, editor_preferences: EditorPreferences) { - self.runtime_io + self.sender .send(GraphRuntimeRequest::EditorPreferencesUpdate(editor_preferences)) .expect("Failed to send editor preferences"); } @@ -151,7 +166,7 @@ impl NodeGraphExecutor { let resources = document.resources.registry.clone(); - self.runtime_io + self.sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, @@ -172,7 +187,7 @@ impl NodeGraphExecutor { let resources = document.resources.registry.clone(); - self.runtime_io + self.sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, node_to_inspect })) .map_err(|e| e.to_string())?; } @@ -338,7 +353,7 @@ impl NodeGraphExecutor { export_config.size = resolution; // Execute the node graph - self.runtime_io + self.sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, @@ -359,24 +374,28 @@ impl NodeGraphExecutor { Ok(()) } - pub fn poll_node_graph_evaluation(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque) -> Result<(), String> { + /// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile. + pub fn poll_node_graph_evaluation(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque) -> Vec { // TODO: Eventually remove this document upgrade code // A gradient migration belongs to one document; if the active document changed away from it, cancel so its stale in-flight response is ignored and revisiting restarts a fresh pass if self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id != document_id) { self.cancel_gradient_migration(); } - let results = self.runtime_io.receive().collect::>(); - for response in results { + let mut all_dropped_thumbnails = Vec::new(); + let mut results = self.receiver.try_iter().collect::>().into_iter(); + while let Some(response) = results.next() { match response { NodeGraphUpdate::ExecutionResponse(execution_response) => { let ExecutionResponse { execution_id, result, responses: existing_responses, + dropped_thumbnails, vector_modify, inspect_result, } = *execution_response; + all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied()); while let Some(&(queued_execution_id, _)) = self.futures.front() { if queued_execution_id < execution_id { @@ -386,42 +405,93 @@ impl NodeGraphExecutor { } } - let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else { - panic!("InvalidGenerationId") + let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) { + let (_, execution_context) = self.futures.pop_front().expect("the front was just checked"); + if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() { + self.pending = Some((execution_id, execution_context.clone())); + } + execution_context + } else if let Some((rendered_execution_id, execution_context)) = &self.pending + && *rendered_execution_id == execution_id + { + execution_context.clone() + } else { + continue; }; - assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id"); + + // Only from the active document's own renders, and before their thumbnails arrive, since the runtime dropped these before rendering them + if execution_context.document_id == document_id { + document.layers_in_view.forget_thumbnails(&dropped_thumbnails, responses); + } // TODO: Eventually remove this document upgrade code // Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork. // Apply only to the active document's in-progress migration, dropping responses left over from a document switch. if let Some(bake_target) = execution_context.measure_fill { if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) { - self.handle_gradient_measurement(document, document_id, bake_target, result.ok().and(inspect_result), responses); + let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(inspect_result).flatten(); + self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses); } continue; } responses.add(OverlaysMessage::Draw); + // A pending graph keeps the last frame, and the errors shown with it + if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) { + let errors = match &result { + ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => errors + .iter() + .map(|(error, node_path)| NodeEvaluationError { + node_path: node_path.to_vec(), + message: error.to_string(), + }) + .collect(), + ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Panic(_) => Vec::new(), + }; + responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors }); + } + let node_graph_output = match result { + ExecutionResult::Pending => Ok(None), + ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Ok(Some(value)), + ExecutionResult::Error(errors) => Err(errors.iter().map(|(error, _)| error.to_string()).collect::>().join("\n")), + ExecutionResult::Panic(payload) => { + let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::().map(String::as_str)); + Err(format!("Panicked: {}", message.unwrap_or("no message"))) + } + }; + let node_graph_output = match node_graph_output { Ok(output) => output, Err(e) => { // Clear the click targets while the graph is in an un-renderable state document.network_interface.update_click_targets(HashMap::new()); document.network_interface.update_outlines(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new()); - return Err(format!("Node graph evaluation failed:\n{e}")); + log::error!("Node graph evaluation failed:\n{e}"); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + break; } }; - responses.extend(existing_responses.into_iter().map(Into::into)); + // Thumbnails reach the frontend only for the layers it shows in view + for response in existing_responses { + match response { + FrontendMessage::UpdateNodeThumbnail { id, value } => { + // A render finishing after a switch to another document has thumbnails of the previous one's layers + if execution_context.document_id == document_id { + document.layers_in_view.receive_thumbnail(id, value, responses); + } + } + response => responses.add(response), + } + } document.network_interface.update_vector_modify(vector_modify); - if let Some(export_config) = execution_context.export_config { - // Special handling for exporting the artwork - self.process_export(node_graph_output, export_config, document, responses)?; - } else { - self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, responses)?; + match (node_graph_output, execution_context.export_config) { + (Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses), + (Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, responses), + (None, _) => {} } responses.add(DeferMessage::TriggerGraphRun { execution_id, @@ -462,7 +532,8 @@ impl NodeGraphExecutor { node_graph_errors, }); - return Err(format!("Node graph evaluation failed:\n{e}")); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + break; } Ok(result) => result, }; @@ -476,11 +547,29 @@ impl NodeGraphExecutor { let (data, width, height) = raster.to_flat_u8(); responses.add(EyedropperToolMessage::PreviewImage { data, width, height }); } - NodeGraphUpdate::NodeGraphUpdateMessage(_) => {} } } - Ok(()) + // An error leaves the later responses unapplied, but the runtime still dropped their thumbnails + for response in results { + if let NodeGraphUpdate::ExecutionResponse(execution_response) = response { + if self.document_of_execution(execution_response.execution_id) == Some(document_id) { + document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses); + } + all_dropped_thumbnails.extend(execution_response.dropped_thumbnails); + } + } + + all_dropped_thumbnails + } + + /// The document an execution was submitted for, while it's still queued or pending. + fn document_of_execution(&self, execution_id: u64) -> Option { + self.futures + .iter() + .chain(&self.pending) + .find(|(queued_execution_id, _)| *queued_execution_id == execution_id) + .map(|(_, execution_context)| execution_context.document_id) } // TODO: Eventually remove this document upgrade code @@ -548,7 +637,7 @@ impl NodeGraphExecutor { let resources = document.resources.registry.clone(); if self - .runtime_io + .sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, @@ -667,9 +756,11 @@ impl NodeGraphExecutor { self.node_graph_hash = 0; } - fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque) -> Result<(), String> { + fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque) { let TaggedValue::RenderOutput(render_output) = node_graph_output else { - return Err(format!("Invalid node graph output type: {node_graph_output:#?}")); + log::error!("Invalid node graph output type: {node_graph_output:#?}"); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + return; }; match render_output.data { @@ -697,7 +788,11 @@ impl NodeGraphExecutor { responses.add(FrontendMessage::UpdateDocumentArtwork { svg }); } RenderOutputType::Texture { .. } => {} - _ => return Err(format!("Invalid node graph output type: {:#?}", render_output.data)), + _ => { + log::error!("Invalid node graph output type: {:#?}", render_output.data); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + return; + } } let RenderMetadata { @@ -730,10 +825,10 @@ impl NodeGraphExecutor { responses.add(DocumentMessage::RenderRulers); responses.add(OverlaysMessage::Draw); - Ok(()) + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Rendering }); } - fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque) -> Result<(), String> { + fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque) { let ExportConfig { file_type, name, @@ -773,15 +868,19 @@ impl NodeGraphExecutor { data: RenderOutputType::Buffer { data, width, height }, .. }) if file_type != FileType::Svg => { - let content = file_type.encode(width, height, data)?.into(); + let content = match file_type.encode(width, height, data) { + Ok(content) => content.into(), + Err(e) => { + log::error!("Failed to encode image: {e}"); + return; + } + }; responses.add(FrontendMessage::TriggerSaveFile { name, folder, filters, content }); } _ => { - return Err(format!("Incorrect render type for exporting to an SVG ({file_type:?}, {node_graph_output})")); + log::error!("Incorrect render type for exporting to an SVG ({file_type:?}, {node_graph_output})"); } - }; - - Ok(()) + } } } @@ -838,7 +937,8 @@ fn measure_fill_geometry(data: &Arc) -> Option<(DAffine2, if let Some(list) = introspected_output::>(data) { let vector = list.element(0)?; let item_transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0); - let bounds = vector.nonzero_bounding_box(); + let paths = paths_from_list_row_attributes(&list, 0).unwrap_or_else(|| no_paths()); + let bounds = vector.nonzero_bounding_box(paths); let bounding_box_affine = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]); return Some((bounding_box_affine, item_transform)); } diff --git a/editor/src/node_graph_executor/recompile_tests.rs b/editor/src/node_graph_executor/recompile_tests.rs new file mode 100644 index 0000000000..f4c9b25c9b --- /dev/null +++ b/editor/src/node_graph_executor/recompile_tests.rs @@ -0,0 +1,56 @@ +use crate::messages::portfolio::document::utility_types::network_interface::FlowType; +use crate::test_utils::test_prelude::*; +use glam::UVec2; +use graph_craft::document::NodeId; +use graphene_std::application_io::TimingInformation; +use std::collections::HashSet; + +async fn compile_and_run(editor: &mut EditorTestUtils) { + let portfolio = editor.portfolio_message_handler_mut(); + let document_id = portfolio.active_document_id.unwrap(); + let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); + let document = documents.get_mut(&document_id).unwrap(); + executor + .submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO) + .unwrap(); + editor.runtime.run().await; + editor.dispatch(Message::Wake); +} + +/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops +/// for one more update, so a first update clears those of the test harness's instrumented graph. +async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet { + compile_and_run(editor).await; + compile_and_run(editor).await; + let source_map = editor.runtime.executor.tree().source_map(); + source_map.iter().filter(|(path, _)| keep(path)).map(|(_, (id, _))| *id).collect() +} + +#[tokio::test] +async fn recompiling_keeps_the_ids_of_an_image_chain() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.create_raster_image(Image::new(16, 16, Color::BLUE), Some((0., 0.))).await; + let layer = editor.get_selected_layer().await.expect("the dropped image should be selected").to_node(); + + // The nodes feeding the image layer's content, which the resource node feeds + let network_interface = &editor.active_document().network_interface; + let chain: Vec<_> = network_interface + .upstream_flow_back_from_nodes(vec![layer], &[], FlowType::HorizontalFlow) + .filter(|&node| node != layer) + .collect(); + let in_chain = |path: &[NodeId]| path.iter().any(|node| chain.contains(node)); + + let all = compiled_ids(&mut editor, |_| true).await; + assert_eq!(compiled_ids(&mut editor, |_| true).await, all, "compiling the same document again changed its proto node IDs"); + let image_chain = compiled_ids(&mut editor, in_chain).await; + assert!(!image_chain.is_empty(), "the image layer has no compiled content"); + + // The new layer above takes the image layer as its input, a change downstream of the image + editor.draw_rect(0., 0., 10., 10.).await; + assert_eq!( + compiled_ids(&mut editor, in_chain).await, + image_chain, + "an edit downstream of the image changed the image chain's proto node IDs" + ); +} diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index 8ce1ccea57..c49d7c46e5 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -1,5 +1,6 @@ use super::*; use crate::messages::frontend::utility_types::{ExportBounds, FileType}; +use crate::task::{Spawn, Spawner, Task}; use glam::{DAffine2, DVec2, UVec2}; use graph_craft::application_io::resource::ResourceRegistry; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; @@ -8,23 +9,24 @@ use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::graphene_compiler::Compiler; use graph_craft::proto::GraphErrors; -use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture}; +use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig, Texture}; use graphene_std::bounds::RenderBoundingBox; use graphene_std::list::{Item, List}; use graphene_std::memo::IORecord; -use graphene_std::ops::Convert; +use graphene_std::ops::ConvertAsync; #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle}; use graphene_std::raster_types::Raster; use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment}; +use graphene_std::runtime::AsyncRuntime; use graphene_std::transform::RenderQuality; -use graphene_std::vector::Vector; use graphene_std::vector::style::RenderMode; -use graphene_std::{Artboard, Context, Graphic}; -use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta}; +use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes}; +use graphene_std::{Artboard, Context, Graphic, NodeError, Poll}; +use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::util::wrap_network_in_scope; -use spin::Mutex; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender}; /// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`. @@ -36,10 +38,15 @@ pub struct NodeRuntime { #[cfg(not(test))] executor: DynamicExecutor, receiver: Receiver, - sender: InternalNodeGraphUpdateSender, + sender: Sender, + editor_wake: Wake, + dirty: Arc, + pending: Option, + pending_export: Option, editor_preferences: EditorPreferences, old_graph: Option, update_thumbnails: bool, + async_runtime: Option, editor_api: Arc, resources: ResourceRegistry, @@ -54,7 +61,7 @@ pub struct NodeRuntime { // TODO: Remove, it doesn't need to be persisted anymore /// The current renders of the thumbnails for layer nodes. thumbnail_renders: HashMap>, - vector_modify: HashMap, + vector_modify: HashMap, /// Cached surface for Wasm viewport rendering (reused across frames) #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] @@ -93,46 +100,24 @@ pub struct ExportConfig { pub artboard_count: usize, } -#[derive(Clone)] -struct InternalNodeGraphUpdateSender(Sender); - -impl InternalNodeGraphUpdateSender { - fn send_compilation_response(&self, response: CompilationResponse) { - self.0.send(NodeGraphUpdate::CompilationResponse(response)).expect("Failed to send response") - } - - fn send_execution_response(&self, response: ExecutionResponse) { - self.0.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response") - } - - fn send_eyedropper_preview(&self, raster: Raster) { - self.0.send(NodeGraphUpdate::EyedropperPreview(raster)).expect("Failed to send response") - } -} - -impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender { - fn send(&self, message: NodeGraphUpdateMessage) { - self.0.send(NodeGraphUpdate::NodeGraphUpdateMessage(message)).expect("Failed to send response") - } -} - -// TODO: Replace with `core::cell::LazyCell` () or similar -pub static NODE_RUNTIME: once_cell::sync::Lazy>> = once_cell::sync::Lazy::new(|| Mutex::new(None)); - impl NodeRuntime { - pub fn new(receiver: Receiver, sender: Sender) -> Self { + pub fn new(receiver: Receiver, sender: Sender, editor_wake: Wake) -> Self { Self { executor: DynamicExecutor::default(), receiver, - sender: InternalNodeGraphUpdateSender(sender.clone()), + sender, + editor_wake, + dirty: Default::default(), + pending: None, + pending_export: None, editor_preferences: EditorPreferences::default(), old_graph: None, resources: ResourceRegistry::default(), update_thumbnails: true, + async_runtime: None, editor_api: PlatformEditorApi { editor_preferences: Box::new(EditorPreferences::default()), - node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)), #[cfg(not(test))] application_io: None, @@ -158,17 +143,23 @@ impl NodeRuntime { } pub async fn run(&mut self) -> Option { + let texture = self.handle_requests().await; + (self.editor_wake)(); + texture + } + + async fn handle_requests(&mut self) -> Option { let mut preferences = None; let mut graph = None; let mut eyedropper = None; let mut execution = None; - for request in self.receiver.try_iter() { + + for request in self.pending_export.is_none().then_some(&self.receiver).into_iter().flat_map(Receiver::try_iter) { match request { GraphRuntimeRequest::GraphUpdate(_) => graph = Some(request), GraphRuntimeRequest::ExecutionRequest(ref execution_request) => { if execution_request.render_config.for_eyedropper { eyedropper = Some(request); - continue; } @@ -185,6 +176,10 @@ impl NodeRuntime { } } + if self.dirty.swap(false, Ordering::Acquire) && execution.is_none() { + execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest); + } + // Eydropper should use the same time and pointer to not invalidate the cache if let Some(GraphRuntimeRequest::ExecutionRequest(eyedropper)) = &mut eyedropper && let Some(GraphRuntimeRequest::ExecutionRequest(execution)) = &execution @@ -201,13 +196,12 @@ impl NodeRuntime { self.editor_preferences = preferences.clone(); self.editor_api = PlatformEditorApi { application_io: self.editor_api.application_io.clone(), - node_graph_message_sender: Box::new(self.sender.clone()), editor_preferences: Box::new(preferences), } .into(); if let Some(graph) = self.old_graph.clone() { // We ignore this result as compilation errors should have been reported in an earlier iteration - let _ = self.update_network(graph).await; + let _ = self.update_network(graph); } } GraphRuntimeRequest::GraphUpdate(GraphUpdate { @@ -222,14 +216,23 @@ impl NodeRuntime { self.resources = resources; self.node_graph_errors.clear(); - let result = self.update_network(network).await; + let result = self.update_network(network); let node_graph_errors = self.node_graph_errors.clone(); self.update_thumbnails = true; - self.sender.send_compilation_response(CompilationResponse { result, node_graph_errors }); + self.sender + .send(NodeGraphUpdate::CompilationResponse(CompilationResponse { result, node_graph_errors })) + .expect("Failed to send response"); } - GraphRuntimeRequest::ExecutionRequest(ExecutionRequest { execution_id, mut render_config, .. }) => { + GraphRuntimeRequest::ExecutionRequest(request @ ExecutionRequest { execution_id, mut render_config, .. }) => { + if !render_config.for_export && !render_config.for_eyedropper { + self.pending = Some(request); + } + if render_config.for_export { + self.pending_export = None; + } + // We may want to render via the SVG pipeline even though raster was requested, if SVG Preview render mode is active or WebGPU/Vello is unavailable if render_config.export_format == ExportFormat::Raster && (render_config.render_mode == RenderMode::SvgPreview || self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_none()) @@ -237,107 +240,117 @@ impl NodeRuntime { render_config.export_format = ExportFormat::Svg; } - let result = self.execute_network(render_config).await; + let mut result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.execute_network(render_config))) { + Ok(Ok(Poll::Pending)) => ExecutionResult::Pending, + Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending, + Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value), + Ok(Ok(Poll::Fallback(boxed))) => { + let (value, error) = *boxed; + ExecutionResult::Fallback(value, self.resolve_errors(&error)) + } + Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)), + Ok(Err(error)) => ExecutionResult::Error(Box::new([(Arc::clone(NodeError::new(error).error()), Box::default())])), + Err(payload) => { + let response = ExecutionResponse { + execution_id, + result: ExecutionResult::Panic(payload), + responses: VecDeque::new(), + dropped_thumbnails: Vec::new(), + vector_modify: HashMap::new(), + inspect_result: None, + }; + self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); + return None; + } + }; + + match (render_config.for_export, &result) { + (true, ExecutionResult::Pending) => { + self.pending_export = Some(request); + return None; + } + (true, _) => self.dirty.store(true, Ordering::Release), + _ => {} + } + let mut responses = VecDeque::new(); // TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes - if !render_config.for_eyedropper { - self.process_monitor_nodes(&mut responses, self.update_thumbnails); - } + let dropped_thumbnails = if !render_config.for_eyedropper { + self.process_monitor_nodes(&mut responses, self.update_thumbnails) + } else { + Vec::new() + }; self.update_thumbnails = false; // Resolve the result from the inspection by accessing the monitor node let inspect_result = self.inspect_state.as_ref().and_then(|state| state.access(&self.executor)); - let (result, texture) = match result { - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata, - })) if render_config.for_export => { - let executor = self - .editor_api - .application_io - .as_ref() - .unwrap() - .gpu_executor() - .expect("GPU executor should be available when we receive a texture"); - - let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; - - let (data, width, height) = raster_cpu.to_flat_u8(); - - ( - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Buffer { data, width, height }, - metadata, - })), - None, - ) - } - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata: _, - })) if render_config.for_eyedropper => { - let executor = self - .editor_api - .application_io - .as_ref() - .unwrap() - .gpu_executor() - .expect("GPU executor should be available when we receive a texture"); - - let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; - - self.sender.send_eyedropper_preview(raster_cpu); - continue; - } - // Eyedropper render that didn't produce a texture (e.g., SVG fallback when GPU is unavailable); discard it - _ if render_config.for_eyedropper => { - continue; - } - #[cfg(all(target_family = "wasm", feature = "gpu"))] - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata, - })) if !render_config.for_export => { - self.current_viewport_texture = Some(texture.clone()); - - let app_io = self.editor_api.application_io.as_ref().unwrap(); - let executor = app_io.gpu_executor().expect("GPU executor should be available when we receive a texture"); - - self.wasm_canvas_cache.present(&texture, executor); - - let logical_resolution = render_config.viewport.resolution.as_dvec2() / render_config.scale; - ( - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::CanvasFrame { - canvas_id: self.wasm_canvas_cache.id(), - resolution: logical_resolution, - }, - metadata, - })), - None, - ) - } - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata, - })) => ( - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture.clone()), - metadata, - })), - Some(texture), - ), - r => (r, None), + let output = match &mut result { + ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Some(value), + ExecutionResult::Pending | ExecutionResult::Error(_) | ExecutionResult::Panic(_) => None, }; + let texture = if let Some(TaggedValue::RenderOutput(RenderOutput { data, .. })) = output + && let RenderOutputType::Texture(texture) = data + { + let texture = texture.clone(); + if render_config.for_export || render_config.for_eyedropper { + let executor = self + .editor_api + .application_io + .as_ref() + .unwrap() + .gpu_executor() + .expect("GPU executor should be available when we receive a texture"); - self.sender.send_execution_response(ExecutionResponse { + let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await; + + if render_config.for_eyedropper { + self.sender.send(NodeGraphUpdate::EyedropperPreview(raster_cpu)).expect("Failed to send response"); + continue; + } + + let (buffer, width, height) = raster_cpu.to_flat_u8(); + *data = RenderOutputType::Buffer { data: buffer, width, height }; + None + } else { + #[cfg(all(target_family = "wasm", feature = "gpu"))] + { + self.current_viewport_texture = Some(texture.clone()); + + let app_io = self.editor_api.application_io.as_ref().unwrap(); + let executor = app_io.gpu_executor().expect("GPU executor should be available when we receive a texture"); + + self.wasm_canvas_cache.present(&texture, executor); + + let logical_resolution = render_config.viewport.resolution.as_dvec2() / render_config.scale; + *data = RenderOutputType::CanvasFrame { + canvas_id: self.wasm_canvas_cache.id(), + resolution: logical_resolution, + }; + None + } + #[cfg(not(all(target_family = "wasm", feature = "gpu")))] + { + Some(texture) + } + } + } else { + None + }; + // Eyedropper render that didn't produce a texture (e.g., SVG fallback when GPU is unavailable); discard it + if render_config.for_eyedropper { + continue; + } + + let response = ExecutionResponse { execution_id, result, responses, + dropped_thumbnails, vector_modify: self.vector_modify.clone(), inspect_result, - }); + }; + self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); return texture; } } @@ -345,8 +358,8 @@ impl NodeRuntime { None } - async fn update_network(&mut self, graph: NodeNetwork) -> Result { - let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone()); + fn update_network(&mut self, graph: NodeNetwork) -> Result { + let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle()); if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) { return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string())); @@ -368,27 +381,57 @@ impl NodeRuntime { .collect::>(); assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); - self.executor.update(proto_network).await.map_err(|(types, e)| { + let result = self.executor.update(proto_network).map_err(|(types, e)| { self.node_graph_errors.clone_from(&e); (types, format!("{e:?}")) - }) + }); + self.async_runtime().retain_sources(self.executor.sources()); + result } - async fn execute_network(&mut self, render_config: RenderConfig) -> Result { + fn execute_network(&mut self, render_config: RenderConfig) -> Result, String> { use graph_craft::graphene_compiler::Executor; match self.executor.input_type() { - Some(t) if t == concrete!(Context) => (&self.executor).execute(render_config.into_context()).await.map_err(|e| e.to_string()), - Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()), + Some(t) if t == concrete!(Context) => (&self.executor) + .execute(render_config.into_context_with_generations(self.async_runtime().snapshot())) + .map_err(|e| e.to_string()), + Some(t) if t == concrete!(()) => (&self.executor).execute(()).map_err(|e| e.to_string()), Some(t) => Err(format!("Invalid input type {t:?}")), _ => Err(format!("No input type:\n{:?}", self.node_graph_errors)), } } - /// Updates state data - pub fn process_monitor_nodes(&mut self, responses: &mut VecDeque, update_thumbnails: bool) { + fn resolve_errors(&self, error: &NodeError) -> EvaluationError { + let source_map = self.executor.tree().source_map(); + let mut errors = Vec::new(); + let mut pending = vec![(Some(self.executor.output()), error)]; + while let Some((node, error)) = pending.pop() { + let origin = node.and_then(|node| self.executor.find_origin(node, error)); + let start = errors.len(); + if let Some(origin) = origin { + errors.extend(source_map.iter().filter(|(_, (node, _))| *node == origin).map(|(path, _)| (Arc::clone(error.error()), path.clone()))); + errors[start..].sort_unstable_by(|(_, a), (_, b)| a.cmp(b)); + } + if errors.len() == start { + errors.push((Arc::clone(error.error()), Box::default())); + } + pending.extend(error.upstream().iter().rev().map(|upstream| (origin, upstream))); + } + errors.into_boxed_slice() + } + + /// Updates state data, giving back the layers whose thumbnails were dropped because they're no longer monitored. + fn process_monitor_nodes(&mut self, responses: &mut VecDeque, update_thumbnails: bool) -> Vec { // TODO: Consider optimizing this since it's currently O(m*n^2), with a sort it could be made O(m * n*log(n)) - self.thumbnail_renders.retain(|id, _| self.monitor_nodes.iter().any(|monitor_node_path| monitor_node_path.contains(id))); + let mut dropped_thumbnails = Vec::new(); + self.thumbnail_renders.retain(|id, _| { + let monitored = self.monitor_nodes.iter().any(|monitor_node_path| monitor_node_path.contains(id)); + if !monitored { + dropped_thumbnails.push(*id); + } + monitored + }); for monitor_node_path in &self.monitor_nodes { // Skip the inspect monitor node @@ -432,7 +475,11 @@ impl NodeRuntime { // Vector list: vector modifications else if let Some(io) = introspected_data.downcast_ref::>>() { // Insert the vector modify - self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default()); + let geometry = VectorGeometry::new( + io.output.element(0).cloned().unwrap_or_default(), + paths_from_list_row_attributes(&io.output, 0).cloned().unwrap_or_default(), + ); + self.vector_modify.insert(parent_network_node_id, geometry); } // String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`) else if let Some(io) = introspected_data.downcast_ref::>>() { @@ -455,7 +502,7 @@ impl NodeRuntime { Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses) } } else if let Some(io) = introspected_data.downcast_ref::>>() { - self.vector_modify.insert(parent_network_node_id, io.output.element().clone()); + self.vector_modify.insert(parent_network_node_id, VectorGeometry::from_item(&io.output)); } else if let Some(io) = introspected_data.downcast_ref::>>() { if update_thumbnails { let singleton = List::new_from_item(io.output.clone()); @@ -468,6 +515,8 @@ impl NodeRuntime { log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}"); } } + + dropped_thumbnails } /// If this is `Graphic` data, regenerate click targets and thumbnails for the layers in the graph, modifying the state and updating the UI. @@ -566,42 +615,45 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] { [center - half, center + half] } -pub async fn introspect_node(path: &[NodeId]) -> Result, IntrospectError> { - let runtime = NODE_RUNTIME.lock(); - if let Some(ref mut runtime) = runtime.as_ref() { - return runtime.executor.introspect(path); - } - Err(IntrospectError::RuntimeNotReady) -} - -pub async fn run_node_graph() -> (bool, Option) { - let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) }; - if let Some(ref mut runtime) = runtime.as_mut() { - return (true, runtime.run().await); - } - (false, None) -} - -pub fn replace_node_runtime(runtime: NodeRuntime) -> Option { - let mut node_runtime = NODE_RUNTIME.lock(); - node_runtime.replace(runtime) -} -pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) { - let mut node_runtime = NODE_RUNTIME.lock(); - if let Some(node_runtime) = &mut *node_runtime { - node_runtime.replace_application_io(application_io); - } -} - impl NodeRuntime { pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) { self.editor_api = PlatformEditorApi { application_io: Some(application_io.into()), - node_graph_message_sender: Box::new(self.sender.clone()), editor_preferences: Box::new(self.editor_preferences.clone()), } .into(); } + + pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) { + let spawn = NodeTaskExecutor { + spawner, + dirty: self.dirty.clone(), + wake, + }; + self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn))); + } + + fn async_runtime(&self) -> &AsyncRuntime { + self.async_runtime.as_ref().expect("the task executor is installed before the first graph update") + } +} + +struct NodeTaskExecutor { + spawner: Spawner, + dirty: Arc, + wake: Wake, +} + +impl Spawn for NodeTaskExecutor { + fn spawn(&self, task: Task) { + let dirty = self.dirty.clone(); + let wake = self.wake.clone(); + self.spawner.spawn(Box::pin(async move { + task.await; + dirty.store(true, Ordering::Release); + wake(); + })); + } } /// Which node is inspected and which monitor node is used (if any) for the current execution diff --git a/editor/src/node_graph_executor/runtime_io.rs b/editor/src/node_graph_executor/runtime_io.rs deleted file mode 100644 index 5b2235ae5e..0000000000 --- a/editor/src/node_graph_executor/runtime_io.rs +++ /dev/null @@ -1,44 +0,0 @@ -use super::*; -use std::sync::mpsc::{Receiver, Sender}; - -/// Handles communication with the NodeRuntime -#[derive(Debug)] -pub struct NodeRuntimeIO { - // Send to - sender: Sender, - receiver: Receiver, -} - -impl Default for NodeRuntimeIO { - fn default() -> Self { - Self::new() - } -} - -impl NodeRuntimeIO { - /// Creates a new NodeRuntimeIO instance - pub fn new() -> Self { - let (response_sender, response_receiver) = std::sync::mpsc::channel(); - let (request_sender, request_receiver) = std::sync::mpsc::channel(); - replace_node_runtime(NodeRuntime::new(request_receiver, response_sender)); - - Self { - sender: request_sender, - receiver: response_receiver, - } - } - #[cfg(test)] - pub fn with_channels(sender: Sender, receiver: Receiver) -> Self { - Self { sender, receiver } - } - - /// Sends a message to the NodeRuntime - pub fn send(&self, message: GraphRuntimeRequest) -> Result<(), String> { - self.sender.send(message).map_err(|e| e.to_string()) - } - - /// Receives any pending updates from the NodeRuntime - pub fn receive(&self) -> impl Iterator + use<'_> { - self.receiver.try_iter() - } -} diff --git a/editor/src/task.rs b/editor/src/task.rs new file mode 100644 index 0000000000..f571fb1c94 --- /dev/null +++ b/editor/src/task.rs @@ -0,0 +1,4 @@ +pub use graphene_std::runtime::{Spawn, Task}; +use std::sync::Arc; + +pub type Spawner = Arc; diff --git a/editor/src/test_utils.rs b/editor/src/test_utils.rs index add951a6a8..8c9cdb5adc 100644 --- a/editor/src/test_utils.rs +++ b/editor/src/test_utils.rs @@ -1,4 +1,6 @@ -use crate::application::Editor; +use crate::application::{DEFAULT_ENVIRONMENT, Editor}; +use crate::builder::{Builder, EditorBuilder, RuntimeBuilder}; +use crate::messages::frontend::utility_types::RenderStatus; use crate::messages::input_mapper::utility_types::keyboard::ModifierKeys; use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ViewportPosition}; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; @@ -8,30 +10,59 @@ use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::ToolType; use crate::node_graph_executor::Instrumented; use crate::node_graph_executor::NodeRuntime; +use crate::task::{Spawn, Task}; use crate::test_utils::test_prelude::LayerNodeIdentifier; +use document_container::store::MemoryStore; use glam::{DVec2, UVec2}; +use graph_craft::application_io::PlatformApplicationIo; +use graph_craft::application_io::resource::HashMapResourceStorage; use graphene_std::raster::color::Color; use graphene_std::uuid::NodeId; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; /// A set of utility functions to make the writing of editor test more declarative pub struct EditorTestUtils { pub editor: Editor, pub runtime: NodeRuntime, + woken: Arc, } impl EditorTestUtils { pub fn create() -> Self { init_test_logger(); - let (mut editor, runtime) = Editor::new_local_executor(); + let woken = Arc::new(AtomicBool::new(false)); + let wake = woken.clone(); + let (editor, runtime) = Builder::new() + .with_editor( + EditorBuilder::new() + .with_wake(move || wake.store(true, Ordering::Relaxed)) + .with_environment(DEFAULT_ENVIRONMENT) + .with_resource_storage(Arc::new(HashMapResourceStorage::new())) + .with_document_store(Arc::new(MemoryStore::default())), + ) + .with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(PlatformApplicationIo::default())) + .with_spawner(BlockingSpawner) + .with_random_seed(0) + .build(); + let mut editor = Self { editor, runtime, woken }; - editor.handle_message(PortfolioMessage::Init); + editor.dispatch(PortfolioMessage::Init); // Tests run with `.gdd` storage on and the dual-write soak validation enabled, so storage round-trip drift fails loud. - editor.handle_message(PreferencesMessage::SaveAsGdd { enabled: true }); - editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: true }); + editor.dispatch(PreferencesMessage::SaveAsGdd { enabled: true }); + editor.dispatch(PreferencesMessage::ValidateStorageRoundTrip { enabled: true }); - Self { editor, runtime } + editor + } + + pub fn dispatch(&mut self, message: impl Into) -> Vec { + let mut responses = self.editor.handle_message(message); + while self.woken.swap(false, Ordering::Relaxed) { + responses.extend(self.editor.handle_message(Message::Wake)); + } + responses } /// Submit an evaluation to the executor, run the runtime, and process the results. @@ -53,11 +84,10 @@ impl EditorTestUtils { } self.runtime.run().await; - let mut messages = VecDeque::new(); - if let Err(e) = self.editor.poll_node_graph_evaluation(&mut messages) { - return Err(format!("Graph should render\n\n{e}")); + let frontend_messages = self.dispatch(Message::Wake); + if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) { + return Err("Graph should render".to_string()); } - let frontend_messages = messages.into_iter().flat_map(|message| self.editor.handle_message(message)); for message in frontend_messages { message.check_node_graph_error(); @@ -81,7 +111,7 @@ impl EditorTestUtils { } pub async fn handle_message(&mut self, message: impl Into) -> Vec { - let frontend_messages_from_msg = self.editor.handle_message(message); + let frontend_messages_from_msg = self.dispatch(message); // Required to process any buffered messages if let Err(e) = self.eval_graph_until_finished().await { @@ -379,9 +409,9 @@ pub trait FrontendMessageTestUtils { impl FrontendMessageTestUtils for FrontendMessage { fn check_node_graph_error(&self) { - let FrontendMessage::UpdateNodeGraphErrorDiagnostic { error } = self else { return }; - if let Some(error) = error { - panic!("error: {:?}", error); + let FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors } = self else { return }; + if !errors.is_empty() { + panic!("errors: {errors:?}"); } } } @@ -440,6 +470,13 @@ pub fn capture_logged_errors(operation: impl FnOnce() -> T) -> (T, Vec {/if} - {#if isWeb} + {#if isWeb && $document.renderStatus === "Rendering"} Initializing Renderer… {/if} + {#if $document.renderStatus === "Error"} + + +

+ The document cannot render in its current state.
+ Undo to go back, if available, or check for error details
+ by clicking the Node Graph button up at the top right. +

+
+
+ {:else if $document.renderStatus === "Panic"} + + +

+ The document crashed while being rendered in its current state.
+ The editor is now unstable! Undo your last action to restore the artwork,
+ then save your document and restart the editor before continuing work. +

+
+
+ {/if}
@@ -961,6 +982,29 @@ } } + .render-status-overlay { + position: absolute; + inset: 0; + align-items: center; + justify-content: center; + background: var(--color-2-mildblack); + pointer-events: none; + + .text-label { + padding: 14px 20px; + border-radius: 4px; + background: var(--color-warning-yellow); + color: var(--color-2-mildblack); + font-size: 18px; + line-height: 24px; + text-align: center; + } + + &.panic .text-label { + background: var(--color-error-red); + } + } + .text-input div { cursor: text; background: none; diff --git a/frontend/src/components/panels/Inspector.svelte b/frontend/src/components/panels/Inspector.svelte index 15bd9b6c9d..c64b18027b 100644 --- a/frontend/src/components/panels/Inspector.svelte +++ b/frontend/src/components/panels/Inspector.svelte @@ -3,6 +3,7 @@ import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte"; import { inspectorLayout } from "/src/stores/portfolio"; + import { createAutoScroller } from "/src/utility-functions/auto-scroll"; import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; const editor = getContext("editor"); @@ -15,12 +16,19 @@ let dragging = false; let fromIndex: number | undefined = undefined; let insertIndex: number | undefined = undefined; - let insertMarkerTop: number | undefined = undefined; + let insertMarker: { top: number; left: number; width: number } | undefined = undefined; let justFinishedDrag = false; // Used to suppress the click event that follows a drag release (which would otherwise toggle a section) + // Scrolling the sections near the panel's edges during a drag shifts them under the pointer, so the gap is found again where the pointer last was + let lastDragClientY = 0; + const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY)); + onMount(() => { addEventListener("pointermove", draggingPointerMove); addEventListener("pointerup", draggingPointerUp); + // A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it + addEventListener("pointercancel", abortDrag); + addEventListener("blur", abortDrag); addEventListener("keydown", draggingKeyDown); addEventListener("mousedown", draggingMouseDown); // Capture phase so this runs before a section header's own click handler @@ -30,9 +38,13 @@ onDestroy(() => { removeEventListener("pointermove", draggingPointerMove); removeEventListener("pointerup", draggingPointerUp); + removeEventListener("pointercancel", abortDrag); + removeEventListener("blur", abortDrag); removeEventListener("keydown", draggingKeyDown); removeEventListener("mousedown", draggingMouseDown); removeEventListener("click", suppressClickAfterDrag, true); + + autoScroller.stop(); }); function suppressClickAfterDrag(e: MouseEvent) { @@ -83,7 +95,11 @@ fromIndex = reorderableSections().findIndex((section) => section.getAttribute("data-node-id") === String(dragState?.nodeId)); } + lastDragClientY = e.clientY; calculateInsertIndex(e.clientY); + + const container = sectionsCol?.div(); + if (container) autoScroller.update(container, e.clientX, e.clientY, 1); } function calculateInsertIndex(clientY: number) { @@ -91,7 +107,7 @@ const sections = reorderableSections(); if (!container || sections.length === 0) { insertIndex = undefined; - insertMarkerTop = undefined; + insertMarker = undefined; return; } @@ -111,17 +127,38 @@ // Position the marker purely from the gap index so it has one fixed spot per gap, rather than snapping between adjacent // sections' edges as the cursor crosses their shared boundary. + // Above the first, it's centered in the room left below what comes before, and below the last, in a gap as wide as the sections leave between each other + const halfGap = (parseFloat(getComputedStyle(sections[0]).getPropertyValue("--section-gap")) || 0) / 2; let markerViewportY; if (index <= 0) { - markerViewportY = sections[0].getBoundingClientRect().top - 2; + markerViewportY = (bottomOfContentAbove(sections[0], container) + sections[0].getBoundingClientRect().top) / 2; } else if (index >= sections.length) { - markerViewportY = sections[sections.length - 1].getBoundingClientRect().bottom + 2; + markerViewportY = sections[sections.length - 1].getBoundingClientRect().bottom + halfGap; } else { markerViewportY = (sections[index - 1].getBoundingClientRect().bottom + sections[index].getBoundingClientRect().top) / 2; } + // Spanning the sections, which a layer's frame around them indents + const firstRect = sections[0].getBoundingClientRect(); + insertIndex = index; - insertMarkerTop = toContentOffset(markerViewportY); + insertMarker = { top: toContentOffset(markerViewportY), left: firstRect.left - containerRect.left, width: firstRect.width }; + } + + // The bottom of what's shown right above a section, which is the last row or section before it (even outside the frame it's in), or else the top of the panel + function bottomOfContentAbove(section: Element, container: HTMLElement): number { + let current = section; + while (current !== container && current.parentElement) { + let previous = current.previousElementSibling; + if (previous) { + // Down through the frames and section bodies to the last row or section within + while (previous.lastElementChild && previous.hasAttribute("data-section-contents")) previous = previous.lastElementChild; + return previous.getBoundingClientRect().bottom; + } + + current = current.parentElement; + } + return container.getBoundingClientRect().top; } function draggingPointerUp(e: PointerEvent) { @@ -156,19 +193,20 @@ } function abortDrag() { + autoScroller.stop(); dragState = undefined; dragging = false; fromIndex = undefined; insertIndex = undefined; - insertMarkerTop = undefined; + insertMarker = undefined; } - {#if dragging && insertMarkerTop !== undefined} -
+ {#if dragging && insertMarker} +
{/if}
@@ -201,8 +239,6 @@ .insert-mark { position: absolute; - left: 4px; - right: 4px; background: var(--color-e-nearwhite); height: 5px; // The marker's `top` is the center of the gap, so shift up by half its height to straddle that line diff --git a/frontend/src/components/panels/Layers.svelte b/frontend/src/components/panels/Layers.svelte index b8488e1c8a..5a07f72c0c 100644 --- a/frontend/src/components/panels/Layers.svelte +++ b/frontend/src/components/panels/Layers.svelte @@ -7,26 +7,35 @@ import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte"; import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle"; import type { NodeGraphStore } from "/src/stores/node-graph"; - import { layersPanelControlBarLeftLayout, layersPanelBottomBarLeftLayout, layersPanelBottomBarRightLayout } from "/src/stores/portfolio"; + import { layersPanelControlBarLeftLayout, layersPanelBottomBarLeftLayout, layersPanelBottomBarRightLayout, retainLayerDetails } from "/src/stores/portfolio"; import type { PortfolioStore } from "/src/stores/portfolio"; import type { TooltipStore } from "/src/stores/tooltip"; + import { createAutoScroller, speedWhileAimingAt } from "/src/utility-functions/auto-scroll"; import { pasteFile } from "/src/utility-functions/files"; + import { targetIsTextField } from "/src/utility-functions/input"; import { operatingSystem } from "/src/utility-functions/platform"; import type { EditorWrapper, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry, LayerStructureEntry } from "/wrapper/pkg/graphite_wasm_wrapper"; type LayerListingInfo = { + id: bigint; folderIndex: number; bottomLayer: boolean; editingName: boolean; - entry: LayerPanelEntry; + // Known only while the listing is in view, since the backend sends the details of just those layers + entry: LayerPanelEntry | undefined; depth: number; parentId: bigint | undefined; - childrenPresent: boolean; - expanded: boolean; - ancestorOfSelected: boolean; + // Along this listing's own path, since a layer listed under several parents can inherit a hide or lock from just one parentsVisible: boolean; parentsUnlocked: boolean; + childrenPresent: boolean; + expanded: boolean; + selected: boolean; + ancestorOfSelected: boolean; treePath: bigint[]; + // Where the listing's rows start in the list, and how tall they are together with those of its expanded chain + top: number; + height: number; }; type DraggingData = { @@ -56,6 +65,9 @@ startY: number; }; + // What a drag reads from a pointer move, which auto-scrolling also gives when it redoes the drag where the pointer last was + type DragPointer = Pick; + // One place along a layer's chain: one of its nodes (with its place among the reorderable ones, if it is one), or the ghost of a node the active tool would add there type ChainSlot = { kind: "node"; node: LayerPanelChainNode; nodeIndex: number; reorderablePosition: number | undefined } | { kind: "insertion"; insertion: LayerPanelChainInsertion }; @@ -67,14 +79,32 @@ const CHAIN_EXPAND_ARROW_WIDTH = 12; const LAYER_ICON_WIDTH = 20; + // The height of a layer's row and of a row listing a node of its expanded chain, each with its bottom border, as styled below + const LAYER_ROW_HEIGHT = 33; + const CHAIN_NODE_ROW_HEIGHT = 25; + // Rows this far past either end of the list's visible part are rendered too, so scrolling doesn't uncover them before they appear + const RENDERED_BEYOND_VIEW_PIXELS = 240; + const editor = getContext("editor"); const nodeGraph = getContext("nodeGraph"); const tooltip = getContext("tooltip"); const portfolio = getContext("portfolio"); + let listArea: LayoutRow | undefined; + let bottomBar: LayoutRow | undefined; let list: LayoutCol | undefined; let layers: LayerListingInfo[] = []; + let layersBuiltFrom: LayerStructureEntry[] | undefined = undefined; + + // Rows are rendered only for the listings from `firstRendered` up to but not including `endRendered`, with the rest of the list's height left empty around them + let firstRendered = 0; + let endRendered = 0; + let listHeight = 0; + // The document and layers the backend was last told have rows rendered, which it sends the details and thumbnails of + let renderedDocumentSent: bigint | undefined = undefined; + let renderedLayersSent = ""; + const listAreaResizeObserver = new ResizeObserver(() => updateRenderedRows()); // Interactive dragging let draggable = true; @@ -95,9 +125,21 @@ let chainRowInsertMarker: { nodeIndex: number; edge: "top" | "bottom" } | undefined = undefined; let chainDragDropTarget: HTMLElement | undefined = undefined; + // Scrolling the list near its edges during a drag shifts the content under the pointer, so the drag is redone where the pointer last was + let lastDragPointer: { clientX: number; clientY: number } | undefined = undefined; + const autoScroller = createAutoScroller(() => { + if (!lastDragPointer) return; + const { clientX, clientY } = lastDragPointer; + + if (internalDragState || chainDragState) draggingPointerMove({ clientX, clientY, target: document.elementFromPoint(clientX, clientY) }); + else if (list) draggingData = calculateDragIndex(list, clientY); + }); + // Viewport hover outline, tracked by row index since rows get reused when the layers change beneath a still pointer let hoveredRowIndex: number | undefined = undefined; let hoveredLayerSent: bigint | undefined = undefined; + // Scrolling carries rows beneath a pointer that hasn't moved, which doesn't count as hovering them until it moves again + let hoverPausedByScroll = false; // Interactive clipping let layerToClipUponClick: LayerListingInfo | undefined = undefined; @@ -119,14 +161,20 @@ chainWidths = chainWidths; }); - $: rebuildLayerHierarchy($portfolio.layerStructure, $portfolio.layerCache); + $: rebuildLayerHierarchy($portfolio.layerStructure); + $: attachLayerDetails($portfolio.layerCache); $: sendHoveredLayer(layers, hoveredRowIndex); onMount(() => { createDragToggleManager(dragToggleListener); + const listAreaDiv = listArea?.div(); + if (listAreaDiv) listAreaResizeObserver.observe(listAreaDiv); + addEventListener("pointerup", draggingPointerUp); addEventListener("pointermove", draggingPointerMove); + addEventListener("pointercancel", abortDrags); + addEventListener("blur", abortDrags); addEventListener("mousedown", draggingMouseDown); addEventListener("keydown", draggingKeyDown); addEventListener("keydown", handleLayerPanelKeyDown); @@ -134,6 +182,8 @@ addEventListener("pointermove", clippingHover); addEventListener("keydown", clippingKeyPress); addEventListener("keyup", clippingKeyPress); + + addEventListener("pointermove", resumeHoverAfterScroll); }); onDestroy(() => { @@ -141,6 +191,8 @@ removeEventListener("pointerup", draggingPointerUp); removeEventListener("pointermove", draggingPointerMove); + removeEventListener("pointercancel", abortDrags); + removeEventListener("blur", abortDrags); removeEventListener("mousedown", draggingMouseDown); removeEventListener("keydown", draggingKeyDown); removeEventListener("keydown", handleLayerPanelKeyDown); @@ -149,14 +201,125 @@ removeEventListener("keydown", clippingKeyPress); removeEventListener("keyup", clippingKeyPress); + removeEventListener("pointermove", resumeHoverAfterScroll); + chainResizeObserver.disconnect(); + listAreaResizeObserver.disconnect(); + stopAutoScroll(); + + // With no rows left, the backend stops sending details, so the ones kept here would go stale + editor.setLayersPanelView(new BigUint64Array(), new BigUint64Array()); + retainLayerDetails(new Set(), false); // Closing the panel removes the hovered row without a `pointerleave` if (hoveredLayerSent !== undefined) editor.setLayersPanelHoveredLayer(undefined); }); + // Renders the rows of just the listings in or near view, and tells the backend which layers those are so it sends only their details and thumbnails + function updateRenderedRows() { + const container = listArea?.div(); + const listElement = list?.div(); + if (!container || !listElement) return; + + // Measured from the top of the list's first row + const renderedTop = container.scrollTop - listElement.offsetTop - RENDERED_BEYOND_VIEW_PIXELS; + const renderedBottom = container.scrollTop - listElement.offsetTop + container.clientHeight + RENDERED_BEYOND_VIEW_PIXELS; + + const [previousFirstRendered, previousEndRendered] = [firstRendered, endRendered]; + firstRendered = firstListingWhere((listing) => listing.top + listing.height > renderedTop); + endRendered = firstListingWhere((listing) => listing.top >= renderedBottom); + + // Listings no longer rendered let go of their details, which the backend stops keeping current, and of renaming, since their removed input can't lose focus to end it + layers.slice(previousFirstRendered, previousEndRendered).forEach((listing, offset) => { + const index = previousFirstRendered + offset; + if (index >= firstRendered && index < endRendered) return; + + listing.entry = undefined; + if (listing.editingName) { + listing.editingName = false; + draggable = true; + } + }); + + attachLayerDetails($portfolio.layerCache); + sendRenderedLayers(); + } + + // The index of the first listing meeting a condition that every later listing meets too, found in O(log n) + function firstListingWhere(condition: (listing: LayerListingInfo) => boolean): number { + let low = 0; + let high = layers.length; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (condition(layers[middle])) high = middle; + else low = middle + 1; + } + return low; + } + + function sendRenderedLayers() { + const documentId = $portfolio.documents[$portfolio.activeDocumentIndex]?.id; + const renderedLayers = layers.slice(firstRendered, endRendered).map((listing) => listing.id); + const key = renderedLayers.join(","); + if (documentId === renderedDocumentSent && key === renderedLayersSent) return; + const otherDocument = documentId !== renderedDocumentSent; + renderedDocumentSent = documentId; + renderedLayersSent = key; + + // The backend keeps only these layers' details current, so the others kept here would go stale + retainLayerDetails(new Set(renderedLayers.map(String)), otherDocument); + const missingDetails = renderedLayers.filter((id) => !$portfolio.layerCache.has(String(id))); + editor.setLayersPanelView(BigUint64Array.from(renderedLayers), BigUint64Array.from(missingDetails)); + } + + // O(rendered rows) + function attachLayerDetails(cache: Map) { + layers.slice(firstRendered, endRendered).forEach((listing) => { + listing.entry = cache.get(String(listing.id)); + }); + layers = layers; + } + + // Brings a listing's rows into view, rendering them before it resolves + async function scrollListingIntoView(listing: LayerListingInfo) { + const container = listArea?.div(); + const listElement = list?.div(); + if (!container || !listElement) return; + + const top = listElement.offsetTop + listing.top; + if (top < container.scrollTop) container.scrollTop = top; + else if (top + LAYER_ROW_HEIGHT > container.scrollTop + container.clientHeight) container.scrollTop = top + LAYER_ROW_HEIGHT - container.clientHeight; + + updateRenderedRows(); + await tick(); + } + + function listAreaScroll() { + pauseHoverForScroll(); + updateRenderedRows(); + } + + function hoverRow(rowIndex: number) { + if (!hoverPausedByScroll) hoveredRowIndex = rowIndex; + } + + function pauseHoverForScroll() { + hoverPausedByScroll = true; + hoveredRowIndex = undefined; + } + + // The pointer's first actual move after a scroll hovers whichever row it's over, which it may have entered while hovering was paused + function resumeHoverAfterScroll(e: PointerEvent) { + if (!hoverPausedByScroll || (e.movementX === 0 && e.movementY === 0)) return; + hoverPausedByScroll = false; + + const row = e.target instanceof Element ? e.target.closest("[data-layer], [data-chain-row-of]") : undefined; + if (!row || !list?.div()?.contains(row)) return; + hoveredRowIndex = Number(row.getAttribute("data-chain-row-of") || row.getAttribute("data-index")); + } + function sendHoveredLayer(listings: LayerListingInfo[], rowIndex: number | undefined) { - const id = rowIndex === undefined ? undefined : listings.at(rowIndex)?.entry.id; + const id = rowIndex === undefined ? undefined : listings.at(rowIndex)?.id; if (id === hoveredLayerSent) return; hoveredLayerSent = id; @@ -185,6 +348,9 @@ async function onEditLayerName(listing: LayerListingInfo) { if (listing.editingName) return; + // A layer chosen from beyond the rendered rows, like the next one by keyboard, needs its row before its name can be edited + await scrollListingIntoView(listing); + draggable = false; listing.editingName = true; layers = layers; @@ -205,8 +371,8 @@ layers = layers; const name = (e.target instanceof HTMLInputElement && e.target.value) || ""; - editor.setLayerName(listing.entry.id, name); - listing.entry.alias = name; + editor.setLayerName(listing.id, name); + if (listing.entry) listing.entry.alias = name; } async function onEditLayerNameDeselect(listing: LayerListingInfo) { @@ -215,7 +381,7 @@ layers = layers; // Set it back to the original name if the user didn't enter a new name - if (document.activeElement instanceof HTMLInputElement) document.activeElement.value = listing.entry.alias; + if (document.activeElement instanceof HTMLInputElement) document.activeElement.value = listing.entry?.alias || ""; // Deselect the text so it doesn't appear selected while the input field becomes disabled and styled to look like regular text window.getSelection()?.removeAllRanges(); @@ -268,7 +434,7 @@ const [accel, oppositeAccel] = operatingSystem() === "Mac" ? [meta, ctrl] : [ctrl, meta]; // Alt-clicking to make a clipping mask - if (layerToClipAltKeyPressed && layerToClipUponClick && layerToClipUponClick.entry.clippable) clipLayer(layerToClipUponClick); + if (layerToClipAltKeyPressed && layerToClipUponClick?.entry?.clippable) clipLayer(layerToClipUponClick); // Select the layer only if the accel and/or shift keys are pressed else if (!oppositeAccel && !alt) selectLayer(listing, accel, shift); @@ -276,7 +442,7 @@ } function clipLayer(listing: LayerListingInfo) { - editor.clipLayer(listing.entry.id); + editor.clipLayer(listing.id); } function clippingKeyPress(e: KeyboardEvent) { @@ -323,7 +489,7 @@ // Don't select while we are entering text to rename the layer if (listing.editingName) return; - editor.selectLayer(listing.entry.id, accel, shift); + editor.selectLayer(listing.id, accel, shift); } function chainNodeClick(e: MouseEvent | undefined, listing: LayerListingInfo, nodeId: bigint) { @@ -336,17 +502,17 @@ const [accel, oppositeAccel] = operatingSystem() === "Mac" ? [e?.metaKey, e?.ctrlKey] : [e?.ctrlKey, e?.metaKey]; if (oppositeAccel || e?.altKey) return; - editor.selectChainNode(listing.entry.id, nodeId, Boolean(accel), Boolean(e?.shiftKey)); + editor.selectChainNode(listing.id, nodeId, Boolean(accel), Boolean(e?.shiftKey)); } // Double-clicking a chain node's icon, or the layer's own icon at the row's end (unless it expands the chain), opens the graph centered on that node function chainIconsDoubleClick(e: MouseEvent, listing: LayerListingInfo) { const target = e.target instanceof Element ? e.target : undefined; const chainNodeButton = target?.closest("[data-chain-node]"); - const chainNode = chainNodeButton ? listing.entry.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined; + const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined; if (chainNode) editor.showNodeInGraph(chainNode.id); - else if (target?.closest("[data-layer-icon]") && !target.closest("[data-chain-expandable]")) editor.showNodeInGraph(listing.entry.id); + else if (target?.closest("[data-layer-icon]") && !target.closest("[data-chain-expandable]")) editor.showNodeInGraph(listing.id); } // The kind of node it is, followed by its name if it's been renamed @@ -461,14 +627,14 @@ // Dropping after the layer lands below its chain's node rows, if they're shown const lastChainRow = Array.from(treeChildren).findLast((child) => child.getAttribute("data-chain-row-of") === indexAttribute); const bottom = (lastChainRow || treeChild).getBoundingClientRect().bottom; - if (listing.entry.childrenAllowed || listing.childrenPresent) { + if (listing.entry?.childrenAllowed || listing.childrenPresent) { if (pointerPercentage < 0.25) { insertParentId = listing.parentId; insertDepth = listing.depth - 1; insertIndex = listing.folderIndex; markerHeight = rect.top - layerPanelTop; } else if (pointerPercentage < 0.75 || (listing.childrenPresent && listing.expanded)) { - insertParentId = listing.entry.id; + insertParentId = listing.id; insertDepth = listing.depth; insertIndex = 0; highlightFolder = true; @@ -493,9 +659,9 @@ } } }); - // Dragging to the empty space below all layers - let lastLayer = treeChildren[treeChildren.length - 1]; - if (lastLayer.getBoundingClientRect().bottom < clientY) { + // Dragging to the empty space below all layers, which only follows the last row once that's rendered + const lastLayer = treeChildren[treeChildren.length - 1]; + if (endRendered === layers.length && lastLayer && lastLayer.getBoundingClientRect().bottom < clientY) { const numberRootLayers = layers.filter((listing) => listing.depth === 1).length; insertParentId = undefined; insertDepth = 0; @@ -522,14 +688,14 @@ // Pressing one of the chain's node buttons drags that node within the chain, rather than dragging the whole layer const chainNodeButton = (e.target instanceof Element && e.target.closest("[data-chain-node]")) || undefined; if (chainNodeButton) { - const chainNode = listing.entry.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))]; + const chainNode = listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))]; if (chainNode) chainNodePointerDown(e, listing, chainNode); return; } internalDragState = { active: false, - layerId: listing.entry.id, + layerId: listing.id, listing: listing, startX: e.clientX, startY: e.clientY, @@ -541,12 +707,42 @@ if (!chainNode.reorderable) return; // Dragging a selected node brings along the chain's other selected nodes, which all end up together at the drop - const nodeIds = chainNode.selected ? listing.entry.chainNodes.filter((node) => node.reorderable && node.selected).map((node) => node.id) : [chainNode.id]; + const chainNodes = listing.entry?.chainNodes || []; + const nodeIds = chainNode.selected ? chainNodes.filter((node) => node.reorderable && node.selected).map((node) => node.id) : [chainNode.id]; - chainDragState = { active: false, layerId: listing.entry.id, nodeIds, startX: e.clientX, startY: e.clientY }; + chainDragState = { active: false, layerId: listing.id, nodeIds, startX: e.clientX, startY: e.clientY }; } - function chainDraggingPointerMove(e: PointerEvent) { + // Scrolls the list while a drag's pointer is near or past its top or bottom edge, easing off while it heads from where it began toward a bottom bar button it can be dropped on + function autoScrollDrag(clientX: number, clientY: number, aim?: { start: [number, number]; droppable: string }) { + lastDragPointer = { clientX, clientY }; + const container = listArea?.div(); + if (!container) return; + + const dropTargets = aim && dropTargetBounds(aim.droppable); + const speed = aim && dropTargets ? speedWhileAimingAt(aim.start, clientX, clientY, dropTargets) : 1; + autoScroller.update(container, clientX, clientY, speed); + } + + // The area spanned by the bottom bar buttons that accept the kind of item being dragged + function dropTargetBounds(droppable: string): DOMRect | undefined { + const buttons = Array.from(bottomBar?.div()?.querySelectorAll(`[data-drag-droppable~="${droppable}"]`) || []); + if (buttons.length === 0) return undefined; + + const rects = buttons.map((button) => button.getBoundingClientRect()); + const left = Math.min(...rects.map((rect) => rect.left)); + const top = Math.min(...rects.map((rect) => rect.top)); + const right = Math.max(...rects.map((rect) => rect.right)); + const bottom = Math.max(...rects.map((rect) => rect.bottom)); + return new DOMRect(left, top, right - left, bottom - top); + } + + function stopAutoScroll() { + lastDragPointer = undefined; + autoScroller.stop(); + } + + function chainDraggingPointerMove(e: DragPointer) { if (!chainDragState) return; if (!chainDragState.active) { @@ -569,6 +765,7 @@ const target = e.target instanceof Element ? e.target : undefined; const droppable = target?.closest("[data-drag-droppable~=chain-nodes]"); chainDragDropTarget = droppable instanceof HTMLElement ? droppable : undefined; + autoScrollDrag(e.clientX, e.clientY, { start: [chainDragState.startX, chainDragState.startY], droppable: "chain-nodes" }); if (chainDragDropTarget || target?.closest("[data-layer-bottom-bar]")) return; // Otherwise the nodes drop into the chain of whichever layer is under the cursor, or whose expanded chain's node row is @@ -601,7 +798,7 @@ let markerX: number | undefined; let index: number; if (edges.length === 0) { - index = layers[Number(row.getAttribute("data-index"))]?.entry.chainNodes.filter((node) => node.reorderable).length || 0; + index = layers[Number(row.getAttribute("data-index"))]?.entry?.chainNodes.filter((node) => node.reorderable).length || 0; const chainNodeButtons = row.querySelectorAll("[data-chain-node]"); const fixedSource = chainNodeButtons[chainNodeButtons.length - 1]; markerX = fixedSource ? fixedSource.getBoundingClientRect().right : row.querySelector("[data-layer-chain]")?.getBoundingClientRect().left; @@ -692,9 +889,10 @@ chainRowInsertMarker = undefined; chainDragDropTarget = undefined; dragInPanel = false; + stopAutoScroll(); } - function draggingPointerMove(e: PointerEvent) { + function draggingPointerMove(e: DragPointer) { if (chainDragState) { chainDraggingPointerMove(e); return; @@ -712,9 +910,9 @@ dragInPanel = true; layerToClipUponClick = undefined; - const layer = internalDragState.listing.entry; - if (!$nodeGraph.selected.includes(layer.id)) { - fakeHighlightOfNotYetSelectedLayerBeingDragged = layer.id; + const layerId = internalDragState.listing.id; + if (!$nodeGraph.selected.includes(layerId)) { + fakeHighlightOfNotYetSelectedLayerBeingDragged = layerId; } } } @@ -728,6 +926,7 @@ // Hide the move-in-tree insert indicator whenever the cursor enters the bottom bar const overBottomBar = ((e.target instanceof Element && e.target.closest("[data-layer-bottom-bar]")) || undefined) !== undefined; + autoScrollDrag(e.clientX, e.clientY, { start: [internalDragState.startX, internalDragState.startY], droppable: "layers" }); if (dragDropTarget || overBottomBar) { draggingData = undefined; return; @@ -786,6 +985,13 @@ fakeHighlightOfNotYetSelectedLayerBeingDragged = undefined; dragInPanel = false; dragDropTarget = undefined; + stopAutoScroll(); + } + + // A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it + function abortDrags() { + if (internalDragState) abortDrag(); + if (chainDragState) abortChainDrag(); } function draggingMouseDown(e: MouseEvent) { @@ -814,10 +1020,10 @@ function handleLayerPanelKeyDown(e: KeyboardEvent) { // TODO: Handle this F2 shortcut detection in the backend, not frontend, so it uses the standard key binding system - // Only handle F2 if not currently editing a layer name - if (e.key === "F2" && !layers.some((layer) => layer.editingName)) { + // Only handle F2 if not currently editing a layer name or typing in another text field + if (e.key === "F2" && !layers.some((layer) => layer.editingName) && !targetIsTextField(e.target || undefined)) { // Find the first selected layer - const selectedLayer = layers.find((layer) => layer.entry.selected); + const selectedLayer = layers.find((layer) => layer.selected); if (selectedLayer) { e.preventDefault(); onEditLayerName(selectedLayer); @@ -830,12 +1036,12 @@ const inputElement = document.activeElement; if (inputElement instanceof HTMLInputElement) { const name = inputElement.value || ""; - editor.setLayerName(currentListing.entry.id, name); - currentListing.entry.alias = name; + editor.setLayerName(currentListing.id, name); + if (currentListing.entry) currentListing.entry.alias = name; } // Find current layer index - const currentIndex = layers.findIndex((layer) => layer.entry.id === currentListing.entry.id); + const currentIndex = layers.indexOf(currentListing); if (currentIndex === -1) return; // Calculate target index based on direction @@ -862,6 +1068,16 @@ dragInPanel = true; if (list) draggingData = calculateDragIndex(list, e.clientY); + autoScrollDrag(e.clientX, e.clientY); + } + + function fileDragLeave(e: DragEvent) { + // Crossing between the list's own elements, as auto-scrolling content does beneath the pointer, doesn't leave the list where files are dropped + const listAreaDiv = listArea?.div(); + if (listAreaDiv && e.relatedTarget instanceof Node && listAreaDiv.contains(e.relatedTarget)) return; + + dragInPanel = false; + stopAutoScroll(); } function fileDrop(e: DragEvent) { @@ -876,336 +1092,365 @@ draggingData = undefined; fakeHighlightOfNotYetSelectedLayerBeingDragged = undefined; dragInPanel = false; + stopAutoScroll(); } - function rebuildLayerHierarchy(layerStructure: LayerStructureEntry[], cache: Map) { + // O(listed layers), so it's skipped when only the layers' details change + function rebuildLayerHierarchy(layerStructure: LayerStructureEntry[]) { + if (layerStructure === layersBuiltFrom) return; + layersBuiltFrom = layerStructure; + // Track the editing state by flat list index, not layer ID, since a layer can appear at multiple positions const editingIndex = layers.findIndex((layer: LayerListingInfo) => layer.editingName); // Clear the layer hierarchy before rebuilding it layers = []; + let top = 0; // Build the new layer hierarchy const recurse = (children: LayerStructureEntry[], depth: number, parentId: bigint | undefined, parentPath: bigint[], parentsVisible: boolean, parentsUnlocked: boolean) => { children.forEach((item, index) => { const treePath = [...parentPath, item.layerId]; - const mapping = cache.get(String(item.layerId)); + const height = LAYER_ROW_HEIGHT + item.chainRows * CHAIN_NODE_ROW_HEIGHT; - if (mapping) { - mapping.id = item.layerId; - layers.push({ - folderIndex: index, - bottomLayer: index === children.length - 1, - entry: mapping, - editingName: editingIndex === layers.length, - depth, - parentId, - childrenPresent: item.childrenPresent, - expanded: item.childrenPresent && item.children.length > 0, - ancestorOfSelected: item.descendantSelected, - parentsVisible, - parentsUnlocked, - treePath, - }); - } + layers.push({ + id: item.layerId, + folderIndex: index, + bottomLayer: index === children.length - 1, + editingName: editingIndex === layers.length, + entry: undefined, + depth, + parentId, + parentsVisible, + parentsUnlocked, + childrenPresent: item.childrenPresent, + expanded: item.childrenPresent && item.children.length > 0, + selected: item.selected, + ancestorOfSelected: item.descendantSelected, + treePath, + top, + height, + }); + top += height; - // Call self recursively, propagating this layer's visibility/lock state to its children - const childParentsVisible = parentsVisible && (mapping?.visible ?? true); - const childParentsUnlocked = parentsUnlocked && (mapping?.unlocked ?? true); - if (item.children.length >= 1) recurse(item.children, depth + 1, item.layerId, treePath, childParentsVisible, childParentsUnlocked); + if (item.children.length >= 1) recurse(item.children, depth + 1, item.layerId, treePath, parentsVisible && item.visible, parentsUnlocked && item.unlocked); }); }; recurse(layerStructure, 1, undefined, [], true, true); - layers = layers; + listHeight = top; + + updateRenderedRows(); } - (dragInPanel = false)}> + - + deselectAllLayers()} on:dragover={fileDragOver} on:drop={fileDrop} > - {#each layers as listing, index} - {@const selected = fakeHighlightOfNotYetSelectedLayerBeingDragged !== undefined ? fakeHighlightOfNotYetSelectedLayerBeingDragged === listing.entry.id : listing.entry.selected} - {@const slots = chainSlots(listing.entry)} - {@const inlineSlots = listing.entry.chainExpanded && listing.entry.chainNodes.length > 0 ? slots.filter((slot) => slot.kind === "insertion") : slots} - {@const ellipsis = chainEllipsis(inlineSlots, chainWidths[index])} - layerPointerDown(e, listing)} - on:click={(e) => selectLayerWithModifiers(e, listing)} - on:dblclick={(e) => chainIconsDoubleClick(e, listing)} - on:pointerenter={() => (hoveredRowIndex = index)} - on:pointerleave={() => (hoveredRowIndex = undefined)} - > - (toggleNodeVisibilityLayerPanel(listing.entry.id), e?.stopPropagation())} - size={24} - icon={listing.entry.visible ? "EyeVisible" : "EyeHidden"} - hoverIcon={listing.entry.visible ? "EyeHide" : "EyeShow"} - tooltipLabel={listing.entry.visible ? "Hide" : "Show"} - tooltipDescription={!listing.parentsVisible ? "A parent of this layer is hidden and that status is being inherited." : ""} - data-drag-toggle-group="layer-visibility" - data-drag-toggle-state={listing.entry.visible ? "visible" : "hidden"} - /> - {#if listing.entry.childrenAllowed || listing.childrenPresent} - - {:else} -
- {/if} - {#if listing.entry.clipped} - +
+ + {#each layers.slice(firstRendered, endRendered) as listing, renderedIndex (firstRendered + renderedIndex)} + {@const index = firstRendered + renderedIndex} + {#if !listing.entry} + +
+ {:else} + {@const entry = listing.entry} + {@const selected = fakeHighlightOfNotYetSelectedLayerBeingDragged !== undefined ? fakeHighlightOfNotYetSelectedLayerBeingDragged === listing.id : entry.selected} + {@const slots = chainSlots(entry)} + {@const inlineSlots = entry.chainExpanded && entry.chainNodes.length > 0 ? slots.filter((slot) => slot.kind === "insertion") : slots} + {@const ellipsis = chainEllipsis(inlineSlots, chainWidths[index])} + layerPointerDown(e, listing)} + on:click={(e) => selectLayerWithModifiers(e, listing)} + on:dblclick={(e) => chainIconsDoubleClick(e, listing)} + on:pointerenter={() => hoverRow(index)} + on:pointerleave={() => (hoveredRowIndex = undefined)} + > + (toggleNodeVisibilityLayerPanel(listing.id), e?.stopPropagation())} + size={24} + icon={entry.visible ? "EyeVisible" : "EyeHidden"} + hoverIcon={entry.visible ? "EyeHide" : "EyeShow"} + tooltipLabel={entry.visible ? "Hide" : "Show"} + tooltipDescription={!listing.parentsVisible ? "A parent of this layer is hidden and that status is being inherited." : ""} + data-drag-toggle-group="layer-visibility" + data-drag-toggle-state={entry.visible ? "visible" : "hidden"} /> - {/if} -
- {#if $nodeGraph.thumbnails.has(listing.entry.id)} - {@html $nodeGraph.thumbnails.get(listing.entry.id)} + {#if entry.childrenAllowed || listing.childrenPresent} + + {:else} +
{/if} -
-
0)}px`}> - onEditLayerName(listing)}> - onEditLayerNameDeselect(listing)} - on:keydown={(e) => { - if (e.key === "Escape") { - onEditLayerNameDeselect(listing); - } else if (e.key === "Enter") { - onEditLayerNameChange(listing, e); - } else if (e.key === "Tab") { - e.preventDefault(); - navigateToLayer(listing, e.shiftKey ? "Up" : "Down"); - } else if (e.key === "ArrowUp") { - e.preventDefault(); - navigateToLayer(listing, "Up"); - } else if (e.key === "ArrowDown") { - e.preventDefault(); - navigateToLayer(listing, "Down"); - } - }} - on:change={(e) => onEditLayerNameChange(listing, e)} - /> - - {#if !listing.entry.unlocked || !listing.parentsUnlocked} - (toggleLayerLock(listing.entry.id), e?.stopPropagation())} - size={24} - icon={listing.entry.unlocked ? "PadlockUnlocked" : "PadlockLocked"} - hoverIcon={listing.entry.unlocked ? "PadlockLocked" : "PadlockUnlocked"} - tooltipLabel={listing.entry.unlocked ? "Lock" : "Unlock"} - tooltipDescription={!listing.parentsUnlocked ? "A parent of this layer is locked and that status is being inherited." : ""} - data-drag-toggle-group="layer-lock" - data-drag-toggle-state={listing.entry.unlocked ? "unlocked" : "locked"} - /> - {:else if activeDragToggleGroup === "layer-lock"} - (toggleLayerLock(listing.entry.id), e?.stopPropagation())} - size={24} - icon="PadlockUnlocked" - data-drag-toggle-group="layer-lock" - data-drag-toggle-state="unlocked" + {#if entry.clipped} + {/if} - -
- {#if chainFits(inlineSlots.length, slots.length > 0, chainWidths[index])} - - {#each inlineSlots as slot, slotIndex} - {#if ellipsis && slotIndex === ellipsis.start} - node.selected), - "tool-target": ellipsis.nodes.some((node) => node.toolTargetDescription), - "edit-in-progress": ellipsis.nodes.some((node) => node.editInProgress), - }} - tooltipLabel={`${ellipsis.nodes.length} More Nodes`} - tooltipDescription={ellipsis.nodes.map((node) => node.name).join(", ")} - data-chain-gap-before={ellipsis.gapBefore} - data-chain-gap-after={ellipsis.gapAfter} - > - - - - - - - {/if} - {#if !ellipsis || slotIndex < ellipsis.start || slotIndex >= ellipsis.end} - {#if slot.kind === "insertion"} - - {:else} - {@const chainNode = slot.node} - chainNodeClick(e, listing, chainNode.id)} - tooltipLabel={chainNodeTooltipLabel(chainNode)} - tooltipDescription={chainNode.toolTargetDescription} - data-chain-node={slot.nodeIndex} - data-chain-gap-before={slot.reorderablePosition} - data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1} - /> - {/if} - {/if} - {/each} - +
+ {#if $nodeGraph.thumbnails.has(listing.id)} + {@html $nodeGraph.thumbnails.get(listing.id)} {/if}
-
- {#if chainDropRowIndex === index && chainInsertMarkerLeft !== undefined} -
- {/if} -
- {#if listing.entry.chainExpanded} - - {#each slots.flatMap((slot) => (slot.kind === "node" ? [slot] : [])).reverse() as slot} - {@const chainNode = slot.node} - {@const editingName = editingChainNodeName?.rowIndex === index && editingChainNodeName.nodeId === chainNode.id} - { - if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode); - }} - on:click={(e) => chainNodeClick(e, listing, chainNode.id)} - on:dblclick={(e) => { - // Only the node's icon opens it in the graph - if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id); - }} - on:pointerenter={() => (hoveredRowIndex = index)} - on:pointerleave={() => (hoveredRowIndex = undefined)} - > - (toggleNodeVisibilityLayerPanel(chainNode.id), e?.stopPropagation())} - size={24} - icon={chainNode.visible ? "EyeVisible" : "EyeHidden"} - hoverIcon={chainNode.visible ? "EyeHide" : "EyeShow"} - tooltipLabel={chainNode.visible ? "Hide" : "Show"} - data-drag-toggle-group="layer-visibility" - data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"} - /> - onEditChainNodeName(index, chainNode.id)}> +
0)}px`}> + onEditLayerName(listing)}> onEditChainNodeNameDeselect(chainNode)} + value={entry.alias} + placeholder={entry.implementationName} + disabled={!listing.editingName} + on:blur={() => onEditLayerNameDeselect(listing)} on:keydown={(e) => { - if (e.key === "Escape") onEditChainNodeNameDeselect(chainNode); - else if (e.key === "Enter") onEditChainNodeNameChange(chainNode.id, e); + if (e.key === "Escape") { + onEditLayerNameDeselect(listing); + } else if (e.key === "Enter") { + onEditLayerNameChange(listing, e); + } else if (e.key === "Tab") { + e.preventDefault(); + navigateToLayer(listing, e.shiftKey ? "Up" : "Down"); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + navigateToLayer(listing, "Up"); + } else if (e.key === "ArrowDown") { + e.preventDefault(); + navigateToLayer(listing, "Down"); + } }} - on:change={(e) => onEditChainNodeNameChange(chainNode.id, e)} + on:change={(e) => onEditLayerNameChange(listing, e)} /> - - {#if chainDropRowIndex === index && chainRowInsertMarker?.nodeIndex === slot.nodeIndex} -
+ {#if !entry.unlocked || !listing.parentsUnlocked} + (toggleLayerLock(listing.id), e?.stopPropagation())} + size={24} + icon={entry.unlocked ? "PadlockUnlocked" : "PadlockLocked"} + hoverIcon={entry.unlocked ? "PadlockLocked" : "PadlockUnlocked"} + tooltipLabel={entry.unlocked ? "Lock" : "Unlock"} + tooltipDescription={!listing.parentsUnlocked ? "A parent of this layer is locked and that status is being inherited." : ""} + data-drag-toggle-group="layer-lock" + data-drag-toggle-state={entry.unlocked ? "unlocked" : "locked"} + /> + {:else if activeDragToggleGroup === "layer-lock"} + (toggleLayerLock(listing.id), e?.stopPropagation())} + size={24} + icon="PadlockUnlocked" + data-drag-toggle-group="layer-lock" + data-drag-toggle-state="unlocked" + /> {/if} - - {/each} + +
+ {#if chainFits(inlineSlots.length, slots.length > 0, chainWidths[index])} + + {#each inlineSlots as slot, slotIndex} + {#if ellipsis && slotIndex === ellipsis.start} + node.selected), + "tool-target": ellipsis.nodes.some((node) => node.toolTargetDescription), + "edit-in-progress": ellipsis.nodes.some((node) => node.editInProgress), + }} + tooltipLabel={`${ellipsis.nodes.length} More Nodes`} + tooltipDescription={ellipsis.nodes.map((node) => node.name).join(", ")} + data-chain-gap-before={ellipsis.gapBefore} + data-chain-gap-after={ellipsis.gapAfter} + > + + + + + + + {/if} + {#if !ellipsis || slotIndex < ellipsis.start || slotIndex >= ellipsis.end} + {#if slot.kind === "insertion"} + + {:else} + {@const chainNode = slot.node} + chainNodeClick(e, listing, chainNode.id)} + tooltipLabel={chainNodeTooltipLabel(chainNode)} + tooltipDescription={chainNode.toolTargetDescription} + data-chain-node={slot.nodeIndex} + data-chain-gap-before={slot.reorderablePosition} + data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1} + /> + {/if} + {/if} + {/each} + + {/if} +
+
+ {#if chainDropRowIndex === index && chainInsertMarkerLeft !== undefined} +
+ {/if} +
+ {#if entry.chainExpanded} + + {#each slots.flatMap((slot) => (slot.kind === "node" ? [slot] : [])).reverse() as slot} + {@const chainNode = slot.node} + {@const editingName = editingChainNodeName?.rowIndex === index && editingChainNodeName.nodeId === chainNode.id} + { + if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode); + }} + on:click={(e) => chainNodeClick(e, listing, chainNode.id)} + on:dblclick={(e) => { + // Only the node's icon opens it in the graph + if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id); + }} + on:pointerenter={() => hoverRow(index)} + on:pointerleave={() => (hoveredRowIndex = undefined)} + > + (toggleNodeVisibilityLayerPanel(chainNode.id), e?.stopPropagation())} + size={24} + icon={chainNode.visible ? "EyeVisible" : "EyeHidden"} + hoverIcon={chainNode.visible ? "EyeHide" : "EyeShow"} + tooltipLabel={chainNode.visible ? "Hide" : "Show"} + data-drag-toggle-group="layer-visibility" + data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"} + /> + onEditChainNodeName(index, chainNode.id)}> + onEditChainNodeNameDeselect(chainNode)} + on:keydown={(e) => { + if (e.key === "Escape") onEditChainNodeNameDeselect(chainNode); + else if (e.key === "Enter") onEditChainNodeNameChange(chainNode.id, e); + }} + on:change={(e) => onEditChainNodeNameChange(chainNode.id, e)} + /> + + + {#if chainDropRowIndex === index && chainRowInsertMarker?.nodeIndex === slot.nodeIndex} +
+ {/if} +
+ {/each} + {/if} {/if} {/each} +
{#if draggingData && !draggingData.highlightFolder && dragInPanel}
{/if}
- + @@ -1297,11 +1542,18 @@ padding-top: 4px; // Combine with the bottom bar to avoid a double border margin-bottom: -1px; + // The browser would otherwise shift the scroll position to make up for the padding that stands in for unrendered rows changing as they're rendered + overflow-anchor: none; &.drag-ongoing .layer { pointer-events: none; } + .unrendered-rows, + .layer-placeholder { + flex: 0 0 auto; + } + .layer { flex: 0 0 auto; align-items: center; @@ -1328,11 +1580,15 @@ background: rgb(from var(--color-4-dimgray) r g b / 0.5); } + // Spanning the insertion line beside the layer (past the visibility column and the indent), plus its own thickness outward so it clears the icons at both ends &.insert-folder::after { + --outline-thickness: 3px; content: ""; position: absolute; inset: 0; - border: 3px solid var(--color-e-nearwhite); + left: calc(24px + var(--layer-indent-levels) * 16px - var(--outline-thickness)); + right: calc(-1 * var(--outline-thickness)); + border: var(--outline-thickness) solid var(--color-e-nearwhite); border-radius: 2px; pointer-events: none; } @@ -1411,7 +1667,7 @@ } // The name (and lock) and the chain split the rest of the row evenly, except that either gives the other whatever share it doesn't need. - // Between them, the spacer keeps an unrelated-width gap. The right margin keeps the layer icon 4px from the row's end like the visibility icon at its start. + // Between them, the spacer keeps an unrelated-width gap. .layer-name-and-chain { flex: 1 1 0; min-width: 0; @@ -1419,7 +1675,6 @@ display: grid; grid-template-columns: minmax(0, max-content) auto minmax(4px, 1fr) minmax(0, var(--chain-width)); align-items: center; - margin-right: 2px; // While renaming, the name takes all the room its text needs, which the chain gives up until it disappears &.editing { @@ -1691,10 +1946,10 @@ margin: 0 8px; } - // At the row's end, past the layer icon's margin and the row's margin + // At the row's end, past a margin like the layer icon's .chain-node-icon { margin-left: auto; - margin-right: calc(2px + 2px); + margin-right: 2px; // Outlined like the layer icon when the active tool edits it &.tool-target, diff --git a/frontend/src/components/views/Graph.svelte b/frontend/src/components/views/Graph.svelte index 1bc6733c6e..be2838f04b 100644 --- a/frontend/src/components/views/Graph.svelte +++ b/frontend/src/components/views/Graph.svelte @@ -27,6 +27,8 @@ const nodeGraphImportsExports = nodeGraph.importsExportsStore; const visibleNodes = nodeGraph.visibleNodesStore; const nodeGraphWires = nodeGraph.wiresStore; + const wireInsertionPreview = nodeGraph.wireInsertionPreviewStore; + const nodeGlideOffsets = nodeGraph.glideOffsetsStore; const documentState = getContext("document"); const subscriptions = getContext("subscriptions"); @@ -38,6 +40,22 @@ let inputElement: HTMLInputElement; + // Whether a pointer button is held, in which case a drag may be underway and hover hints would only get in the way + let pointerHeld = false; + + let graph: HTMLDivElement | undefined; + + // The connector the wire being dragged comes from, which stays undimmed, and the one it has snapped onto, which looks hovered + let wireSourceConnector: Element | undefined; + let wireTargetConnector: Element | undefined; + let wireEndsMarked = ""; + $: markWireEndConnectors($nodeGraph.wireInProgressDraggedFrom, $nodeGraph.wireInProgressSnappedTo); + + // The connector a press at the pointer would grab, as the backend decides since it knows the click targets + let hoveredConnector: Element | undefined; + let hoveredConnectorMarked = ""; + $: markHoveredConnector($nodeGraph.hoveredConnector); + // The import, export, or layer with its name being edited in place, and the name the field started with type NameTarget = { kind: "Import" | "Export"; index: number } | { kind: "Layer"; nodeId: bigint }; let editingName: (NameTarget & { initialText: string }) | undefined = undefined; @@ -58,13 +76,12 @@ editingName = undefined; if (!target || editingNameText === target.initialText) return; - if (target.kind === "Layer") editor.setLayerName(target.nodeId, editingNameText); + if (target.kind === "Layer") editor.setLayerNameInGraph(target.nodeId, editingNameText); else if (target.kind === "Import") editor.setImportName(target.index, editingNameText); else editor.setExportName(target.index, editingNameText); } - // The name fields stop propagation of the keys they handle so the global keyboard forwarder (`shouldRedirectKeyboardEventToBackend`) doesn't also dispatch them. - // Its Escape carve-out would otherwise close the graph view, and Enter could trigger unrelated bindings. + // The name fields stop propagation of the keys they handle so no window listener also acts on them function onNameInputKeyDown(e: KeyboardEvent) { if (e.key === "Enter") commitEditingName(); else if (e.key === "Escape") editingName = undefined; @@ -123,16 +140,76 @@ if (commandKey && e.key === "Enter") closeDescriptionPopover(); } + // Finds the connectors at the wire's ends, which only change when the wire snaps onto or off of one + function markWireEndConnectors(draggedFrom: [number, number] | undefined, snappedTo: [number, number] | undefined) { + const ends = JSON.stringify([draggedFrom, snappedTo]); + if (ends === wireEndsMarked) return; + wireEndsMarked = ends; + + wireSourceConnector?.classList.remove("wire-source"); + wireTargetConnector?.classList.remove("wire-target"); + + wireSourceConnector = connectorAt(draggedFrom); + wireTargetConnector = connectorAt(snappedTo); + + wireSourceConnector?.classList.add("wire-source"); + wireTargetConnector?.classList.add("wire-target"); + } + + // The backend picks the hovered connector, so it lights up anywhere in its click target rather than just over its drawn arrow + function markHoveredConnector(center: [number, number] | undefined) { + const marked = JSON.stringify(center); + if (marked === hoveredConnectorMarked) return; + hoveredConnectorMarked = marked; + + hoveredConnector?.classList.remove("hovered"); + hoveredConnector = connectorAt(center); + hoveredConnector?.classList.add("hovered"); + } + + // The connector drawn at a point in node graph space, which can sit a few pixels from where its wires attach + function connectorAt(point: [number, number] | undefined): Element | undefined { + if (!graph || !point) return undefined; + + const graphBounds = graph.getBoundingClientRect(); + const { x, y, scale } = $nodeGraphTransform; + return Array.from(graph.querySelectorAll("[data-connector]")).find((connector) => { + const bounds = connector.getBoundingClientRect(); + const centerX = (bounds.left + bounds.width / 2 - graphBounds.left - x) / scale; + const centerY = (bounds.top + bounds.height / 2 - graphBounds.top - y) / scale; + return Math.abs(centerX - point[0]) <= 4 && Math.abs(centerY - point[1]) <= 4; + }); + } + + function onWindowPointerDown() { + pointerHeld = true; + } + + function onWindowPointerUp() { + pointerHeld = false; + } + onMount(() => { // Backend dispatches this when the user double-clicks a layer's name area subscriptions.subscribeFrontendMessage("TriggerEditLayerNameInGraph", (data) => { const node = $nodeGraph.nodes.get(data.nodeId); if (node) startEditingName({ kind: "Layer", nodeId: data.nodeId }, node.displayName); }); + + // Capturing so the state follows the pointer even where another handler stops the event + window.addEventListener("pointerdown", onWindowPointerDown, true); + window.addEventListener("pointerup", onWindowPointerUp, true); + window.addEventListener("pointercancel", onWindowPointerUp, true); + window.addEventListener("blur", onWindowPointerUp); }); onDestroy(() => { subscriptions.unsubscribeFrontendMessage("TriggerEditLayerNameInGraph"); + + window.removeEventListener("pointerdown", onWindowPointerDown, true); + window.removeEventListener("pointerup", onWindowPointerUp, true); + window.removeEventListener("pointercancel", onWindowPointerUp, true); + window.removeEventListener("blur", onWindowPointerUp); }); function calculateGridSpacing(scale: number): number { @@ -198,6 +275,17 @@ return `M-2,-2 L${nodeWidth + 2},-2 L${nodeWidth + 2},${nodeHeight + 2} L-2,${nodeHeight + 2}z ${rectangles.join(" ")}`; } + // Whether the wire feeding an input is the one a dragged node would be inserted onto if dropped now + function isInsertionPreview(preview: [bigint, number] | undefined, nodeId: bigint, inputIndex: number): boolean { + return preview !== undefined && preview[0] === nodeId && preview[1] === inputIndex; + } + + // Whatever is gliding into the place it moved to is drawn short of that place, by this many grid cells along the axis. + // It shifts the position rather than transforming, since a transform would trap a layer's connectors beneath the wires drawn after it. + function glideCells(offset: [number, number] | undefined, axis: 0 | 1): number { + return (offset?.[axis] || 0) / GRID_SIZE; + } + function nodeNameTooltipLabel(node: FrontendNode): string { return node.displayName === node.implementationName ? node.displayName : `${node.implementationName} (${node.displayName})`; } @@ -242,7 +330,7 @@ } -
+
{/if} - {#if isImport} - { - editor.addImportPassthrough(index); - closeContextMenu(); - }} - flush={true} - /> - {/if} { @@ -421,14 +499,19 @@ {/if} - {#if $nodeGraph.error} + {#if $nodeGraph.errors.length > 0}
- - {$nodeGraph.error.error} - - - {$nodeGraph.error.error} - + {#each $nodeGraph.errors as error} + {@const glideOffset = $nodeGlideOffsets.nodes.get(error.nodeId)} + {@const left = `${error.position[0] + (glideOffset?.[0] || 0)}px`} + {@const top = `${error.position[1] + (glideOffset?.[1] || 0)}px`} + + {error.error} + + + {error.error} + + {/each}
{/if} @@ -459,10 +542,10 @@
- {#each $nodeGraphWires.values() as map} - {#each map.values() as { pathString, centerPathString, dataType, thick, dashed }} + {#each $nodeGraphWires.entries() as [nodeId, map]} + {#each map.entries() as [inputIndex, { pathString, centerPathString, dataType, thick, dashed }]} {#if thick} - + {#if frontendOutput.connected} @@ -508,8 +591,8 @@ class="edit-import-export import" class:separator-bottom={index === 0 && $nodeGraphImportsExports.addImportExport} class:separator-top={index === 1 && $nodeGraphImportsExports.addImportExport} - style:--offset-left={($nodeGraphImportsExports.importPosition[0] - 8) / 24} - style:--offset-top={($nodeGraphImportsExports.importPosition[1] - 8) / 24 + importExportRowOffset(index)} + style:--offset-left={($nodeGraphImportsExports.importPosition[0] - 8) / 24 + glideCells($nodeGlideOffsets.imports, 0)} + style:--offset-top={($nodeGraphImportsExports.importPosition[1] - 8) / 24 + glideCells($nodeGlideOffsets.imports, 1) + importExportRowOffset(index)} > {#if editingName?.kind === "Import" && editingName.index === index} {/if} {/each} @@ -561,8 +646,8 @@ data-datatype={frontendInput.dataType} style:--data-color={`var(--color-data-${frontendInput.dataType.toLowerCase()})`} style:--data-color-dim={`var(--color-data-${frontendInput.dataType.toLowerCase()}-dim)`} - style:--offset-left={($nodeGraphImportsExports.exportPosition[0] - 8) / 24} - style:--offset-top={($nodeGraphImportsExports.exportPosition[1] - 8) / 24 + importExportRowOffset(index)} + style:--offset-left={($nodeGraphImportsExports.exportPosition[0] - 8) / 24 + glideCells($nodeGlideOffsets.exports, 0)} + style:--offset-top={($nodeGraphImportsExports.exportPosition[1] - 8) / 24 + glideCells($nodeGlideOffsets.exports, 1) + importExportRowOffset(index)} > {#if frontendInput.connected} @@ -574,8 +659,8 @@ class="edit-import-export export" class:separator-bottom={index === 0 && $nodeGraphImportsExports.addImportExport} class:separator-top={index === 1 && $nodeGraphImportsExports.addImportExport} - style:--offset-left={($nodeGraphImportsExports.exportPosition[0] - 8) / 24} - style:--offset-top={($nodeGraphImportsExports.exportPosition[1] - 8) / 24 + importExportRowOffset(index)} + style:--offset-left={($nodeGraphImportsExports.exportPosition[0] - 8) / 24 + glideCells($nodeGlideOffsets.exports, 0)} + style:--offset-top={($nodeGraphImportsExports.exportPosition[1] - 8) / 24 + glideCells($nodeGlideOffsets.exports, 1) + importExportRowOffset(index)} > {#if editingName?.kind === "Export" && editingName.index === index} - + {/if} {/each} @@ -627,10 +714,15 @@ data-connector="output" data-tooltip-label="Add Import" data-tooltip-description="Drag a wire from here and connect it to an input, or drop one here from an input." - style:--offset-left={($nodeGraphImportsExports.importPosition[0] - 8) / 24} - style:--offset-top={($nodeGraphImportsExports.importPosition[1] - 8) / 24 + importExportRowOffset($nodeGraphImportsExports.imports.length) + 1} + style:--data-color="var(--color-data-general)" + style:--data-color-dim="var(--color-data-general-dim)" + style:--offset-left={($nodeGraphImportsExports.importPosition[0] - 8) / 24 + glideCells($nodeGlideOffsets.imports, 0)} + style:--offset-top={($nodeGraphImportsExports.importPosition[1] - 8) / 24 + + glideCells($nodeGlideOffsets.imports, 1) + + importExportRowOffset($nodeGraphImportsExports.imports.length) + + 1} > - + - + {/if} @@ -651,7 +748,11 @@ x: Number($nodeGraphImportsExports.importPosition[0]), y: Number($nodeGraphImportsExports.importPosition[1]) + reorderLineTop(Number($nodeGraph.reorderImportIndex)), }} -
+
{/if} {#if $nodeGraph.reorderExportIndex !== undefined} @@ -659,7 +760,11 @@ x: Number($nodeGraphImportsExports.exportPosition[0]), y: Number($nodeGraphImportsExports.exportPosition[1]) + reorderLineTop(Number($nodeGraph.reorderExportIndex)), }} -
+
{/if} {/if}
@@ -683,8 +788,8 @@ class:previewed={node.previewed} class:disabled={!node.visible} class:locked={node.locked} - style:--offset-left={node.position?.[0] || 0} - style:--offset-top={node.position?.[1] || 0} + style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)} + style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)} style:--clip-path-id={`url(#${clipPathId})`} style:--data-color={`var(--color-data-${(node.primaryOutput?.dataType || "General").toLowerCase()})`} style:--data-color-dim={`var(--color-data-${(node.primaryOutput?.dataType || "General").toLowerCase()}-dim)`} @@ -715,6 +820,7 @@ {#if node.primaryOutputConnectedToLayer} @@ -740,6 +846,7 @@ {#if node.primaryInputConnectedToLayer} @@ -827,10 +934,10 @@
- {#each $nodeGraphWires.values() as map} - {#each map.values() as { pathString, dataType, thick, dashed, isList }} + {#each $nodeGraphWires.entries() as [nodeId, map]} + {#each map.entries() as [inputIndex, { pathString, dataType, thick, dashed, isList }]} {#if !thick} - + {#if isList} {#each Array.from($nodeGraph.nodes) - .filter(([nodeId, node]) => !node.isLayer && $visibleNodes.has(nodeId)) + .filter(([nodeId, node]) => !node.isLayer && !node.isRedirectDot && $visibleNodes.has(nodeId)) .map(([_, node]) => node) as node (node.id)} {@const exposedInputsOutputs = zipWithUndefined(node.exposedInputs, node.exposedOutputs)} {@const clipPathId = String(Math.random()).substring(2)} @@ -879,8 +986,8 @@ class:selected={$nodeGraph.selected.includes(node.id)} class:previewed={node.previewed} class:disabled={!node.visible} - style:--offset-left={node.position?.[0] || 0} - style:--offset-top={node.position?.[1] || 0} + style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)} + style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)} style:--clip-path-id={`url(#${clipPathId})`} style:--data-color={`var(--color-data-${(node.primaryOutput?.dataType || "General").toLowerCase()})`} style:--data-color-dim={`var(--color-data-${(node.primaryOutput?.dataType || "General").toLowerCase()}-dim)`} @@ -1002,6 +1109,36 @@
{/each} + + + {#each Array.from($nodeGraph.nodes) + .filter(([nodeId, node]) => node.isRedirectDot && $visibleNodes.has(nodeId)) + .map(([_, node]) => node) as node (node.id)} +
+ +
+ {#if !node.primaryInput?.connected} +
+ {/if} +
+ +
+ + + +
+ {/each}
@@ -1024,6 +1161,12 @@ flex-direction: row; flex-grow: 1; + // The outline around a hovered connector or redirect dot, set where each one's data type color is + .connector, + .redirect-dot { + --hover-outline-color: var(--data-color-dim); + } + .grid-background { position: absolute; width: 100%; @@ -1214,10 +1357,12 @@ stroke: var(--data-color-dim); stroke-width: var(--data-line-width); stroke-dasharray: var(--data-dasharray); + transition: stroke 0.1s; } - // The previewed node's temporary wire stands out in the bright data color - .dashed path { + // The previewed node's temporary wire stands out in the bright data color, as does the wire a dragged node would be dropped onto + .dashed path, + .undimmed path { stroke: var(--data-color); } } @@ -1527,6 +1672,154 @@ } } + .redirect-dot { + position: absolute; + left: calc(var(--offset-left) * 24px - 15px); + top: calc((var(--offset-top) + 1) * 24px - 8px); + // Matches the dot's click target in the backend, which also covers the port gutters to either side + width: 30px; + height: 16px; + display: flex; + align-items: center; + justify-content: center; + + .zone { + position: absolute; + z-index: 1; + + // Left and middle, where pressing selects the dot and dragging moves it + &.move { + inset: 0; + } + + // Right gutter, matching the output port's click target (a 10px circle centered 10px right of the dot) + &.wire-out { + left: 20px; + top: 3px; + width: 10px; + height: 10px; + border-radius: 50%; + z-index: 2; + } + + // Left gutter of a dot with nothing feeding it, matching the input port's click target there, which pulls a wire out rather than moving the dot + &.wire-in { + left: 0; + top: 3px; + width: 10px; + height: 10px; + border-radius: 50%; + z-index: 2; + } + } + + .dot { + box-sizing: border-box; + width: 10px; + height: 10px; + border-radius: 50%; + background: var(--data-color); + // Faded in on hover + outline: 2px solid transparent; + pointer-events: none; + transition: + transform 0.1s, + background-color 0.1s, + outline-color 0.1s; + + &.unwired { + background: var(--data-color-dim); + } + } + + // The same connector arrow nodes have on their outputs, offered where a new wire can be pulled out + .wire-out-port { + position: absolute; + left: 21px; + top: 4px; + width: 8px; + height: 8px; + overflow: visible; + pointer-events: none; + opacity: 0; + transition: opacity 0.1s; + } + + &.selected .dot { + outline: 2px solid rgb(from var(--color-f-white) r g b / 0.5); + } + + &.previewed .dot { + outline: 1px dashed var(--data-color); + outline-offset: 2px; + } + } + + // Hover hints stay hidden while a pointer button is held, since a drag may be underway, except on the dot being pressed. + // Hovering to select or drag enlarges the dot and rings it. + &:not(.pointer-held) .redirect-dot .zone.move:hover ~ .dot, + .redirect-dot .zone.move:active ~ .dot { + transform: scale(1.3); + outline: 2px solid var(--hover-outline-color); + } + + // Hovering the right gutter instead dims the dot and reveals the connector to pull a wire from + &:not(.pointer-held) .redirect-dot .zone.wire-out:hover ~ .dot { + background-color: var(--data-color-dim); + } + + &:not(.pointer-held) .redirect-dot .zone.wire-out:hover ~ .wire-out-port { + opacity: 1; + } + + // A wire dragged out of the dot keeps showing its connector as hovering the gutter did, and one snapped onto it rings it like a hover + .redirect-dot .dot.wire-source { + background-color: var(--data-color-dim); + + ~ .wire-out-port { + opacity: 1; + } + } + + .redirect-dot .dot.wire-target { + transform: scale(1.3); + outline: 2px solid var(--hover-outline-color); + } + + // Hovering a connector enlarges it and outlines its arrow, like the ring a hovered redirect dot gets + .connector, + .redirect-dot .wire-out-port { + overflow: visible; + + // Enlarged about the arrow's own center, leaving the ends of a thick stack wire drawn within a layer's connector as they are + path { + transform-box: fill-box; + transform-origin: center; + transition: + fill 0.1s, + transform 0.1s; + } + } + + &:not(.pointer-held) .connector.hovered, + .connector.wire-target, + &:not(.pointer-held) .redirect-dot .zone.wire-out:hover ~ .wire-out-port { + // Undimmed if disconnected, with the stroke painted beneath the fill, so only its outer half shows + path:not(.stack-wire-end) { + transform: scale(1.3); + fill: var(--data-color); + stroke: var(--hover-outline-color); + stroke-width: 4px; + stroke-linejoin: round; + paint-order: stroke; + } + } + + // The connector a wire is dragged from stays undimmed, as it was while hovered + .connector.wire-source path:not(.stack-wire-end) { + fill: var(--data-color); + } + .node { flex-direction: column; border-radius: 2px; diff --git a/frontend/src/components/widgets/NodeSection.svelte b/frontend/src/components/widgets/NodeSection.svelte index 14262cebbe..ea9442f641 100644 --- a/frontend/src/components/widgets/NodeSection.svelte +++ b/frontend/src/components/widgets/NodeSection.svelte @@ -16,8 +16,11 @@ export { className as class }; export let classes: Record = {}; + // A node without parameters has nothing to show, so its section stays collapsed with its arrow grayed out, like the Layers panel's + $: expandable = widgetData.layout.length > 0; + // Whether the section is expanded is owned by the backend (persisted per node), so just reflect it here - $: expanded = widgetData.expanded; + $: expanded = widgetData.expanded && expandable; // The sections of the chain feeding one of this node's inputs, which follow its own rows and are shown beneath them $: chainSections = widgetData.layout.flatMap((layoutGroup) => ("NodeSection" in layoutGroup && layoutGroup.NodeSection.outputWire ? [layoutGroup.NodeSection] : [])); @@ -30,6 +33,8 @@ // Like the Layers panel's expand arrows, a modifier key applies the toggle recursively to the sections nested within function toggleExpandedWithModifiers(e: MouseEvent) { + if (!expandable) return; + const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey; editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel); } @@ -45,42 +50,46 @@ "output-wire": Boolean(widgetData.outputWire), "output-wire-list": Boolean(widgetData.outputWire?.isList), "node-reference": widgetData.nodeReference, + "content-wire": Boolean(widgetData.contentWire), + "content-wire-list": Boolean(widgetData.contentWire?.isList), + "content-wire-continues": widgetData.contentWireContinues, collapsed: !expanded, }} styles={{ "--chain-wire-color": widgetData.chainWire && `var(--color-data-${widgetData.chainWire.dataType.toLowerCase()}-dim)`, "--output-wire-color": widgetData.outputWire && `var(--color-data-${widgetData.outputWire.dataType.toLowerCase()}-dim)`, + "--content-wire-color": widgetData.contentWire && `var(--color-data-${widgetData.contentWire.dataType.toLowerCase()}-dim)`, }} data-inspector-reorderable-section={reorderable ? "" : undefined} data-node-id={reorderable ? String(widgetData.id) : undefined} > {#if widgetData.nodeReference} + {#if widgetData.contentWireContinues} +
+ {/if} {#each widgetData.layout as layoutGroup} {#if "Row" in layoutGroup} {/if} {/each} {:else} -
+ {widgetData.name} { - editor.toggleNodeVisibilityLayerPanel(widgetData.id); + editor.toggleNodeVisibilityInspector(widgetData.id); e?.stopPropagation(); }} class={widgetData.visible ? "show-only-on-hover" : ""} /> + {#if reorderable} +
undefined} role="presentation">
+ {/if} {#if expanded} - + {#each widgetData.layout as layoutGroup} {#if "Row" in layoutGroup} @@ -124,7 +136,7 @@ {/each} {#if chainSections.length > 0} - + {#each chainSections as chainSection} {/each} @@ -136,11 +148,32 @@