Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui_linux: Add wl_data_source support for outbound drags on Wayland (#61947)
Erik Wc7aea6cbbd43
diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rsindex 81ed5b7ef03..3d5f9029aa5 100644--- a/crates/gpui_linux/src/linux/wayland/client.rs+++ b/crates/gpui_linux/src/linux/wayland/client.rs@@ -94,12 +94,12 @@ use crate::linux::{xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},};use gpui::{- AnyWindowHandle, Bounds, Capslock, CursorStyle, DevicePixels, DisplayId, FileDropEvent,- ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent,- MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection,- Pixels, PlatformDisplay, PlatformInput, PlatformKeyboardLayout, PlatformWindow, Point,- ScrollDelta, ScrollWheelEvent, SharedString, Size, TouchPhase, WindowButtonLayout, WindowKind,- WindowParams, point, profiler, px, size,+ AnyWindowHandle, Bounds, Capslock, CursorStyle, DevicePixels, DisplayId, ExternalDragPayload,+ FileDragPaths, FileDropEvent, ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke,+ Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent,+ MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay, PlatformInput,+ PlatformKeyboardLayout, PlatformWindow, Point, ScrollDelta, ScrollWheelEvent, SharedString,+ Size, TouchPhase, WindowButtonLayout, WindowKind, WindowParams, point, profiler, px, size,};use gpui_wgpu::{CompositorGpuHint, GpuContext};use wayland_protocols::wp::linux_dmabuf::zv1::client::{@@ -329,6 +329,7 @@ pub(crate) struct WaylandClientState {keymap_state: Option<xkb::State>,compose_state: Option<xkb::compose::State>,drag: DragState,+ external_drag: Option<ExternalDrag>,click: ClickState,repeat: KeyRepeat,pub modifiers: Modifiers,@@ -364,6 +365,30 @@ pub struct DragState {position: Point<Pixels>,}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum DataSourceKind {+ Clipboard,+ Drag,+}++pub(crate) struct ExternalDrag {+ source: wl_data_source::WlDataSource,+ bytes: Vec<u8>,+ window: WaylandWindowStatePtr,+}++fn file_uri_list(paths: &FileDragPaths) -> String {+ paths+ .entries()+ .iter()+ .filter_map(|(path, _)| Url::from_file_path(path).ok())+ .fold(String::new(), |mut list, url| {+ list.push_str(url.as_str());+ list.push_str("\r\n");+ list+ })+}+pub struct ClickState {last_mouse_button: Option<MouseButton>,last_click: Instant,@@ -415,6 +440,46 @@ impl WaylandClientStatePtr {self.0.upgrade().unwrap().borrow().serial_tracker.get(kind)}+ pub fn start_external_drag(+ &self,+ surface: &wl_surface::WlSurface,+ payload: &ExternalDragPayload,+ ) -> bool {+ let client = self.get_client();+ let mut state = client.borrow_mut();++ let Some(window) = get_window(&mut state, &surface.id()) else {+ return false;+ };++ let (Some(data_device_manager), Some(data_device)) = (+ state.globals.data_device_manager.as_ref(),+ state.data_device.as_ref(),+ ) else {+ return false;+ };++ let ExternalDragPayload::Files(paths) = payload;+ let uri_list = file_uri_list(paths);+ if uri_list.is_empty() {+ return false;+ }++ let serial = state.serial_tracker.get(SerialKind::MousePress);+ let source =+ data_device_manager.create_data_source(&state.globals.qh, DataSourceKind::Drag);+ source.offer(FILE_LIST_MIME_TYPE.to_string());+ source.set_actions(DndAction::Copy | DndAction::Move);+ data_device.start_drag(Some(&source), surface, None, serial.as_raw());++ state.external_drag = Some(ExternalDrag {+ source,+ bytes: uri_list.into_bytes(),+ window,+ });+ true+ }+pub fn set_pending_activation(&self, window: ObjectId) {self.0.upgrade().unwrap().borrow_mut().pending_activation =Some(PendingActivation::Window(window));@@ -802,6 +867,7 @@ impl WaylandClient {window: None,position: Point::default(),},+ external_drag: None,click: ClickState {last_click: Instant::now(),last_mouse_button: None,@@ -1123,7 +1189,8 @@ impl LinuxClient for WaylandClient {);return;};- let data_source = data_device_manager.create_data_source(&state.globals.qh, ());+ let data_source = data_device_manager+ .create_data_source(&state.globals.qh, DataSourceKind::Clipboard);for mime_type in TEXT_MIME_TYPES {data_source.offer(mime_type.to_string());}@@ -2614,25 +2681,45 @@ impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {}}-impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {+impl Dispatch<wl_data_source::WlDataSource, DataSourceKind> for WaylandClientStatePtr {fn event(this: &mut Self,data_source: &wl_data_source::WlDataSource,event: wl_data_source::Event,- _: &(),+ kind: &DataSourceKind,_: &Connection,_: &QueueHandle<Self>,) {let client = this.get_client();- let state = client.borrow_mut();+ let mut state = client.borrow_mut();- match event {- wl_data_source::Event::Send { mime_type, fd } => {+ match (kind, event) {+ (DataSourceKind::Clipboard, wl_data_source::Event::Send { mime_type, fd }) => {state.clipboard.send(mime_type, fd);}- wl_data_source::Event::Cancelled => {+ (DataSourceKind::Clipboard, wl_data_source::Event::Cancelled) => {data_source.destroy();}+ (DataSourceKind::Drag, wl_data_source::Event::Send { fd, .. }) => {+ let Some(external_drag) = state.external_drag.as_ref() else {+ return;+ };+ let bytes = external_drag.bytes.clone();+ state.clipboard.send_bytes(fd, bytes);+ }+ (+ DataSourceKind::Drag,+ wl_data_source::Event::DndFinished | wl_data_source::Event::Cancelled,+ ) => {+ let Some(external_drag) = state.external_drag.take() else {+ return;+ };+ external_drag.source.destroy();++ let input = PlatformInput::FileDrop(FileDropEvent::Ended);+ drop(state);+ external_drag.window.handle_input(input);+ }_ => {}}}@@ -2772,6 +2859,37 @@ mod tests {}}+ #[test]+ fn builds_terminated_uri_list_for_each_dragged_path() {+ let paths = FileDragPaths::new([+ (PathBuf::from("/tmp/first"), false),+ (PathBuf::from("/tmp/nested directory"), true),+ ]);++ assert_eq!(+ file_uri_list(&paths),+ "file:///tmp/first\r\nfile:///tmp/nested%20directory\r\n"+ );+ }++ #[test]+ fn skips_paths_that_have_no_file_url() {+ let paths = FileDragPaths::new([+ (PathBuf::from("relative/path"), false),+ (PathBuf::from("/tmp/absolute"), false),+ ]);++ assert_eq!(file_uri_list(&paths), "file:///tmp/absolute\r\n");+ }++ #[test]+ fn builds_empty_uri_list_without_convertible_paths() {+ assert!(file_uri_list(&FileDragPaths::default()).is_empty());+ assert!(+ file_uri_list(&FileDragPaths::new([(PathBuf::from("relative"), false)])).is_empty()+ );+ }+fn ime_cursor_bounds(x: f32) -> Bounds<Pixels> {Bounds::new(point(px(x), px(20.25)), size(px(1.0), px(18.75)))}diff --git a/crates/gpui_linux/src/linux/wayland/clipboard.rs b/crates/gpui_linux/src/linux/wayland/clipboard.rsindex dfedf53f6df..57ecd9345bf 100644--- a/crates/gpui_linux/src/linux/wayland/clipboard.rs+++ b/crates/gpui_linux/src/linux/wayland/clipboard.rs@@ -182,7 +182,7 @@ impl Clipboard {pub fn send(&self, _mime_type: String, fd: OwnedFd) {if let Some(text) = self.contents.as_ref().and_then(|contents| contents.text()) {- self.send_internal(fd, text.as_bytes().to_owned());+ self.send_bytes(fd, text.as_bytes().to_owned());}}@@ -192,7 +192,7 @@ impl Clipboard {.as_ref().and_then(|contents| contents.text()){- self.send_internal(fd, text.as_bytes().to_owned());+ self.send_bytes(fd, text.as_bytes().to_owned());}}@@ -232,7 +232,7 @@ impl Clipboard {Some(item)}- fn send_internal(&self, fd: OwnedFd, bytes: Vec<u8>) {+ pub fn send_bytes(&self, fd: OwnedFd, bytes: Vec<u8>) {let mut written = 0;self.loop_handle.insert_source(diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rsindex f4372a2dcbd..6e4bd304f2f 100644--- a/crates/gpui_linux/src/linux/wayland/window.rs+++ b/crates/gpui_linux/src/linux/wayland/window.rs@@ -32,11 +32,11 @@ use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_surface_v1;use crate::linux::wayland::{display::WaylandDisplay, serial::SerialKind};use crate::linux::{Globals, Output, WaylandClientStatePtr, get_window};use gpui::{- AnyWindowHandle, Bounds, Capslock, Decorations, DevicePixels, GpuSpecs, Modifiers, Pixels,- PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,- PromptButton, PromptLevel, RequestFrameOptions, ResizeEdge, Scene, Size, Tiling,- WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowControls,- WindowDecorations, WindowKind, WindowParams,+ AnyWindowHandle, Bounds, Capslock, Decorations, DevicePixels, ExternalDragPayload, GpuSpecs,+ Modifiers, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler,+ PlatformWindow, Point, PromptButton, PromptLevel, RequestFrameOptions, ResizeEdge, Scene, Size,+ Tiling, WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea,+ WindowControls, WindowDecorations, WindowKind, WindowParams,layer_shell::{Anchor, LayerShellNotSupportedError},popup::PopupOptions,px, size,@@ -1774,6 +1774,15 @@ impl PlatformWindow for WaylandWindow {}}+ fn can_start_external_drag(&self) -> bool {+ true+ }++ fn start_external_drag(&self, payload: &ExternalDragPayload) -> bool {+ let state = self.borrow();+ state.client.start_external_drag(&state.surface, payload)+ }+fn start_window_resize(&self, edge: gpui::ResizeEdge) {let state = self.borrow();if let Some(toplevel) = state.surface_state.toplevel() {