diff --git a/Cargo.lock b/Cargo.lock index 8b65d21309..ec31333747 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1283,7 +1283,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1349,9 +1349,8 @@ dependencies = [ [[package]] name = "dpi" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +version = "0.1.1" +source = "git+https://github.com/kevinard/winit?rev=eeaff073f326103c894faa43ad0f4e1d32460bf2#eeaff073f326103c894faa43ad0f4e1d32460bf2" [[package]] name = "editor" @@ -1437,7 +1436,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2811,7 +2810,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2869,7 +2868,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3527,7 +3526,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4959,7 +4958,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.11.0", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5737,7 +5736,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.2", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -6982,7 +6981,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7476,9 +7475,8 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winit" -version = "0.30.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66d4b9ed69c4009f6321f762d6e61ad8a2389cd431b97cb1e146812e9e6c732" +version = "0.30.13" +source = "git+https://github.com/kevinard/winit?rev=eeaff073f326103c894faa43ad0f4e1d32460bf2#eeaff073f326103c894faa43ad0f4e1d32460bf2" dependencies = [ "ahash", "android-activity", diff --git a/Cargo.toml b/Cargo.toml index bfaf6f44e5..9818f94e6c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -263,3 +263,6 @@ useless_conversion = "deny" [workspace.lints.rustdoc] broken_intra_doc_links = "forbid" + +[patch.crates-io] +winit = { git = "https://github.com/kevinard/winit", rev = "eeaff073f326103c894faa43ad0f4e1d32460bf2" } diff --git a/runtime/src/window.rs b/runtime/src/window.rs index 2eb0509882..a811db3806 100644 --- a/runtime/src/window.rs +++ b/runtime/src/window.rs @@ -11,11 +11,15 @@ use crate::futures::futures::channel::oneshot; use crate::task::{self, Task}; pub use raw_window_handle; +/// Optional native drag transport, negotiated offers and bounded byte I/O. +pub mod drag_drop; use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; /// An operation to be performed on some window. pub enum Action { + /// Opt in to native data-device transport for an ordinary window. + EnableDragDrop(Id, oneshot::Sender>), /// Open a new window with some [`Settings`]. Open(Id, Settings, oneshot::Sender), diff --git a/runtime/src/window/drag_drop.rs b/runtime/src/window/drag_drop.rs new file mode 100644 index 0000000000..33c522b3f8 --- /dev/null +++ b/runtime/src/window/drag_drop.rs @@ -0,0 +1,270 @@ +//! Optional native drag transport. No filesystem or application policy lives here. +use crate::futures::futures::{channel::mpsc, future::BoxFuture}; +use crate::{ + core::window::Id, + task::{self, Task}, +}; +use std::{ + any::Any, + fmt, + sync::{Arc, Mutex}, + time::Duration, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// A single action selected for a native drop. +pub enum Action { + /// The destination copies the referenced data. + Copy, + /// The destination moves the referenced data; source cleanup is not implied. + Move, +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +/// Supported native actions. An empty set rejects negotiation. +pub struct Actions { + /// Copy is available. + pub copy: bool, + /// Move is available. + pub move_files: bool, +} + +#[derive(Clone)] +/// Prepared native payload; Debug shows its size without logging its bytes. +pub struct Content { + /// The advertised MIME type. + pub mime: String, + /// Immutable bytes served on a background pipe worker. + pub bytes: Arc<[u8]>, +} +impl fmt::Debug for Content { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Drag content") + .field("mime", &self.mime) + .field("bytes", &self.bytes.len()) + .finish() + } +} + +#[derive(Clone, Debug)] +/// Current state of an incoming offer. It grants no filesystem authority. +pub struct OfferSnapshot { + /// Identity within the native connection, stable through this offer's lifetime. + pub id: u64, + /// Surface-local logical coordinates. Divide by application scale for widgets. + pub position: (f64, f64), + /// Actions advertised by the source. + pub actions: Actions, + /// Latest compositor choice, which must be honored once dropped. + pub selected: Option, + /// Drop has occurred; this remains true through a later Leave. + pub dropped: bool, + /// The pointer has left the receiving surface. + pub left: bool, + /// The offer has ended or was explicitly finished. + pub finished: bool, + /// Actual source on this connection and seat, independently of public MIME data. + pub local_source: Option, +} +#[derive(Clone, Debug)] +/// Latched outgoing-source lifecycle, observable after its origin closes. +pub struct SourceSnapshot { + /// Identity within the native connection. + pub id: u64, + /// Latest negotiated native action. + pub selected: Option, + /// The implicit grab ended in a drop, while completion may still be pending. + pub dropped: bool, + /// The transport ended locally or received native completion/cancellation. + pub finished: bool, + /// The source ended without a successful native completion. + pub cancelled: bool, + /// A payload worker failure, if any. + pub error: Option, +} + +/// Platform adapters implement only native transport and bounded byte I/O. +pub trait Driver: Send + Sync { + /// Retained offers, including dropped offers still awaiting completion. + fn offers(&self) -> Vec; + /// Consume one origin record for each client left-button press, in input + /// dispatch order, even when that press does not start a drag. + fn capture_origin(&self) -> Option; + /// Start from the origin's current implicit grab; return an explicit refusal. + fn start( + &self, + origin: Origin, + contents: Vec, + actions: Actions, + ) -> Result; +} + +/// Exact native input capability, invalidated by release or a newer press. +/// Capture before asynchronous preparation; it cannot borrow a later gesture. +#[derive(Clone)] +pub struct Origin(Arc); +impl Origin { + /// Construct a capability from a platform adapter's opaque origin. + pub fn new(value: impl Any + Send + Sync) -> Self { + Self(Arc::new(value)) + } + /// Inspect an adapter's own origin representation without exposing native handles. + pub fn downcast_ref(&self) -> Option<&T> { + self.0.downcast_ref() + } +} +impl fmt::Debug for Origin { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Native drag origin") + } +} +/// Platform implementation of one negotiated incoming offer. +pub trait OfferDriver: Send + Sync { + /// Fetch latched native state without consuming an event. + fn snapshot(&self) -> OfferSnapshot; + /// Inspect advertised formats without starting a transfer. + fn has_format(&self, mime: &str) -> bool; + /// Set supported/preferred actions before release; None rejects the format. + fn accept( + &self, + mime: Option, + actions: Actions, + preferred: Option, + ) -> Result<(), String>; + /// Read bounded bytes off dispatch; dropping the future cancels its worker. + fn read( + &self, + mime: String, + limit: usize, + deadline: Duration, + ) -> BoxFuture<'static, Result, String>>; + /// Finish a claimed drop, reporting success only after application work commits. + fn finish(&self, success: bool) -> Result<(), String>; +} +/// Platform implementation of an outgoing source; it never deletes referenced files. +pub trait SourceDriver: Send + Sync { + /// Inspect current lifecycle and payload failures. + fn snapshot(&self) -> SourceSnapshot; + /// Stop serving and request native cancellation, independently of accepted work. + /// Local termination is not an acknowledgement from a foreign destination. + fn cancel(&self); +} + +/// Offers retain their native identity and final action across UI rebuilding. +#[derive(Clone)] +pub struct Offer(Arc); +impl Offer { + /// Construct an offer from a platform adapter. + pub fn new(driver: impl OfferDriver + 'static) -> Self { + Self(Arc::new(driver)) + } + /// Fetch the current native lifecycle and final action. + pub fn snapshot(&self) -> OfferSnapshot { + self.0.snapshot() + } + /// Check whether the source advertised this MIME type. + pub fn has_format(&self, mime: &str) -> bool { + self.0.has_format(mime) + } + /// Negotiate hover acceptance. A dropped offer can no longer change actions. + pub fn accept( + &self, + mime: Option, + actions: Actions, + preferred: Option, + ) -> Result<(), String> { + self.0.accept(mime, actions, preferred) + } + /// Read bounded bytes on a worker. Dropping this future cancels that read. + pub fn read( + &self, + mime: String, + limit: usize, + deadline: Duration, + ) -> BoxFuture<'static, Result, String>> { + self.0.read(mime, limit, deadline) + } + /// End a dropped offer; only report success after all accepted work succeeds. + pub fn finish(&self, success: bool) -> Result<(), String> { + self.0.finish(success) + } +} +impl fmt::Debug for Offer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.snapshot().fmt(f) + } +} + +#[derive(Clone)] +/// Outgoing native offering. Keep it and its endpoint notices until completion. +pub struct Source(Arc); +impl Source { + /// Construct a source from a platform adapter. + pub fn new(driver: impl SourceDriver + 'static) -> Self { + Self(Arc::new(driver)) + } + /// Inspect latched completion, cancellation and payload failures. + pub fn snapshot(&self) -> SourceSnapshot { + self.0.snapshot() + } + /// Stop offering data. Receivers own their already accepted application work. + pub fn cancel(&self) { + self.0.cancel(); + } +} +impl fmt::Debug for Source { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.snapshot().fmt(f) + } +} + +/// Notices coalesce. Inspect every retained offer and owned source after waking; +/// Drop/Finish are latched states, never transient messages that motion can erase. +#[derive(Clone)] +pub struct DragDrop { + driver: Arc, + notices: Arc>>>, +} +impl DragDrop { + /// Construct an endpoint and its coalesced notice receiver for a platform adapter. + pub fn new(driver: impl Driver + 'static, notices: mpsc::Receiver<()>) -> Self { + Self { + driver: Arc::new(driver), + notices: Arc::new(Mutex::new(Some(notices))), + } + } + /// Inspect retained incoming offers without consuming their lifecycle. + pub fn offers(&self) -> Vec { + self.driver.offers() + } + /// Consume the origin record for this client left press, including ordinary + /// clicks. None is an expired/overflowed record, never a replacement grab. + pub fn capture_origin(&self) -> Option { + self.driver.capture_origin() + } + /// Start on the currently held origin grab using already prepared payloads. + pub fn start( + &self, + origin: Origin, + contents: Vec, + actions: Actions, + ) -> Result { + self.driver.start(origin, contents, actions) + } + /// Take the endpoint's single coalesced notice stream. Poll state after each wake. + pub fn take_notices(&self) -> Option> { + self.notices + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + } +} +impl fmt::Debug for DragDrop { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Native drag endpoint") + } +} + +/// None means an unsupported backend, closed window, or duplicate endpoint. +pub fn enable(id: Id) -> Task> { + task::oneshot(move |reply| crate::Action::Window(super::Action::EnableDragDrop(id, reply))) +} diff --git a/winit/src/drag_drop.rs b/winit/src/drag_drop.rs new file mode 100644 index 0000000000..0ffa5beece --- /dev/null +++ b/winit/src/drag_drop.rs @@ -0,0 +1,251 @@ +//! Ordinary-window transport adapter; byte I/O is bounded and off dispatch. +use crate::runtime::window::drag_drop as exchange; + +#[cfg(not(all(target_os = "linux", feature = "wayland")))] +pub(crate) fn enable(_: &winit::window::Window) -> Option { + None +} + +#[cfg(all(target_os = "linux", feature = "wayland"))] +pub(crate) fn enable(window: &winit::window::Window) -> Option { + wayland::enable(window) +} + +#[cfg(all(target_os = "linux", feature = "wayland"))] +mod wayland { + use super::*; + use crate::futures::futures::{ + channel::{mpsc, oneshot}, + future::BoxFuture, + }; + use std::{ + sync::{Arc, Mutex}, + time::Duration, + }; + use winit::platform::wayland::{WindowExtWayland, drag_drop as native}; + + fn actions(actions: exchange::Actions) -> native::DragActions { + native::DragActions { + copy: actions.copy, + move_files: actions.move_files, + } + } + fn action(action: exchange::Action) -> native::DragAction { + match action { + exchange::Action::Copy => native::DragAction::Copy, + exchange::Action::Move => native::DragAction::Move, + } + } + fn selected(action: native::DragAction) -> exchange::Action { + match action { + native::DragAction::Copy => exchange::Action::Copy, + native::DragAction::Move => exchange::Action::Move, + } + } + + pub(super) fn enable(window: &winit::window::Window) -> Option { + let (sender, receiver) = mpsc::channel(0); + let sender = Arc::new(Mutex::new(sender)); + let changed: native::Changed = Arc::new(move || { + let _ = sender + .lock() + .unwrap_or_else(|e| e.into_inner()) + .try_send(()); + }); + let endpoint = window.drag_drop(changed.clone())?; + Some(exchange::DragDrop::new( + Driver { endpoint, changed }, + receiver, + )) + } + + struct Driver { + endpoint: native::DragDrop, + changed: native::Changed, + } + impl exchange::Driver for Driver { + fn capture_origin(&self) -> Option { + self.endpoint.capture_origin().map(exchange::Origin::new) + } + fn offers(&self) -> Vec { + let mut offers = self.endpoint.offers(); + offers.sort_by_key(|offer| offer.snapshot().id); + offers + .into_iter() + .map(|offer| exchange::Offer::new(Offer(offer))) + .collect() + } + + fn start( + &self, + origin: exchange::Origin, + contents: Vec, + supported: exchange::Actions, + ) -> Result { + if contents.is_empty() + || contents.len() > 32 + || contents + .iter() + .try_fold(0usize, |size, content| { + size.checked_add(content.bytes.len()) + }) + .is_none_or(|size| size > 16 * 1024 * 1024) + { + return Err("The dragged data is too large or empty".into()); + } + let formats = contents + .iter() + .map(|content| content.mime.clone()) + .collect(); + let shared = Arc::new(Sending { + source: Mutex::new(None), + writes: Mutex::new(Vec::new()), + error: Mutex::new(None), + }); + let sent = shared.clone(); + let changed = self.changed.clone(); + let send: native::SendData = Arc::new(move |mime, fd| { + let Some(content) = contents.iter().find(|content| content.mime == mime) else { + return; + }; + let result_state = sent.clone(); + let changed = changed.clone(); + let result = native::write_pipe( + fd, + content.bytes.clone(), + Duration::from_secs(5), + move |result| { + if let Err(error) = result { + *result_state.error.lock().unwrap() = Some(error.to_string()); + let source = result_state.source.lock().unwrap().clone(); + if let Some(source) = source { + source.cancel(); + } + changed(); + } + }, + ); + match result { + Ok(task) => { + let mut writes = sent.writes.lock().unwrap(); + writes.retain(|write| !write.is_finished()); + writes.push(task); + } + Err(error) => { + *sent.error.lock().unwrap() = Some(error.to_string()); + let source = sent.source.lock().unwrap().clone(); + if let Some(source) = source { + source.cancel(); + } + } + } + }); + let origin = origin + .downcast_ref::() + .ok_or_else(|| "The drag origin belongs to another backend".to_owned())?; + let source = self + .endpoint + .start(origin, formats, actions(supported), send) + .map_err(|e| e.to_string())?; + *shared.source.lock().unwrap() = Some(source.clone()); + Ok(exchange::Source::new(Source { source, shared })) + } + } + + struct Sending { + source: Mutex>, + writes: Mutex>, + error: Mutex>, + } + impl Drop for Sending { + fn drop(&mut self) { + self.writes.get_mut().unwrap().clear(); + } + } + struct Source { + source: native::Source, + shared: Arc, + } + impl exchange::SourceDriver for Source { + fn snapshot(&self) -> exchange::SourceSnapshot { + let state = self.source.snapshot(); + if state.finished { + self.shared.writes.lock().unwrap().clear(); + } + exchange::SourceSnapshot { + id: state.id, + selected: state.selected.map(selected), + dropped: state.dropped, + finished: state.finished, + cancelled: state.cancelled, + error: self.shared.error.lock().unwrap().clone(), + } + } + fn cancel(&self) { + self.source.cancel(); + self.shared.writes.lock().unwrap().clear(); + } + } + impl Drop for Source { + fn drop(&mut self) { + self.source.cancel(); + } + } + + struct Offer(native::Offer); + impl exchange::OfferDriver for Offer { + fn snapshot(&self) -> exchange::OfferSnapshot { + let state = self.0.snapshot(); + exchange::OfferSnapshot { + id: state.id, + position: state.position, + actions: exchange::Actions { + copy: state.actions.copy, + move_files: state.actions.move_files, + }, + selected: state.selected.map(selected), + dropped: state.dropped, + left: state.left, + finished: state.finished, + local_source: state.local_source, + } + } + fn has_format(&self, mime: &str) -> bool { + self.0.has_format(mime) + } + fn accept( + &self, + mime: Option, + supported: exchange::Actions, + preferred: Option, + ) -> Result<(), String> { + self.0 + .accept(mime, actions(supported), preferred.map(action)) + .map_err(|e| e.to_string()) + } + fn read( + &self, + mime: String, + limit: usize, + deadline: Duration, + ) -> BoxFuture<'static, Result, String>> { + let offer = self.0.clone(); + Box::pin(async move { + let (send, receive) = oneshot::channel(); + let fd = offer.receive(mime).map_err(|e| e.to_string())?; + let task = native::read_pipe(fd, limit, deadline, move |result| { + let _ = send.send(result.map_err(|e| e.to_string())); + }) + .map_err(|e| e.to_string())?; + let result = receive + .await + .map_err(|_| "The drag data reader stopped".to_owned())?; + drop(task); + result + }) + } + fn finish(&self, success: bool) -> Result<(), String> { + self.0.finish(success).map_err(|e| e.to_string()) + } + } +} diff --git a/winit/src/lib.rs b/winit/src/lib.rs index 9f48aa8c9a..4e0ee33bd6 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -31,6 +31,7 @@ pub mod conversion; mod error; mod proxy; +mod drag_drop; mod window; pub use clipboard::Clipboard; @@ -1380,6 +1381,10 @@ fn run_action<'a, P, C>( } }, Action::Window(action) => match action { + window::Action::EnableDragDrop(id, reply) => { + let endpoint = window_manager.get_mut(id).and_then(|window| drag_drop::enable(&window.raw)); + let _ = reply.send(endpoint); + } window::Action::Open(id, settings, channel) => { let monitor = window_manager.last_monitor();