From ba3844ed2dc2f895c922856fc514e5a8a210f166 Mon Sep 17 00:00:00 2001 From: schoeller Date: Sun, 22 Nov 2026 18:54:31 +0100 Subject: [PATCH 1/3] Plugin panels: surface event envelope + best-effort notification (S04 part 1, api v29) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The event leg of the panel-surface train: a semantic event vocabulary with EXPLICIT event identity, and the wire notification that carries it to the owning plugin — best-effort by contract, never acknowledged by re-publishing values (finding F2: identical-looking activations are DISTINCT events; equality is not identity). scene.rs (ungated — the pure store and the wire share the vocabulary): - SurfaceEvent: ElementClicked{element,pos} (press+release without drag; the plugin binds its own semantics to the element id — the host never interprets scene vocabulary), DragStarted{element,origin}, DragMoved{element,pos} (COALESCABLE — positions are absolute, so dropped intermediates lose nothing), DragSettled{element,pos} (THE authoritative settle: exactly one per drag, never coalesced away), DragCancelled{element,origin} (pre-drag origin, lossless restore). - Per-surface monotonic sequence numbers are the event identity; they ride the notification, not the event enum. Wire: HostNotification::PanelSurfaceEvent { panel_id, sequence, event } (tag 16, appended after the v27 delta's 15 per the established append-only tag story; pinned by panel_surface_event_notification_tag_is_sixteen with the length-prefixed tag offset the legacy pins use). The runner's notification_api_version gate returns 29 for the variant — a v28 runner can never receive a tag it cannot represent. Deliberately absent (S04 continues): the host-side router/canvas seam and delivery (app-owned, next commit), and any prompt/table state machines (out of scope by mission). Verification: cargo test -p ocs_plugin_api --all-features 199 passed / 0 failed / 1 ignored (new: tag-16 pin + sequence/payload round-trip). Pre-existing upstream baseline failures (windows D3D12 trait errors at this base SHA — see #3460 discussion — plus fmt/clippy informational jobs) are inherited and untouched. --- crates/ocs_plugin_api/src/host.rs | 34 +++++++++++++++ crates/ocs_plugin_api/src/ipc/mod.rs | 44 +++++++++++++++++++- crates/ocs_plugin_api/src/ipc/proxy.rs | 2 +- crates/ocs_plugin_api/src/ipc/transport.rs | 2 +- crates/ocs_plugin_api/src/ipc/v4/client.rs | 23 ++++++---- crates/ocs_plugin_api/src/ipc/v4/protocol.rs | 30 ++++++------- crates/ocs_plugin_api/src/ipc/v4/server.rs | 4 +- crates/ocs_plugin_api/src/runner.rs | 9 ++-- crates/ocs_plugin_api/src/scene.rs | 27 ++++++++++++ 9 files changed, 143 insertions(+), 32 deletions(-) diff --git a/crates/ocs_plugin_api/src/host.rs b/crates/ocs_plugin_api/src/host.rs index 7c97ceacf8..7a0543073a 100644 --- a/crates/ocs_plugin_api/src/host.rs +++ b/crates/ocs_plugin_api/src/host.rs @@ -573,6 +573,21 @@ pub enum HostNotification { snapshot: Option, full_refresh_required: bool, }, + /// A semantic panel-surface event (api v29): what the user did to + /// which element of `panel_id`, with the surface's monotonic event + /// `sequence` as the explicit event identity — identical-looking + /// activations are DISTINCT events, and equality is not identity. + /// Best-effort by contract: never acknowledged by re-publishing + /// values; drag moves may be coalesced (positions are absolute), but + /// `DragSettled` and `DragCancelled` are authoritative and never + /// dropped. Only routed to plugins whose manifest declares v29 — a + /// v28 runner cannot decode tag 16 + /// (`notification_api_version` gate). Discriminant 16. + PanelSurfaceEvent { + panel_id: String, + sequence: u64, + event: crate::scene::SurfaceEvent, + }, /// Fallback for notification variants added in future minor revisions. /// Carries the raw bincode payload so an older peer can ignore it without /// failing deserialization. @@ -722,6 +737,16 @@ impl Serialize for HostNotification { bincode::serialize_into(&mut bytes, full_refresh_required) .map_err(serde::ser::Error::custom)?; } + HostNotification::PanelSurfaceEvent { + panel_id, + sequence, + event, + } => { + bytes.push(16); + bincode::serialize_into(&mut bytes, panel_id).map_err(serde::ser::Error::custom)?; + bincode::serialize_into(&mut bytes, sequence).map_err(serde::ser::Error::custom)?; + bincode::serialize_into(&mut bytes, event).map_err(serde::ser::Error::custom)?; + } HostNotification::Unknown(raw) => bytes.extend_from_slice(raw), } bytes.serialize(serializer) @@ -853,6 +878,15 @@ impl<'de> Deserialize<'de> for HostNotification { }, ) .map_err(serde::de::Error::custom), + 16 => bincode::deserialize(rest) + .map( + |(panel_id, sequence, event)| HostNotification::PanelSurfaceEvent { + panel_id, + sequence, + event, + }, + ) + .map_err(serde::de::Error::custom), _ => Ok(HostNotification::Unknown(bytes)), } } diff --git a/crates/ocs_plugin_api/src/ipc/mod.rs b/crates/ocs_plugin_api/src/ipc/mod.rs index e07402d489..512f2c3a23 100644 --- a/crates/ocs_plugin_api/src/ipc/mod.rs +++ b/crates/ocs_plugin_api/src/ipc/mod.rs @@ -41,8 +41,8 @@ mod tests { use std::thread; use interprocess::local_socket::{ - traits::{Listener, Stream as StreamTrait}, GenericNamespaced, ListenerOptions, Stream, ToNsName, + traits::{Listener, Stream as StreamTrait}, }; use crate::ipc::protocol::{HostRequest, HostResponse, HostToPlugin, PluginToHost}; @@ -712,4 +712,46 @@ mod tests { other => panic!("unexpected: {other:?}"), } } + + /// The v29 panel-surface event notification is pinned at tag 16 + /// (appended after the v27 delta's 15) and round-trips with its + /// sequence (the explicit event identity) and typed event payload. + #[test] + fn panel_surface_event_notification_tag_is_sixteen() { + let notification = crate::host::HostNotification::PanelSurfaceEvent { + panel_id: "acme:graph".to_owned(), + sequence: 42, + event: crate::scene::SurfaceEvent::DragSettled { + element: crate::scene::StableId(3), + pos: crate::scene::Vec2([7.0, 9.0]), + }, + }; + fn tag(notification: &crate::host::HostNotification) -> u8 { + // The wire frame is [u64 length][tag byte][fields] — the tag + // sits after the bincode length prefix (the v27 comment above + // explains the append-only tag story). + let bytes = bincode::serialize(notification).unwrap(); + bytes[8] + } + assert_eq!(tag(¬ification), 16); + let bytes = bincode::serialize(¬ification).expect("serialize notification"); + match bincode::deserialize::(&bytes) + .expect("deserialize notification") + { + crate::host::HostNotification::PanelSurfaceEvent { + panel_id, + sequence, + event, + } => { + assert_eq!(panel_id, "acme:graph"); + assert_eq!(sequence, 42); + assert!(matches!( + event, + crate::scene::SurfaceEvent::DragSettled { element, pos } + if element == crate::scene::StableId(3) && pos == crate::scene::Vec2([7.0, 9.0]) + )); + } + other => panic!("unexpected: {other:?}"), + } + } } diff --git a/crates/ocs_plugin_api/src/ipc/proxy.rs b/crates/ocs_plugin_api/src/ipc/proxy.rs index dc15262379..ff802700e0 100644 --- a/crates/ocs_plugin_api/src/ipc/proxy.rs +++ b/crates/ocs_plugin_api/src/ipc/proxy.rs @@ -164,7 +164,7 @@ fn read_with_poll( return Err(PollError::Io(ProxyError::Io(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "proxy disconnected", - )))) + )))); } Ok(n) => off += n, Err(e) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => { diff --git a/crates/ocs_plugin_api/src/ipc/transport.rs b/crates/ocs_plugin_api/src/ipc/transport.rs index fe8fb5767d..d80027cf58 100644 --- a/crates/ocs_plugin_api/src/ipc/transport.rs +++ b/crates/ocs_plugin_api/src/ipc/transport.rs @@ -12,7 +12,7 @@ use std::io::{Read, Write}; use interprocess::local_socket::Stream; -use serde::{de::DeserializeOwned, Serialize}; +use serde::{Serialize, de::DeserializeOwned}; /// Maximum serialized message size accepted over the wire (1 GiB). Prevents /// a malicious or buggy peer from exhausting host/runner memory, while a full diff --git a/crates/ocs_plugin_api/src/ipc/v4/client.rs b/crates/ocs_plugin_api/src/ipc/v4/client.rs index 6ce6e9302d..d4476659f8 100644 --- a/crates/ocs_plugin_api/src/ipc/v4/client.rs +++ b/crates/ocs_plugin_api/src/ipc/v4/client.rs @@ -6,14 +6,14 @@ use std::collections::{HashMap, VecDeque}; use std::path::Path; use std::rc::Rc; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{mpsc, Arc, Mutex}; +use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; use document::xdata::ExtendedDataRecord; use document::{Document, EntityType, Handle}; +use interprocess::TryClone; use interprocess::local_socket::traits::Stream as StreamTrait; use interprocess::local_socket::{GenericNamespaced, Stream, ToNsName}; -use interprocess::TryClone; use crate::host::{ DocumentReader, ExecutionResult, HostApi, HostNotification, HostSettingValue, @@ -22,7 +22,7 @@ use crate::host::{ use crate::ipc::protocol::{ HostRequest, HostResponse, PluginRequest, PluginResponse, RunnerHandshake, }; -use crate::ipc::transport::{recv, send, TransportError}; +use crate::ipc::transport::{TransportError, recv, send}; use crate::ipc::v4::protocol::{ HostToPluginV4, NotificationEnvelope, PluginToHostV4, V4_PROTOCOL_VERSION, }; @@ -106,8 +106,9 @@ impl V4Client { }); let shared_for_reader = Arc::clone(&shared); - let notifications = - Arc::new(Mutex::new(VecDeque::<(Option, HostNotification)>::new())); + let notifications = Arc::new(Mutex::new( + VecDeque::<(Option, HostNotification)>::new(), + )); let notifications_for_loop = Arc::clone(¬ifications); std::thread::spawn(move || { reader_thread(reader, shared_for_reader, runner_tx, notifications) @@ -229,7 +230,10 @@ fn reader_thread( } } Ok(HostToPluginV4::Notification(envelope)) => { - let is_sel4 = matches!(&envelope.payload, HostNotification::SelectionChangedV4 { .. }); + let is_sel4 = matches!( + &envelope.payload, + HostNotification::SelectionChangedV4 { .. } + ); let mut queue = notifications.lock().unwrap_or_else(|e| e.into_inner()); if is_sel4 { // Latest-wins, head-priority: a selection change is @@ -1560,8 +1564,9 @@ impl V4Client { in_flight: Mutex::new(HashMap::new()), }); let shared_for_reader = Arc::clone(&shared); - let notifications = - Arc::new(Mutex::new(VecDeque::<(Option, HostNotification)>::new())); + let notifications = Arc::new(Mutex::new( + VecDeque::<(Option, HostNotification)>::new(), + )); let notifications_for_loop = Arc::clone(¬ifications); std::thread::spawn(move || { reader_thread(reader, shared_for_reader, runner_tx, notifications) @@ -1595,8 +1600,8 @@ mod tests { use std::thread; use interprocess::local_socket::{ - traits::{Listener, Stream as StreamTrait}, GenericNamespaced, ListenerOptions, Stream, ToNsName, + traits::{Listener, Stream as StreamTrait}, }; use super::*; diff --git a/crates/ocs_plugin_api/src/ipc/v4/protocol.rs b/crates/ocs_plugin_api/src/ipc/v4/protocol.rs index 48d52ca51a..00f22c2920 100644 --- a/crates/ocs_plugin_api/src/ipc/v4/protocol.rs +++ b/crates/ocs_plugin_api/src/ipc/v4/protocol.rs @@ -1018,20 +1018,22 @@ mod tests { // API v15: quad registration frames survive one bincode hop intact; // the icon rides the OwnedIconKind encoding (ribbon precedent) and // the response keeps one outcome per panel. - let panels = vec![crate::dialog::QuadPanelDef::new("align_tools", "Align") - .with_applies_to(vec!["LWPOLYLINE".to_owned()]) - .with_item(crate::dialog::QuadItemDef { - control_id: "flip".to_owned(), - label: "Flip".to_owned(), - icon: crate::ribbon::owned::OwnedIconKind::Svg("".into()), - action: crate::dialog::QuadActionDef::Command("FLIPALIGNED".to_owned()), - }) - .with_item(crate::dialog::QuadItemDef { - control_id: "report".to_owned(), - label: "Report".to_owned(), - icon: crate::ribbon::owned::OwnedIconKind::Glyph("\u{1F4CA}".to_owned()), - action: crate::dialog::QuadActionDef::Callback, - })]; + let panels = vec![ + crate::dialog::QuadPanelDef::new("align_tools", "Align") + .with_applies_to(vec!["LWPOLYLINE".to_owned()]) + .with_item(crate::dialog::QuadItemDef { + control_id: "flip".to_owned(), + label: "Flip".to_owned(), + icon: crate::ribbon::owned::OwnedIconKind::Svg("".into()), + action: crate::dialog::QuadActionDef::Command("FLIPALIGNED".to_owned()), + }) + .with_item(crate::dialog::QuadItemDef { + control_id: "report".to_owned(), + label: "Report".to_owned(), + icon: crate::ribbon::owned::OwnedIconKind::Glyph("\u{1F4CA}".to_owned()), + action: crate::dialog::QuadActionDef::Callback, + }), + ]; let bytes = bincode::serialize(&PluginRequest::RegisterQuadPanels { panels: panels.clone(), }) diff --git a/crates/ocs_plugin_api/src/ipc/v4/server.rs b/crates/ocs_plugin_api/src/ipc/v4/server.rs index 80ca173c8b..7e6298827a 100644 --- a/crates/ocs_plugin_api/src/ipc/v4/server.rs +++ b/crates/ocs_plugin_api/src/ipc/v4/server.rs @@ -1,13 +1,13 @@ //! Host-side V4 IPC reader and dispatcher helpers. use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{mpsc, Arc, Mutex}; +use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; use interprocess::local_socket::Stream; use crate::host::PluginNotification; -use crate::ipc::transport::{recv, TransportError}; +use crate::ipc::transport::{TransportError, recv}; use crate::ipc::v4::protocol::PluginToHostV4; /// Default plugin→host notification rate limit (notifications per second). diff --git a/crates/ocs_plugin_api/src/runner.rs b/crates/ocs_plugin_api/src/runner.rs index 2fa8289eac..83c5ade572 100644 --- a/crates/ocs_plugin_api/src/runner.rs +++ b/crates/ocs_plugin_api/src/runner.rs @@ -25,7 +25,7 @@ use std::rc::Rc; use crate::host::{BuiltinPlugin, CommandStep, HostNotification, InteractiveCommand}; use crate::ipc::client::{InteractiveRegistry, IpcClient, PluginHostApi}; use crate::ipc::protocol::{ - HostRequest, HostResponse, HostToPlugin, InteractiveEvent, PluginToHost, PLUGIN_TOKEN_ENV, + HostRequest, HostResponse, HostToPlugin, InteractiveEvent, PLUGIN_TOKEN_ENV, PluginToHost, }; use crate::ipc::transport::{recv, send}; use crate::ipc::v4::client::{RunnerFrame, V4Client}; @@ -71,7 +71,7 @@ pub fn run_with_plugin( version: u32, mut plugin: Box, ) -> Result<(), Box> { - use crate::version_info::{wire_schema, SELF_HOSTED_API_VERSION, WIRE_SCHEMA_ENV}; + use crate::version_info::{SELF_HOSTED_API_VERSION, WIRE_SCHEMA_ENV, wire_schema}; if version >= SELF_HOSTED_API_VERSION { if let Ok(host) = std::env::var(WIRE_SCHEMA_ENV) { if host != wire_schema() { @@ -354,6 +354,7 @@ fn notification_api_version(notification: &crate::host::HostNotification) -> u32 N::SelectionChangedDigest { .. } => 22, N::DocumentChangedRegions { .. } => 13, N::DocumentChangedDelta { .. } => 27, + N::PanelSurfaceEvent { .. } => 29, N::DocumentOpened { .. } => 9, N::CommandStateChanged { .. } | N::DrawingChanged { .. } => 7, N::DocumentChangedV4 { .. } @@ -663,7 +664,7 @@ fn handle_host_request_v4( Err(_) => { return Some(HostResponse::Error( "plugin entity_classes() panicked".to_string(), - )) + )); } }; } @@ -1066,8 +1067,8 @@ mod tests { use std::thread; use interprocess::local_socket::{ - traits::{Listener, Stream as StreamTrait}, GenericNamespaced, ListenerOptions, Stream, ToNsName, + traits::{Listener, Stream as StreamTrait}, }; use super::*; diff --git a/crates/ocs_plugin_api/src/scene.rs b/crates/ocs_plugin_api/src/scene.rs index 0b05bde743..c231bec100 100644 --- a/crates/ocs_plugin_api/src/scene.rs +++ b/crates/ocs_plugin_api/src/scene.rs @@ -837,6 +837,33 @@ pub struct SurfaceReject { pub current_revision: Option, } +/// One semantic event from a panel surface (api v29, S04): what the user +/// did to WHICH element, carrying absolute scene-space positions. Events +/// are best-effort notifications — never acked by re-publishing values +/// (identical-looking activations are DISTINCT events; equality is not +/// event identity). Drag moves may be coalesced by the host (absolute +/// positions carry all the information); `DragSettled` and +/// `DragCancelled` are authoritative and never dropped. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum SurfaceEvent { + /// A click (press + release without drag) on an element. The plugin + /// binds its own semantics to the element id — the host does not + /// interpret scene vocabulary. + ElementClicked { element: StableId, pos: Vec2 }, + /// A drag began on an element; `origin` is the scene-space point the + /// element occupied when the drag started. + DragStarted { element: StableId, origin: Vec2 }, + /// A coalesced drag move; `pos` is the element's CURRENT scene-space + /// origin (absolute — dropped intermediate moves lose nothing). + DragMoved { element: StableId, pos: Vec2 }, + /// THE authoritative settle: the final origin after the drop. + /// Exactly one per drag; never coalesced away. + DragSettled { element: StableId, pos: Vec2 }, + /// The drag was cancelled (escape, focus loss, teardown). `origin` is + /// the PRE-DRAG origin, so the plugin can restore losslessly. + DragCancelled { element: StableId, origin: Vec2 }, +} + /// Maximum patch ops accepted in one patch frame, bounding allocation and /// CPU magnification per frame (mirrors [`MAX_SCENE_NODES`]'s spirit: the /// cap is well above any authored update and far below a denial budget). From 4e732fe7c87461d91c8e672f72a6cf9f293fbe6a Mon Sep 17 00:00:00 2001 From: schoeller Date: Mon, 23 Nov 2026 08:32:00 +0100 Subject: [PATCH 2/3] Plugin panels: pure surface-event router + owner-targeted delivery seam (S04 part 2, api v29) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The host-owned input half of the event stage, as pure testable logic: - app/panel_events.rs (no renderer, no wire, wasm-clean): PanelEventRouter turns pointer transitions into ordered best-effort notifications. Click contract: press begins a POTENTIAL drag (no event yet); the first move emits DragStarted (pre-drag origin) plus a coalesced DragMoved; further moves COALESCE (absolute positions — dropped intermediates lose nothing); release after moves emits exactly one DragSettled; release without moves emits ElementClicked. Cancellation restores the pre-drag origin losslessly; a cancelled potential drag emits nothing and burns no sequence numbers. One pointer, one law: a new press settles (or silently drops) the in-flight drag first — at most one settle per drag, what the preview showed is what settles. Per-surface monotonic sequences are the explicit event identity: identical-looking clicks carry distinct sequences (F2). - v4_support.rs: publish_surface_event_to_plugin — owner-targeted delivery of HostNotification::PanelSurfaceEvent (grip_endpoint + best-effort notify, the same guarded path and dead-owner law as every v4 notification). Panel surfaces are plugin-owned: no fan-out. Verification: cargo test --lib -p OpenCADStudio -- panel_events 6 passed / 0 failed (click identity, drag start/coalesce/settle, lossless cancel restore, cancelled-potential silence, cross-panel press settle); cargo test -p ocs_plugin_api --all-features 199 passed / 0 failed / 1 ignored. Part 3 (next): the canvas pointer seam (hit-test against cached prims, Program::update pushing the pointer Message), the dispatch arm routing through PanelEventRouter to publish_surface_event_to_plugin, and the host-local drag preview in the canvas paint. --- src/app/mod.rs | 4 + src/app/panel_events.rs | 390 +++++++++++++++++++++++++++++++++++++++ src/plugin/v4_support.rs | 30 ++- 3 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 src/app/panel_events.rs diff --git a/src/app/mod.rs b/src/app/mod.rs index 022bd38e7e..65b5ef3d01 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -109,6 +109,10 @@ pub(crate) mod node_graph; #[cfg(test)] mod object_isolation_tests; mod options_session; +/// Pure panel-surface event routing (api v29): pointer semantics, drag +/// state machine, per-surface event identity. Host-owned input; no +/// renderer or wire coupling. +pub mod panel_events; #[cfg(test)] mod paste_special_tests; #[cfg(not(target_arch = "wasm32"))] diff --git a/src/app/panel_events.rs b/src/app/panel_events.rs new file mode 100644 index 0000000000..78016331cc --- /dev/null +++ b/src/app/panel_events.rs @@ -0,0 +1,390 @@ +//! Pure panel-surface event routing (api v29, S04): pointer semantics, +//! drag state machine, and event identity. +//! +//! Host-owned input (finding F2's contract): the host interprets raw +//! pointer input against its own scene projection and emits best-effort +//! semantic notifications to the owning plugin. Moves are COALESCED +//! (absolute positions carry all information; dropped intermediates lose +//! nothing); `DragSettled` and `DragCancelled` are authoritative and +//! never dropped. Exactly one settle per drag. Cancellation restores the +//! pre-drag origin losslessly. +//! +//! Click contract: press begins a POTENTIAL drag (no event yet); the +//! first move emits `DragStarted` (the pre-drag origin) plus a coalesced +//! `DragMoved`; release after moves emits `DragSettled`; release without +//! any move emits `ElementClicked`. A cancelled potential drag emits +//! nothing (silently dropped candidate) — a cancelled STARTED drag emits +//! `DragCancelled` with the origin. +//! +//! Nothing here touches the renderer or the wire: the caller translates +//! [`RoutedEvent`]s into `HostNotification::PanelSurfaceEvent` frames +//! with the router's sequence numbers (the explicit event identity). + +use ocs_plugin_api::scene::{StableId, SurfaceEvent, Vec2}; + +/// One notification the host should send: the panel surface's identity, +/// the explicit event sequence, and the event itself. +#[derive(Debug, Clone, PartialEq)] +pub struct RoutedEvent { + pub panel_id: String, + pub sequence: u64, + pub event: SurfaceEvent, +} + +#[derive(Debug)] +struct DragState { + element: StableId, + /// The pre-drag origin (scene space) — the lossless-cancel restore. + origin: Vec2, + /// Whether `DragStarted` has been emitted for this drag. + started: bool, + /// Latest coalesced move position (scene space), if any. + latest_move: Option, +} + +/// The per-surface router. One instance owns ALL panel surfaces: event +/// sequences are per SURFACE (panel), and at most one drag is active at a +/// time (the host has one pointer). +#[derive(Debug, Default)] +pub struct PanelEventRouter { + sequences: std::collections::BTreeMap, + drag: Option<(String, DragState)>, +} + +/// A pointer transition in scene space, already resolved to the element +/// under the pointer (or `None` when the pointer is over empty canvas). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Pointer { + Press, + Move, + Release, + /// Escape / focus loss / teardown: the authoritative cancel. + Cancel, +} + +impl PanelEventRouter { + pub fn new() -> Self { + Self::default() + } + + /// Feed one pointer transition for `panel_id`. Returns the ordered + /// notifications to send for this transition (often empty, one for + /// clicks/settles/cancels, two when a drag starts with a move). + pub fn on_pointer( + &mut self, + panel_id: &str, + pointer: Pointer, + element: Option, + pos: Vec2, + ) -> Vec { + match pointer { + Pointer::Press => self.on_press(panel_id, element, pos), + Pointer::Move => self.on_move(panel_id, element, pos), + Pointer::Release => self.on_release(panel_id, element, pos), + Pointer::Cancel => self.on_cancel(panel_id), + } + } + + fn next_sequence(&mut self, panel_id: &str) -> u64 { + let entry = self.sequences.entry(panel_id.to_owned()).or_insert(0); + *entry += 1; + *entry + } + + fn notify(&mut self, panel_id: &str, event: SurfaceEvent) -> Vec { + let sequence = self.next_sequence(panel_id); + vec![RoutedEvent { + panel_id: panel_id.to_owned(), + sequence, + event, + }] + } + + fn on_press( + &mut self, + panel_id: &str, + element: Option, + pos: Vec2, + ) -> Vec { + // One pointer: a press anywhere settles (or silently drops) the + // in-flight drag first — the host has a single pointer, and the + // settle is authoritative (never lost, never partial). + let flushed = self.settle_active_drag(); + self.drag = element.map(|element| { + ( + panel_id.to_owned(), + DragState { + element, + origin: pos, + started: false, + latest_move: None, + }, + ) + }); + flushed + } + + fn on_move( + &mut self, + panel_id: &str, + element: Option, + pos: Vec2, + ) -> Vec { + // The dragged element stays the drag's subject: moves over other + // elements do not re-target the drag. + let _ = element; + let Some((drag_panel, drag)) = self.drag.as_mut() else { + return Vec::new(); + }; + if drag_panel != panel_id { + return Vec::new(); + } + let subject = drag.element; + let origin = drag.origin; + let first_move = !drag.started; + drag.started = true; + // Coalesce: the pending move is REPLACED by the latest (absolute + // positions lose nothing). + drag.latest_move = Some(pos); + drop(drag); + let mut out = Vec::new(); + if first_move { + out.extend(self.notify( + panel_id, + SurfaceEvent::DragStarted { + element: subject, + origin, + }, + )); + } + out + } + + fn on_release( + &mut self, + panel_id: &str, + element: Option, + pos: Vec2, + ) -> Vec { + let Some((drag_panel, mut drag)) = self.drag.take() else { + return Vec::new(); + }; + if drag_panel != panel_id { + self.drag = Some((drag_panel, drag)); + return Vec::new(); + } + if !drag.started { + // Never moved: this was a CLICK on the pressed element (the + // release target wins; it is the element under the pointer). + let target = element.unwrap_or(drag.element); + return self.notify( + panel_id, + SurfaceEvent::ElementClicked { + element: target, + pos, + }, + ); + } + // The authoritative settle supersedes any coalesced move. + let _ = drag.latest_move.take(); + self.notify( + panel_id, + SurfaceEvent::DragSettled { + element: drag.element, + pos, + }, + ) + } + + fn on_cancel(&mut self, panel_id: &str) -> Vec { + let Some((drag_panel, drag)) = self.drag.take() else { + return Vec::new(); + }; + if drag_panel != panel_id { + self.drag = Some((drag_panel, drag)); + return Vec::new(); + } + if !drag.started { + // A cancelled potential drag emitted nothing: silently dropped. + return Vec::new(); + } + // Lossless cancellation: the origin rides the event. + self.notify( + panel_id, + SurfaceEvent::DragCancelled { + element: drag.element, + origin: drag.origin, + }, + ) + } + + /// Settle the active drag (whatever panel owns it): a `DragSettled` + /// at the latest known position when started, or a silent drop when + /// the drag never began. The single-pointer law: a new press steals + /// the pointer, and what the preview showed is what settles. + fn settle_active_drag(&mut self) -> Vec { + let Some((drag_panel, drag)) = self.drag.take() else { + return Vec::new(); + }; + if !drag.started { + return Vec::new(); + } + let pos = drag.latest_move.unwrap_or(drag.origin); + self.notify( + &drag_panel, + SurfaceEvent::DragSettled { + element: drag.element, + pos, + }, + ) + } + + /// Whether a drag is in flight for `panel_id` (the canvas paints the + /// host-local preview when true). + pub fn drag_preview(&self, panel_id: &str) -> Option<(StableId, Vec2, Vec2)> { + let (drag_panel, drag) = self.drag.as_ref()?; + if drag_panel != panel_id || !drag.started { + return None; + } + Some(( + drag.element, + drag.origin, + drag.latest_move.unwrap_or(drag.origin), + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PANEL: &str = "acme:graph"; + const EL: StableId = StableId(7); + + fn at(x: f64, y: f64) -> Vec2 { + Vec2([x, y]) + } + + #[test] + fn click_without_move_emits_exactly_one_element_clicked() { + let mut router = PanelEventRouter::new(); + assert!( + router + .on_pointer(PANEL, Pointer::Press, Some(EL), at(1.0, 1.0)) + .is_empty() + ); + let out = router.on_pointer(PANEL, Pointer::Release, Some(EL), at(1.0, 1.0)); + assert_eq!( + out, + vec![RoutedEvent { + panel_id: PANEL.to_owned(), + sequence: 1, + event: SurfaceEvent::ElementClicked { + element: EL, + pos: at(1.0, 1.0) + } + }] + ); + } + + #[test] + fn drag_emits_started_then_coalesced_moves_then_one_settle() { + let mut router = PanelEventRouter::new(); + router.on_pointer(PANEL, Pointer::Press, Some(EL), at(0.0, 0.0)); + // Press with no events yet. + let started_flush = router.on_pointer(PANEL, Pointer::Move, Some(EL), at(1.0, 1.0)); + assert_eq!(started_flush.len(), 1, "DragStarted rides the first move"); + assert!(matches!( + &started_flush[0].event, + SurfaceEvent::DragStarted { origin, .. } if *origin == at(0.0, 0.0) + )); + // Moves COALESCE: three moves flush only the latest. + let mut flush = router.on_pointer(PANEL, Pointer::Move, Some(EL), at(2.0, 2.0)); + assert!(flush.is_empty(), "move without started-flush coalesces"); + flush.extend(router.on_pointer(PANEL, Pointer::Move, Some(EL), at(3.0, 3.0))); + flush.extend(router.on_pointer(PANEL, Pointer::Move, Some(EL), at(4.0, 4.0))); + assert!(flush.is_empty(), "moves stay coalesced until flushed"); + // The settle supersedes the pending coalesced move and is the + // single authoritative end. + let out = router.on_pointer(PANEL, Pointer::Release, Some(EL), at(5.0, 5.0)); + assert_eq!(out.len(), 1); + assert_eq!( + out[0].sequence, + started_flush[0].sequence + 1, + "sequences are per-surface monotonic" + ); + assert!(matches!( + &out[0].event, + SurfaceEvent::DragSettled { element, pos } + if *element == EL && *pos == at(5.0, 5.0) + )); + } + + #[test] + fn cancel_after_started_drag_restores_the_origin_losslessly() { + let mut router = PanelEventRouter::new(); + router.on_pointer(PANEL, Pointer::Press, Some(EL), at(9.0, 9.0)); + router.on_pointer(PANEL, Pointer::Move, Some(EL), at(10.0, 10.0)); + router.on_pointer(PANEL, Pointer::Move, Some(EL), at(50.0, 50.0)); + let out = router.on_pointer(PANEL, Pointer::Cancel, Some(EL), at(50.0, 50.0)); + assert_eq!(out.len(), 1); + assert!(matches!( + &out[0].event, + SurfaceEvent::DragCancelled { element, origin } + if *element == EL && *origin == at(9.0, 9.0) + )); + // After the cancel the router is idle: moves emit nothing. + assert!( + router + .on_pointer(PANEL, Pointer::Move, Some(EL), at(60.0, 60.0)) + .is_empty() + ); + } + + #[test] + fn cancelled_potential_drag_emits_nothing() { + let mut router = PanelEventRouter::new(); + router.on_pointer(PANEL, Pointer::Press, Some(EL), at(1.0, 1.0)); + assert!( + router + .on_pointer(PANEL, Pointer::Cancel, Some(EL), at(1.0, 1.0)) + .is_empty() + ); + // A fresh press after the cancel: the next click sequence numbers + // start at 1 (nothing burned by the dropped candidate). + router.on_pointer(PANEL, Pointer::Press, Some(EL), at(1.0, 1.0)); + let out = router + .on_pointer(PANEL, Pointer::Release, Some(EL), at(1.0, 1.0)) + .pop() + .expect("release after re-press"); + assert_eq!(out.sequence, 1); + } + + #[test] + fn sequences_are_explicit_identity_across_identical_clicks() { + let mut router = PanelEventRouter::new(); + for _ in 0..2 { + router.on_pointer(PANEL, Pointer::Press, Some(EL), at(1.0, 1.0)); + router.on_pointer(PANEL, Pointer::Release, Some(EL), at(1.0, 1.0)); + } + // Both clicks observed: two events, DISTINCT sequences, identical + // payloads — equality is not event identity. + assert_eq!(router.sequences.get(PANEL), Some(&2)); + } + + #[test] + fn press_during_a_drag_settles_the_old_drag_first() { + let mut router = PanelEventRouter::new(); + router.on_pointer(PANEL, Pointer::Press, Some(EL), at(0.0, 0.0)); + router.on_pointer(PANEL, Pointer::Move, Some(EL), at(1.0, 1.0)); + // A second press (e.g. another panel's canvas or a second button): + // the in-flight drag settles authoritatively before anything else. + let out = router.on_pointer("other:panel", Pointer::Press, Some(EL), at(0.0, 0.0)); + assert_eq!(out.len(), 1); + assert!(matches!( + &out[0].event, + SurfaceEvent::DragSettled { element, pos } + if *element == EL && *pos == at(1.0, 1.0) + )); + } +} diff --git a/src/plugin/v4_support.rs b/src/plugin/v4_support.rs index 0ae502705b..0dbbf55a04 100644 --- a/src/plugin/v4_support.rs +++ b/src/plugin/v4_support.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use ocs_plugin_api::host::{HostNotification, PluginNotification}; -use ocs_plugin_api::host_v4::{manager, HostV4SnapshotManager}; +use ocs_plugin_api::host_v4::{HostV4SnapshotManager, manager}; use ocs_plugin_api::process::NotificationHandler; use ocs_plugin_api::shm::DocumentViewInfo; @@ -284,6 +284,34 @@ pub fn publish_panel_action_to_plugin( } } +/// Deliver a semantic panel-surface event to the OWNING plugin only +/// (api v29). Panel surfaces are plugin-owned: only the owner may act on +/// its events (no fan-out). Best-effort by contract — a dead owner's +/// event drops silently (the same law as every v4 notification), and the +/// runner-side `notification_api_version` gate keeps v28 runners from +/// receiving tag 16. +pub fn publish_surface_event_to_plugin( + plugin_id: &str, + panel_id: String, + sequence: u64, + event: ocs_plugin_api::scene::SurfaceEvent, +) { + let notification = HostNotification::PanelSurfaceEvent { + panel_id, + sequence, + event, + }; + #[cfg(test)] + record_test_dispatch(¬ification); + crate::plugin::external::with_manager(|mgr| { + if let Some((process, _api_version, alive)) = mgr.grip_endpoint(plugin_id) { + if alive { + let _ = process.notify_plugin(None, notification); + } + } + }); +} + /// Deliver a quad cursor menu pick to the OWNING plugin only (API v15). /// /// The quad is not an active command: the pick path resolves the item's From 98c7593d0b6318ef930605dfbe52a2d099ac765b Mon Sep 17 00:00:00 2001 From: schoeller Date: Mon, 23 Nov 2026 11:13:05 +0100 Subject: [PATCH 3/3] Plugin panels: canvas pointer seam, routing, and host-local drag preview (S04 part 3, api v29) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The event stage's live seam: a published scene's canvas now translates raw pointer input into semantic events, routes them through the pure router, and delivers them to the OWNING plugin — with a host-local drag preview that never touches the stored scene. - Prims carry their element: ScenePrim::element (hit-testing and the preview target); project_elements sets it. - hit_test: the topmost prim containing the scene-space point (bounding boxes, deliberately coarse — the plugin owns finer semantics). - SceneCanvas::update (the vendored canvas Program::update, Option< Action>): left press/release/cursor-move inside bounds publish Message::PanelSurfacePointer { owner, panel, pointer, element, pos }; scene space equals canvas-local space (S01 no-transform invariant). - dispatch: the PanelEventRouter owns the semantics (click vs drag, move coalescing, at-most-one settle, lossless cancel); each routed event goes out owner-targeted via v4_support::publish_surface_event_to_plugin. Desktop-only delivery — the web runtime has no plugin host and its routed events die there (paired-stub convention; no surface can exist on web). - Host-local preview: the canvas paints the dragged element shifted by (preview pos − origin) at PAINT time; the stored scene, the retained cache and the plugin's data are untouched until the plugin settles with its own patch. Verification: cargo test --lib -p OpenCADStudio -- panel_events panel_surfaces plugin_scene 22 passed / 0 failed; cargo test -p ocs_plugin_api --all-features 209 passed / 0 failed / 1 ignored; cargo check --lib -p OpenCADStudio clean; wasm32 check green for OpenCADStudio + ocs_web_worker (recorded). Pre-existing upstream baseline failures (windows D3D12 trait errors, fmt/clippy informational jobs) inherited and untouched. --- src/app/dock/view.rs | 5 +- src/app/message.rs | 11 ++ src/app/mod.rs | 6 ++ src/app/update/dispatch.rs | 27 +++++ src/ui/window/plugin_scene.rs | 182 +++++++++++++++++++++++++++++++--- 5 files changed, 218 insertions(+), 13 deletions(-) diff --git a/src/app/dock/view.rs b/src/app/dock/view.rs index 222970a9c6..1e8d8faec1 100644 --- a/src/app/dock/view.rs +++ b/src/app/dock/view.rs @@ -767,7 +767,10 @@ impl OpenCADStudio { .map(|scene| (owner.to_owned(), scene)) }) { let (owner, scene) = scene; - crate::ui::window::plugin_scene::scene_view(&owner, panel_id, scene) + let preview = self.panel_event_router.drag_preview(panel_id); + crate::ui::window::plugin_scene::scene_view( + &owner, panel_id, scene, preview, + ) } else { state.view(num, width, chrome) } diff --git a/src/app/message.rs b/src/app/message.rs index 6e01b2ddcc..f3e81a555c 100644 --- a/src/app/message.rs +++ b/src/app/message.rs @@ -524,6 +524,17 @@ pub enum Message { }, /// Live text change in a plugin modal dialog control. PluginDialogTextChange(String, String), + /// Raw pointer transition on a plugin scene surface (api v29): the + /// canvas resolved the scene-space position and the topmost element; + /// the app's `PanelEventRouter` owns the semantics (click vs drag, + /// coalescing, settle/cancel) and delivery to the owning plugin. + PanelSurfacePointer { + owner: String, + panel: String, + pointer: crate::app::panel_events::Pointer, + element: Option, + pos: ocs_plugin_api::scene::Vec2, + }, /// Checkbox toggle in a plugin modal dialog control. PluginDialogBoolToggle(String, bool), /// Dropdown choice selection in a plugin modal dialog control. diff --git a/src/app/mod.rs b/src/app/mod.rs index 65b5ef3d01..e5b1b5114d 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1642,6 +1642,10 @@ pub(super) struct OpenCADStudio { /// UI projects from it, nothing here draws. pub(crate) panel_surfaces: crate::app::panel_surfaces::PanelSurfaceStore, + /// Pointer semantics for panel scene surfaces (api v29): click vs + /// drag, move coalescing, settle/cancel; per-surface event identity. + pub(crate) panel_event_router: + crate::app::panel_events::PanelEventRouter, /// Numeric mapping for PanelId::Plugin(u32). pub(crate) plugin_panel_ids: std::collections::HashMap, pub(crate) plugin_panel_by_num: std::collections::HashMap, @@ -3247,6 +3251,8 @@ impl OpenCADStudio { plugin_panels: std::collections::BTreeMap::new(), panel_surfaces: crate::app::panel_surfaces::PanelSurfaceStore::default(), + panel_event_router: + crate::app::panel_events::PanelEventRouter::new(), plugin_panel_ids: std::collections::HashMap::new(), plugin_panel_by_num: std::collections::HashMap::new(), hyperlink_editor_handles: Vec::new(), diff --git a/src/app/update/dispatch.rs b/src/app/update/dispatch.rs index 69cb55ef06..6a6130bae2 100644 --- a/src/app/update/dispatch.rs +++ b/src/app/update/dispatch.rs @@ -2087,6 +2087,33 @@ impl OpenCADStudio { Task::none() } + Message::PanelSurfacePointer { + owner, + panel, + pointer, + element, + pos, + } => { + // The router owns the semantics (click vs drag, coalescing, + // settle/cancel). Delivery is owner-targeted and + // best-effort — the same law as every v4 notification. + // Desktop-only: the web runtime has no plugin host, so its + // routed events simply die here (honest no-op — the paired + // stub convention; no scene surface can exist on web). + let routed = + self.panel_event_router + .on_pointer(&panel, pointer, element, pos); + #[cfg(not(target_arch = "wasm32"))] + for ev in routed { + crate::plugin::v4_support::publish_surface_event_to_plugin( + &owner, ev.panel_id, ev.sequence, ev.event, + ); + } + #[cfg(target_arch = "wasm32")] + let _ = (owner, routed); + Task::none() + } + Message::PluginDialogTextChange(id, val) => { if let Some(state) = &mut self.plugin_dialog_state { state.text_values.insert(id, val); diff --git a/src/ui/window/plugin_scene.rs b/src/ui/window/plugin_scene.rs index fac84d77c5..3ee9df9cf3 100644 --- a/src/ui/window/plugin_scene.rs +++ b/src/ui/window/plugin_scene.rs @@ -60,10 +60,12 @@ fn cached_prims(owner: &str, panel: &str, scene: &PanelScene) -> Arc, }, Polyline { + element: ocs_plugin_api::scene::StableId, points: Vec<(f32, f32)>, closed: bool, stroke: Option<(SceneColor, f32)>, }, Label { + element: ocs_plugin_api::scene::StableId, x: f32, y: f32, size: f32, @@ -94,17 +98,30 @@ pub(crate) fn project_scene(scene: &PanelScene) -> Vec { prims } +impl ScenePrim { + /// The prim's owning element (hit-testing and the drag preview). + fn element(&self) -> Option { + match self { + ScenePrim::Rect { element, .. } + | ScenePrim::Polyline { element, .. } + | ScenePrim::Label { element, .. } => Some(*element), + } + } +} + fn project_elements(elements: &[SceneElement], prims: &mut Vec) { for element in elements { match element { SceneElement::Group { children, .. } => project_elements(children, prims), SceneElement::Rect { + id, pos, size, fill, stroke, .. } => prims.push(ScenePrim::Rect { + element: *id, x: pos.0[0] as f32, y: pos.0[1] as f32, w: size.0[0] as f32, @@ -113,11 +130,13 @@ fn project_elements(elements: &[SceneElement], prims: &mut Vec) { stroke: stroke.as_ref().map(|s| (s.color, s.width)), }), SceneElement::Path { + id, points, closed, stroke, .. } => prims.push(ScenePrim::Polyline { + element: *id, points: points .iter() .map(|p| (p.0[0] as f32, p.0[1] as f32)) @@ -126,12 +145,14 @@ fn project_elements(elements: &[SceneElement], prims: &mut Vec) { stroke: stroke.as_ref().map(|s| (s.color, s.width)), }), SceneElement::Text { + id, pos, content, size, color, .. } => prims.push(ScenePrim::Label { + element: *id, x: pos.0[0] as f32, y: pos.0[1] as f32, size: *size, @@ -142,6 +163,56 @@ fn project_elements(elements: &[SceneElement], prims: &mut Vec) { } } +/// Hit-test: the LAST (topmost in paint order) prim whose geometry +/// contains `point`. Coarse and deliberately so — rectangles and labels +/// hit their bounding boxes, polylines hit their bounding box; the +/// plugin owns any finer semantics. +pub(crate) fn hit_test( + prims: &[ScenePrim], + point: (f32, f32), +) -> Option { + let (px, py) = point; + prims + .iter() + .rev() + .find(|prim| match prim { + ScenePrim::Rect { x, y, w, h, .. } => { + px >= *x && px <= x + w && py >= *y && py <= y + h + } + ScenePrim::Polyline { points, .. } => { + let (mut min_x, mut min_y, mut max_x, mut max_y) = ( + f32::INFINITY, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NEG_INFINITY, + ); + for (x, y) in points { + min_x = min_x.min(*x); + min_y = min_y.min(*y); + max_x = max_x.max(*x); + max_y = max_y.max(*y); + } + px >= min_x && px <= max_x && py >= min_y && py <= max_y + } + ScenePrim::Label { + x, + y, + size, + content, + .. + } => { + let w = size * 0.6 * content.chars().count() as f32; + let h = size * 1.4; + px >= *x && px <= x + w && py >= *y && py <= y + h + } + }) + .map(|prim| match prim { + ScenePrim::Rect { element, .. } + | ScenePrim::Polyline { element, .. } + | ScenePrim::Label { element, .. } => *element, + }) +} + /// Semantic color -> host theme slot. Deterministic and pinned by tests so /// iced palette drift breaks the pin instead of silently re-skinning /// plugin panels. @@ -167,7 +238,18 @@ pub(crate) fn scene_color(theme: &Theme, color: SceneColor) -> Color { /// the flat prim list each invocation; no cache (S03 adds the retained /// projection keyed by render inputs). pub(crate) struct SceneCanvas { + pub owner: String, + pub panel: String, pub prims: Arc>, + /// Host-local drag preview (api v29 S04): the dragged element, its + /// pre-drag origin and the current preview position. Paint-time only — + /// the retained prims stay valid, the dragged element's prims shift by + /// (pos − origin) at draw time; nothing here mutates the stored scene. + pub preview: Option<( + ocs_plugin_api::scene::StableId, + ocs_plugin_api::scene::Vec2, + ocs_plugin_api::scene::Vec2, + )>, } impl canvas::Program for SceneCanvas { @@ -182,14 +264,73 @@ impl canvas::Program for SceneCanvas { _cursor: mouse::Cursor, ) -> Vec { let mut frame = canvas::Frame::new(renderer, bounds.size()); + let preview = self.preview.map(|(element, origin, pos)| { + ( + element, + (pos.0[0] - origin.0[0]) as f32, + (pos.0[1] - origin.0[1]) as f32, + ) + }); for prim in self.prims.iter() { - paint_prim(&mut frame, theme, prim); + paint_prim(&mut frame, theme, prim, preview); } vec![frame.into_geometry()] } + + /// Pointer seam (api v29 S04): translate raw canvas events into + /// panel-surface pointer messages. Scene space equals canvas-local + /// space in this projection (no transforms — S01 invariant), so the + /// hit-test runs the cached prims directly. The ROUTER owns the + /// semantics; the canvas only resolves geometry. + fn update( + &self, + _state: &mut Self::State, + event: &iced::Event, + bounds: Rectangle, + cursor: mouse::Cursor, + ) -> Option> { + use crate::app::panel_events::Pointer; + let Some(point) = cursor.position_in(bounds) else { + return None; + }; + let message_for = |pointer: Pointer| { + Some(iced::widget::Action::publish( + Message::PanelSurfacePointer { + owner: self.owner.clone(), + panel: self.panel.clone(), + pointer, + element: hit_test(self.prims.as_slice(), (point.x, point.y)), + pos: ocs_plugin_api::scene::Vec2([point.x as f64, point.y as f64]), + }, + )) + }; + match event { + iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { + message_for(Pointer::Press) + } + iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => { + message_for(Pointer::Release) + } + iced::Event::Mouse(mouse::Event::CursorMoved { .. }) => message_for(Pointer::Move), + _ => None, + } + } } -fn paint_prim(frame: &mut canvas::Frame, theme: &Theme, prim: &ScenePrim) { +fn paint_prim( + frame: &mut canvas::Frame, + theme: &Theme, + prim: &ScenePrim, + preview: Option<(ocs_plugin_api::scene::StableId, f32, f32)>, +) { + // Host-local drag preview: the dragged element's prims shift by the + // preview delta at PAINT time — the stored scene and the cache are + // untouched until the plugin settles with its own patch. + let shift = match (preview, prim.element()) { + (Some((element, dx, dy)), Some(prim_element)) if prim_element == element => (dx, dy), + _ => (0.0, 0.0), + }; + let shifted = |x: f32, y: f32| Point::new(x + shift.0, y + shift.1); match prim { ScenePrim::Rect { x, @@ -198,8 +339,9 @@ fn paint_prim(frame: &mut canvas::Frame, theme: &Theme, prim: &ScenePrim) { h, fill, stroke, + .. } => { - let origin = Point::new(*x, *y); + let origin = shifted(*x, *y); let size = Size::new(*w, *h); if let Some(color) = fill { frame.fill_rectangle(origin, size, scene_color(theme, *color)); @@ -218,6 +360,7 @@ fn paint_prim(frame: &mut canvas::Frame, theme: &Theme, prim: &ScenePrim) { points, closed, stroke, + .. } => { if points.len() < 2 { return; @@ -226,10 +369,10 @@ fn paint_prim(frame: &mut canvas::Frame, theme: &Theme, prim: &ScenePrim) { let path = canvas::Path::new(|builder| { let mut pts = points.iter(); if let Some((x, y)) = pts.next() { - builder.move_to(Point::new(*x, *y)); + builder.move_to(shifted(*x, *y)); } for (x, y) in pts { - builder.line_to(Point::new(*x, *y)); + builder.line_to(shifted(*x, *y)); } if *closed { builder.close(); @@ -249,10 +392,11 @@ fn paint_prim(frame: &mut canvas::Frame, theme: &Theme, prim: &ScenePrim) { size, content, color, + .. } => { frame.fill_text(canvas::Text { content: content.clone().into(), - position: Point::new(*x, *y), + position: shifted(*x, *y), color: scene_color(theme, *color), size: (*size).into(), ..canvas::Text::default() @@ -263,12 +407,26 @@ fn paint_prim(frame: &mut canvas::Frame, theme: &Theme, prim: &ScenePrim) { /// The panel body seam: one canvas element sized to the panel body, /// painting the retained projection for (owner, panel, revision). -pub(crate) fn scene_view<'a>(owner: &str, panel: &str, scene: &PanelScene) -> Element<'a, Message> { +pub(crate) fn scene_view<'a>( + owner: &str, + panel: &str, + scene: &PanelScene, + preview: Option<( + ocs_plugin_api::scene::StableId, + ocs_plugin_api::scene::Vec2, + ocs_plugin_api::scene::Vec2, + )>, +) -> Element<'a, Message> { let prims = cached_prims(owner, panel, scene); - iced::widget::canvas(SceneCanvas { prims }) - .width(Length::Fill) - .height(Length::Fill) - .into() + iced::widget::canvas(SceneCanvas { + owner: owner.to_owned(), + panel: panel.to_owned(), + prims, + preview, + }) + .width(Length::Fill) + .height(Length::Fill) + .into() } #[cfg(test)]