1use std::{
2 cell::{RefCell, RefMut},
3 hash::Hash,
4 os::fd::{AsRawFd, BorrowedFd},
5 path::PathBuf,
6 rc::{Rc, Weak},
7 time::{Duration, Instant},
8};
9
10use ashpd::WindowIdentifier;
11use calloop::{
12 EventLoop, LoopHandle,
13 timer::{TimeoutAction, Timer},
14};
15use calloop_wayland_source::WaylandSource;
16use collections::HashMap;
17use filedescriptor::Pipe;
18use http_client::Url;
19use smallvec::SmallVec;
20use util::ResultExt as _;
21use wayland_backend::client::ObjectId;
22use wayland_backend::protocol::WEnum;
23use wayland_client::event_created_child;
24use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init};
25use wayland_client::protocol::wl_callback::{self, WlCallback};
26use wayland_client::protocol::wl_data_device_manager::DndAction;
27use wayland_client::protocol::wl_data_offer::WlDataOffer;
28use wayland_client::protocol::wl_pointer::AxisSource;
29use wayland_client::protocol::{
30 wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_output, wl_region,
31};
32use wayland_client::{
33 Connection, Dispatch, Proxy, QueueHandle, delegate_noop,
34 protocol::{
35 wl_buffer, wl_compositor, wl_keyboard, wl_pointer, wl_registry, wl_seat, wl_shm,
36 wl_shm_pool, wl_surface,
37 },
38};
39use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::{
40 self, ZwpPrimarySelectionOfferV1,
41};
42use wayland_protocols::wp::primary_selection::zv1::client::{
43 zwp_primary_selection_device_manager_v1, zwp_primary_selection_device_v1,
44 zwp_primary_selection_source_v1,
45};
46use wayland_protocols::wp::text_input::zv3::client::zwp_text_input_v3::{
47 ContentHint, ContentPurpose,
48};
49use wayland_protocols::wp::text_input::zv3::client::{
50 zwp_text_input_manager_v3, zwp_text_input_v3,
51};
52use wayland_protocols::wp::viewporter::client::{wp_viewport, wp_viewporter};
53use wayland_protocols::xdg::activation::v1::client::{xdg_activation_token_v1, xdg_activation_v1};
54use wayland_protocols::xdg::decoration::zv1::client::{
55 zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1,
56};
57use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base};
58use wayland_protocols::{
59 wp::cursor_shape::v1::client::{wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1},
60 xdg::dialog::v1::client::xdg_wm_dialog_v1::{self, XdgWmDialogV1},
61};
62use wayland_protocols::{
63 wp::fractional_scale::v1::client::{wp_fractional_scale_manager_v1, wp_fractional_scale_v1},
64 xdg::dialog::v1::client::xdg_dialog_v1::XdgDialogV1,
65};
66use wayland_protocols_plasma::blur::client::{org_kde_kwin_blur, org_kde_kwin_blur_manager};
67use wayland_protocols_wlr::layer_shell::v1::client::{zwlr_layer_shell_v1, zwlr_layer_surface_v1};
68use xkbcommon::xkb::ffi::XKB_KEYMAP_FORMAT_TEXT_V1;
69use xkbcommon::xkb::{self, KEYMAP_COMPILE_NO_FLAGS, Keycode};
70
71use super::{
72 display::WaylandDisplay,
73 window::{ImeInput, WaylandWindowStatePtr},
74};
75
76use crate::{
77 AnyWindowHandle, Bounds, Capslock, CursorStyle, DOUBLE_CLICK_INTERVAL, DevicePixels, DisplayId,
78 FileDropEvent, ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, LinuxCommon,
79 LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
80 MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay,
81 PlatformInput, PlatformKeyboardLayout, Point, ResultExt as _, SCROLL_LINES, ScrollDelta,
82 ScrollWheelEvent, Size, TouchPhase, WindowParams, point, profiler, px, size,
83};
84use crate::{
85 RunnableVariant, TaskTiming,
86 platform::{PlatformWindow, blade::BladeContext},
87};
88use crate::{
89 SharedString,
90 platform::linux::{
91 LinuxClient, get_xkb_compose_state, is_within_click_distance, open_uri_internal, read_fd,
92 reveal_path_internal,
93 wayland::{
94 clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPES},
95 cursor::Cursor,
96 serial::{SerialKind, SerialTracker},
97 window::WaylandWindow,
98 },
99 xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
100 },
101};
102
103/// Used to convert evdev scancode to xkb scancode
104const MIN_KEYCODE: u32 = 8;
105
106const UNKNOWN_KEYBOARD_LAYOUT_NAME: SharedString = SharedString::new_static("unknown");
107
108#[derive(Clone)]
109pub struct Globals {
110 pub qh: QueueHandle<WaylandClientStatePtr>,
111 pub activation: Option<xdg_activation_v1::XdgActivationV1>,
112 pub compositor: wl_compositor::WlCompositor,
113 pub cursor_shape_manager: Option<wp_cursor_shape_manager_v1::WpCursorShapeManagerV1>,
114 pub data_device_manager: Option<wl_data_device_manager::WlDataDeviceManager>,
115 pub primary_selection_manager:
116 Option<zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1>,
117 pub wm_base: xdg_wm_base::XdgWmBase,
118 pub shm: wl_shm::WlShm,
119 pub seat: wl_seat::WlSeat,
120 pub viewporter: Option<wp_viewporter::WpViewporter>,
121 pub fractional_scale_manager:
122 Option<wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1>,
123 pub decoration_manager: Option<zxdg_decoration_manager_v1::ZxdgDecorationManagerV1>,
124 pub layer_shell: Option<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
125 pub blur_manager: Option<org_kde_kwin_blur_manager::OrgKdeKwinBlurManager>,
126 pub text_input_manager: Option<zwp_text_input_manager_v3::ZwpTextInputManagerV3>,
127 pub dialog: Option<xdg_wm_dialog_v1::XdgWmDialogV1>,
128 pub executor: ForegroundExecutor,
129}
130
131impl Globals {
132 fn new(
133 globals: GlobalList,
134 executor: ForegroundExecutor,
135 qh: QueueHandle<WaylandClientStatePtr>,
136 seat: wl_seat::WlSeat,
137 ) -> Self {
138 let dialog_v = XdgWmDialogV1::interface().version;
139 Globals {
140 activation: globals.bind(&qh, 1..=1, ()).ok(),
141 compositor: globals
142 .bind(
143 &qh,
144 wl_surface::REQ_SET_BUFFER_SCALE_SINCE
145 ..=wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE,
146 (),
147 )
148 .unwrap(),
149 cursor_shape_manager: globals.bind(&qh, 1..=1, ()).ok(),
150 data_device_manager: globals
151 .bind(
152 &qh,
153 WL_DATA_DEVICE_MANAGER_VERSION..=WL_DATA_DEVICE_MANAGER_VERSION,
154 (),
155 )
156 .ok(),
157 primary_selection_manager: globals.bind(&qh, 1..=1, ()).ok(),
158 shm: globals.bind(&qh, 1..=1, ()).unwrap(),
159 seat,
160 wm_base: globals.bind(&qh, 2..=5, ()).unwrap(),
161 viewporter: globals.bind(&qh, 1..=1, ()).ok(),
162 fractional_scale_manager: globals.bind(&qh, 1..=1, ()).ok(),
163 decoration_manager: globals.bind(&qh, 1..=1, ()).ok(),
164 layer_shell: globals.bind(&qh, 1..=5, ()).ok(),
165 blur_manager: globals.bind(&qh, 1..=1, ()).ok(),
166 text_input_manager: globals.bind(&qh, 1..=1, ()).ok(),
167 dialog: globals.bind(&qh, dialog_v..=dialog_v, ()).ok(),
168 executor,
169 qh,
170 }
171 }
172}
173
174#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
175pub struct InProgressOutput {
176 name: Option<String>,
177 scale: Option<i32>,
178 position: Option<Point<DevicePixels>>,
179 size: Option<Size<DevicePixels>>,
180}
181
182impl InProgressOutput {
183 fn complete(&self) -> Option<Output> {
184 if let Some((position, size)) = self.position.zip(self.size) {
185 let scale = self.scale.unwrap_or(1);
186 Some(Output {
187 name: self.name.clone(),
188 scale,
189 bounds: Bounds::new(position, size),
190 })
191 } else {
192 None
193 }
194 }
195}
196
197#[derive(Debug, Clone, Eq, PartialEq, Hash)]
198pub struct Output {
199 pub name: Option<String>,
200 pub scale: i32,
201 pub bounds: Bounds<DevicePixels>,
202}
203
204pub(crate) struct WaylandClientState {
205 serial_tracker: SerialTracker,
206 globals: Globals,
207 gpu_context: BladeContext,
208 wl_seat: wl_seat::WlSeat, // TODO: Multi seat support
209 wl_pointer: Option<wl_pointer::WlPointer>,
210 wl_keyboard: Option<wl_keyboard::WlKeyboard>,
211 cursor_shape_device: Option<wp_cursor_shape_device_v1::WpCursorShapeDeviceV1>,
212 data_device: Option<wl_data_device::WlDataDevice>,
213 primary_selection: Option<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1>,
214 text_input: Option<zwp_text_input_v3::ZwpTextInputV3>,
215 pre_edit_text: Option<String>,
216 ime_pre_edit: Option<String>,
217 composing: bool,
218 // Surface to Window mapping
219 windows: HashMap<ObjectId, WaylandWindowStatePtr>,
220 // Output to scale mapping
221 outputs: HashMap<ObjectId, Output>,
222 in_progress_outputs: HashMap<ObjectId, InProgressOutput>,
223 keyboard_layout: LinuxKeyboardLayout,
224 keymap_state: Option<xkb::State>,
225 compose_state: Option<xkb::compose::State>,
226 drag: DragState,
227 click: ClickState,
228 repeat: KeyRepeat,
229 pub modifiers: Modifiers,
230 pub capslock: Capslock,
231 axis_source: AxisSource,
232 pub mouse_location: Option<Point<Pixels>>,
233 continuous_scroll_delta: Option<Point<Pixels>>,
234 discrete_scroll_delta: Option<Point<f32>>,
235 vertical_modifier: f32,
236 horizontal_modifier: f32,
237 scroll_event_received: bool,
238 enter_token: Option<()>,
239 button_pressed: Option<MouseButton>,
240 mouse_focused_window: Option<WaylandWindowStatePtr>,
241 keyboard_focused_window: Option<WaylandWindowStatePtr>,
242 loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
243 cursor_style: Option<CursorStyle>,
244 clipboard: Clipboard,
245 data_offers: Vec<DataOffer<WlDataOffer>>,
246 primary_data_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
247 cursor: Cursor,
248 pending_activation: Option<PendingActivation>,
249 event_loop: Option<EventLoop<'static, WaylandClientStatePtr>>,
250 common: LinuxCommon,
251}
252
253pub struct DragState {
254 data_offer: Option<wl_data_offer::WlDataOffer>,
255 window: Option<WaylandWindowStatePtr>,
256 position: Point<Pixels>,
257}
258
259pub struct ClickState {
260 last_mouse_button: Option<MouseButton>,
261 last_click: Instant,
262 last_location: Point<Pixels>,
263 current_count: usize,
264}
265
266pub(crate) struct KeyRepeat {
267 characters_per_second: u32,
268 delay: Duration,
269 current_id: u64,
270 current_keycode: Option<xkb::Keycode>,
271}
272
273pub(crate) enum PendingActivation {
274 /// URI to open in the web browser.
275 Uri(String),
276 /// Path to open in the file explorer.
277 Path(PathBuf),
278 /// A window from ourselves to raise.
279 Window(ObjectId),
280}
281
282/// This struct is required to conform to Rust's orphan rules, so we can dispatch on the state but hand the
283/// window to GPUI.
284#[derive(Clone)]
285pub struct WaylandClientStatePtr(Weak<RefCell<WaylandClientState>>);
286
287impl WaylandClientStatePtr {
288 pub fn get_client(&self) -> Rc<RefCell<WaylandClientState>> {
289 self.0
290 .upgrade()
291 .expect("The pointer should always be valid when dispatching in wayland")
292 }
293
294 pub fn get_serial(&self, kind: SerialKind) -> u32 {
295 self.0.upgrade().unwrap().borrow().serial_tracker.get(kind)
296 }
297
298 pub fn set_pending_activation(&self, window: ObjectId) {
299 self.0.upgrade().unwrap().borrow_mut().pending_activation =
300 Some(PendingActivation::Window(window));
301 }
302
303 pub fn enable_ime(&self) {
304 let client = self.get_client();
305 let mut state = client.borrow_mut();
306 let Some(mut text_input) = state.text_input.take() else {
307 return;
308 };
309
310 text_input.enable();
311 text_input.set_content_type(ContentHint::None, ContentPurpose::Normal);
312 if let Some(window) = state.keyboard_focused_window.clone() {
313 drop(state);
314 if let Some(area) = window.get_ime_area() {
315 text_input.set_cursor_rectangle(
316 area.origin.x.0 as i32,
317 area.origin.y.0 as i32,
318 area.size.width.0 as i32,
319 area.size.height.0 as i32,
320 );
321 }
322 state = client.borrow_mut();
323 }
324 text_input.commit();
325 state.text_input = Some(text_input);
326 }
327
328 pub fn disable_ime(&self) {
329 let client = self.get_client();
330 let mut state = client.borrow_mut();
331 state.composing = false;
332 if let Some(text_input) = &state.text_input {
333 text_input.disable();
334 text_input.commit();
335 }
336 }
337
338 pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
339 let client = self.get_client();
340 let mut state = client.borrow_mut();
341 if state.composing || state.text_input.is_none() || state.pre_edit_text.is_some() {
342 return;
343 }
344
345 let text_input = state.text_input.as_ref().unwrap();
346 text_input.set_cursor_rectangle(
347 bounds.origin.x.0 as i32,
348 bounds.origin.y.0 as i32,
349 bounds.size.width.0 as i32,
350 bounds.size.height.0 as i32,
351 );
352 text_input.commit();
353 }
354
355 pub fn handle_keyboard_layout_change(&self) {
356 let client = self.get_client();
357 let mut state = client.borrow_mut();
358 let changed = if let Some(keymap_state) = &state.keymap_state {
359 let layout_idx = keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
360 let keymap = keymap_state.get_keymap();
361 let layout_name = keymap.layout_get_name(layout_idx);
362 let changed = layout_name != state.keyboard_layout.name();
363 if changed {
364 state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
365 }
366 changed
367 } else {
368 let changed = &UNKNOWN_KEYBOARD_LAYOUT_NAME != state.keyboard_layout.name();
369 if changed {
370 state.keyboard_layout = LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME);
371 }
372 changed
373 };
374
375 if changed && let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
376 {
377 drop(state);
378 callback();
379 state = client.borrow_mut();
380 state.common.callbacks.keyboard_layout_change = Some(callback);
381 }
382 }
383
384 pub fn drop_window(&self, surface_id: &ObjectId) {
385 let mut client = self.get_client();
386 let mut state = client.borrow_mut();
387 let closed_window = state.windows.remove(surface_id).unwrap();
388 if let Some(window) = state.mouse_focused_window.take()
389 && !window.ptr_eq(&closed_window)
390 {
391 state.mouse_focused_window = Some(window);
392 }
393 if let Some(window) = state.keyboard_focused_window.take()
394 && !window.ptr_eq(&closed_window)
395 {
396 state.keyboard_focused_window = Some(window);
397 }
398 }
399}
400
401#[derive(Clone)]
402pub struct WaylandClient(Rc<RefCell<WaylandClientState>>);
403
404impl Drop for WaylandClient {
405 fn drop(&mut self) {
406 let mut state = self.0.borrow_mut();
407 state.windows.clear();
408
409 if let Some(wl_pointer) = &state.wl_pointer {
410 wl_pointer.release();
411 }
412 if let Some(cursor_shape_device) = &state.cursor_shape_device {
413 cursor_shape_device.destroy();
414 }
415 if let Some(data_device) = &state.data_device {
416 data_device.release();
417 }
418 if let Some(text_input) = &state.text_input {
419 text_input.destroy();
420 }
421 }
422}
423
424const WL_DATA_DEVICE_MANAGER_VERSION: u32 = 3;
425
426fn wl_seat_version(version: u32) -> u32 {
427 // We rely on the wl_pointer.frame event
428 const WL_SEAT_MIN_VERSION: u32 = 5;
429 const WL_SEAT_MAX_VERSION: u32 = 9;
430
431 if version < WL_SEAT_MIN_VERSION {
432 panic!(
433 "wl_seat below required version: {} < {}",
434 version, WL_SEAT_MIN_VERSION
435 );
436 }
437
438 version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION)
439}
440
441fn wl_output_version(version: u32) -> u32 {
442 const WL_OUTPUT_MIN_VERSION: u32 = 2;
443 const WL_OUTPUT_MAX_VERSION: u32 = 4;
444
445 if version < WL_OUTPUT_MIN_VERSION {
446 panic!(
447 "wl_output below required version: {} < {}",
448 version, WL_OUTPUT_MIN_VERSION
449 );
450 }
451
452 version.clamp(WL_OUTPUT_MIN_VERSION, WL_OUTPUT_MAX_VERSION)
453}
454
455impl WaylandClient {
456 pub(crate) fn new() -> Self {
457 let conn = Connection::connect_to_env().unwrap();
458
459 let (globals, mut event_queue) =
460 registry_queue_init::<WaylandClientStatePtr>(&conn).unwrap();
461 let qh = event_queue.handle();
462
463 let mut seat: Option<wl_seat::WlSeat> = None;
464 #[allow(clippy::mutable_key_type)]
465 let mut in_progress_outputs = HashMap::default();
466 globals.contents().with_list(|list| {
467 for global in list {
468 match &global.interface[..] {
469 "wl_seat" => {
470 seat = Some(globals.registry().bind::<wl_seat::WlSeat, _, _>(
471 global.name,
472 wl_seat_version(global.version),
473 &qh,
474 (),
475 ));
476 }
477 "wl_output" => {
478 let output = globals.registry().bind::<wl_output::WlOutput, _, _>(
479 global.name,
480 wl_output_version(global.version),
481 &qh,
482 (),
483 );
484 in_progress_outputs.insert(output.id(), InProgressOutput::default());
485 }
486 _ => {}
487 }
488 }
489 });
490
491 let event_loop = EventLoop::<WaylandClientStatePtr>::try_new().unwrap();
492
493 let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
494
495 let handle = event_loop.handle();
496 handle
497 .insert_source(main_receiver, {
498 let handle = handle.clone();
499 move |event, _, _: &mut WaylandClientStatePtr| {
500 if let calloop::channel::Event::Msg(runnable) = event {
501 handle.insert_idle(|_| {
502 let start = Instant::now();
503 let mut timing = match runnable {
504 RunnableVariant::Meta(runnable) => {
505 let location = runnable.metadata().location;
506 let timing = TaskTiming {
507 location,
508 start,
509 end: None,
510 };
511 profiler::add_task_timing(timing);
512
513 runnable.run();
514 timing
515 }
516 RunnableVariant::Compat(runnable) => {
517 let location = core::panic::Location::caller();
518 let timing = TaskTiming {
519 location,
520 start,
521 end: None,
522 };
523 profiler::add_task_timing(timing);
524
525 runnable.run();
526 timing
527 }
528 };
529
530 let end = Instant::now();
531 timing.end = Some(end);
532 profiler::add_task_timing(timing);
533 });
534 }
535 }
536 })
537 .unwrap();
538
539 // This could be unified with the notification handling in zed/main:fail_to_open_window.
540 let gpu_context = BladeContext::new().notify_err("Unable to init GPU context");
541
542 let seat = seat.unwrap();
543 let globals = Globals::new(
544 globals,
545 common.foreground_executor.clone(),
546 qh.clone(),
547 seat.clone(),
548 );
549
550 let data_device = globals
551 .data_device_manager
552 .as_ref()
553 .map(|data_device_manager| data_device_manager.get_data_device(&seat, &qh, ()));
554
555 let primary_selection = globals
556 .primary_selection_manager
557 .as_ref()
558 .map(|primary_selection_manager| primary_selection_manager.get_device(&seat, &qh, ()));
559
560 let mut cursor = Cursor::new(&conn, &globals, 24);
561
562 handle
563 .insert_source(XDPEventSource::new(&common.background_executor), {
564 move |event, _, client| match event {
565 XDPEvent::WindowAppearance(appearance) => {
566 if let Some(client) = client.0.upgrade() {
567 let mut client = client.borrow_mut();
568
569 client.common.appearance = appearance;
570
571 for window in client.windows.values_mut() {
572 window.set_appearance(appearance);
573 }
574 }
575 }
576 XDPEvent::CursorTheme(theme) => {
577 if let Some(client) = client.0.upgrade() {
578 let mut client = client.borrow_mut();
579 client.cursor.set_theme(theme);
580 }
581 }
582 XDPEvent::CursorSize(size) => {
583 if let Some(client) = client.0.upgrade() {
584 let mut client = client.borrow_mut();
585 client.cursor.set_size(size);
586 }
587 }
588 }
589 })
590 .unwrap();
591
592 let mut state = Rc::new(RefCell::new(WaylandClientState {
593 serial_tracker: SerialTracker::new(),
594 globals,
595 gpu_context,
596 wl_seat: seat,
597 wl_pointer: None,
598 wl_keyboard: None,
599 cursor_shape_device: None,
600 data_device,
601 primary_selection,
602 text_input: None,
603 pre_edit_text: None,
604 ime_pre_edit: None,
605 composing: false,
606 outputs: HashMap::default(),
607 in_progress_outputs,
608 windows: HashMap::default(),
609 common,
610 keyboard_layout: LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME),
611 keymap_state: None,
612 compose_state: None,
613 drag: DragState {
614 data_offer: None,
615 window: None,
616 position: Point::default(),
617 },
618 click: ClickState {
619 last_click: Instant::now(),
620 last_mouse_button: None,
621 last_location: Point::default(),
622 current_count: 0,
623 },
624 repeat: KeyRepeat {
625 characters_per_second: 16,
626 delay: Duration::from_millis(500),
627 current_id: 0,
628 current_keycode: None,
629 },
630 modifiers: Modifiers {
631 shift: false,
632 control: false,
633 alt: false,
634 function: false,
635 platform: false,
636 },
637 capslock: Capslock { on: false },
638 scroll_event_received: false,
639 axis_source: AxisSource::Wheel,
640 mouse_location: None,
641 continuous_scroll_delta: None,
642 discrete_scroll_delta: None,
643 vertical_modifier: -1.0,
644 horizontal_modifier: -1.0,
645 button_pressed: None,
646 mouse_focused_window: None,
647 keyboard_focused_window: None,
648 loop_handle: handle.clone(),
649 enter_token: None,
650 cursor_style: None,
651 clipboard: Clipboard::new(conn.clone(), handle.clone()),
652 data_offers: Vec::new(),
653 primary_data_offer: None,
654 cursor,
655 pending_activation: None,
656 event_loop: Some(event_loop),
657 }));
658
659 WaylandSource::new(conn, event_queue)
660 .insert(handle)
661 .unwrap();
662
663 Self(state)
664 }
665}
666
667impl LinuxClient for WaylandClient {
668 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
669 Box::new(self.0.borrow().keyboard_layout.clone())
670 }
671
672 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
673 self.0
674 .borrow()
675 .outputs
676 .iter()
677 .map(|(id, output)| {
678 Rc::new(WaylandDisplay {
679 id: id.clone(),
680 name: output.name.clone(),
681 bounds: output.bounds.to_pixels(output.scale as f32),
682 }) as Rc<dyn PlatformDisplay>
683 })
684 .collect()
685 }
686
687 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
688 self.0
689 .borrow()
690 .outputs
691 .iter()
692 .find_map(|(object_id, output)| {
693 (object_id.protocol_id() == id.0).then(|| {
694 Rc::new(WaylandDisplay {
695 id: object_id.clone(),
696 name: output.name.clone(),
697 bounds: output.bounds.to_pixels(output.scale as f32),
698 }) as Rc<dyn PlatformDisplay>
699 })
700 })
701 }
702
703 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
704 None
705 }
706
707 #[cfg(feature = "screen-capture")]
708 fn is_screen_capture_supported(&self) -> bool {
709 false
710 }
711
712 #[cfg(feature = "screen-capture")]
713 fn screen_capture_sources(
714 &self,
715 ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn crate::ScreenCaptureSource>>>>
716 {
717 // TODO: Get screen capture working on wayland. Be sure to try window resizing as that may
718 // be tricky.
719 //
720 // start_scap_default_target_source()
721 let (sources_tx, sources_rx) = futures::channel::oneshot::channel();
722 sources_tx
723 .send(Err(anyhow::anyhow!(
724 "Wayland screen capture not yet implemented."
725 )))
726 .ok();
727 sources_rx
728 }
729
730 fn open_window(
731 &self,
732 handle: AnyWindowHandle,
733 params: WindowParams,
734 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
735 let mut state = self.0.borrow_mut();
736
737 let parent = state.keyboard_focused_window.clone();
738
739 let (window, surface_id) = WaylandWindow::new(
740 handle,
741 state.globals.clone(),
742 &state.gpu_context,
743 WaylandClientStatePtr(Rc::downgrade(&self.0)),
744 params,
745 state.common.appearance,
746 parent,
747 )?;
748 state.windows.insert(surface_id, window.0.clone());
749
750 Ok(Box::new(window))
751 }
752
753 fn set_cursor_style(&self, style: CursorStyle) {
754 let mut state = self.0.borrow_mut();
755
756 let need_update = state.cursor_style != Some(style)
757 && (state.mouse_focused_window.is_none()
758 || state
759 .mouse_focused_window
760 .as_ref()
761 .is_some_and(|w| !w.is_blocked()));
762
763 if need_update {
764 let serial = state.serial_tracker.get(SerialKind::MouseEnter);
765 state.cursor_style = Some(style);
766
767 if let CursorStyle::None = style {
768 let wl_pointer = state
769 .wl_pointer
770 .clone()
771 .expect("window is focused by pointer");
772 wl_pointer.set_cursor(serial, None, 0, 0);
773 } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
774 cursor_shape_device.set_shape(serial, style.to_shape());
775 } else if let Some(focused_window) = &state.mouse_focused_window {
776 // cursor-shape-v1 isn't supported, set the cursor using a surface.
777 let wl_pointer = state
778 .wl_pointer
779 .clone()
780 .expect("window is focused by pointer");
781 let scale = focused_window.primary_output_scale();
782 state
783 .cursor
784 .set_icon(&wl_pointer, serial, style.to_icon_names(), scale);
785 }
786 }
787 }
788
789 fn open_uri(&self, uri: &str) {
790 let mut state = self.0.borrow_mut();
791 if let (Some(activation), Some(window)) = (
792 state.globals.activation.clone(),
793 state.mouse_focused_window.clone(),
794 ) {
795 state.pending_activation = Some(PendingActivation::Uri(uri.to_string()));
796 let token = activation.get_activation_token(&state.globals.qh, ());
797 let serial = state.serial_tracker.get(SerialKind::MousePress);
798 token.set_serial(serial, &state.wl_seat);
799 token.set_surface(&window.surface());
800 token.commit();
801 } else {
802 let executor = state.common.background_executor.clone();
803 open_uri_internal(executor, uri, None);
804 }
805 }
806
807 fn reveal_path(&self, path: PathBuf) {
808 let mut state = self.0.borrow_mut();
809 if let (Some(activation), Some(window)) = (
810 state.globals.activation.clone(),
811 state.mouse_focused_window.clone(),
812 ) {
813 state.pending_activation = Some(PendingActivation::Path(path));
814 let token = activation.get_activation_token(&state.globals.qh, ());
815 let serial = state.serial_tracker.get(SerialKind::MousePress);
816 token.set_serial(serial, &state.wl_seat);
817 token.set_surface(&window.surface());
818 token.commit();
819 } else {
820 let executor = state.common.background_executor.clone();
821 reveal_path_internal(executor, path, None);
822 }
823 }
824
825 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
826 f(&mut self.0.borrow_mut().common)
827 }
828
829 fn run(&self) {
830 let mut event_loop = self
831 .0
832 .borrow_mut()
833 .event_loop
834 .take()
835 .expect("App is already running");
836
837 event_loop
838 .run(
839 None,
840 &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
841 |_| {},
842 )
843 .log_err();
844 }
845
846 fn write_to_primary(&self, item: crate::ClipboardItem) {
847 let mut state = self.0.borrow_mut();
848 let (Some(primary_selection_manager), Some(primary_selection)) = (
849 state.globals.primary_selection_manager.clone(),
850 state.primary_selection.clone(),
851 ) else {
852 return;
853 };
854 if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
855 state.clipboard.set_primary(item);
856 let serial = state.serial_tracker.get(SerialKind::KeyPress);
857 let data_source = primary_selection_manager.create_source(&state.globals.qh, ());
858 for mime_type in TEXT_MIME_TYPES {
859 data_source.offer(mime_type.to_string());
860 }
861 data_source.offer(state.clipboard.self_mime());
862 primary_selection.set_selection(Some(&data_source), serial);
863 }
864 }
865
866 fn write_to_clipboard(&self, item: crate::ClipboardItem) {
867 let mut state = self.0.borrow_mut();
868 let (Some(data_device_manager), Some(data_device)) = (
869 state.globals.data_device_manager.clone(),
870 state.data_device.clone(),
871 ) else {
872 return;
873 };
874 if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
875 state.clipboard.set(item);
876 let serial = state.serial_tracker.get(SerialKind::KeyPress);
877 let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
878 for mime_type in TEXT_MIME_TYPES {
879 data_source.offer(mime_type.to_string());
880 }
881 data_source.offer(state.clipboard.self_mime());
882 data_device.set_selection(Some(&data_source), serial);
883 }
884 }
885
886 fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
887 self.0.borrow_mut().clipboard.read_primary()
888 }
889
890 fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
891 self.0.borrow_mut().clipboard.read()
892 }
893
894 fn active_window(&self) -> Option<AnyWindowHandle> {
895 self.0
896 .borrow_mut()
897 .keyboard_focused_window
898 .as_ref()
899 .map(|window| window.handle())
900 }
901
902 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
903 None
904 }
905
906 fn compositor_name(&self) -> &'static str {
907 "Wayland"
908 }
909
910 fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
911 async fn inner(surface: Option<wl_surface::WlSurface>) -> Option<WindowIdentifier> {
912 if let Some(surface) = surface {
913 ashpd::WindowIdentifier::from_wayland(&surface).await
914 } else {
915 None
916 }
917 }
918
919 let client_state = self.0.borrow();
920 let active_window = client_state.keyboard_focused_window.as_ref();
921 inner(active_window.map(|aw| aw.surface()))
922 }
923}
924
925impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
926 fn event(
927 this: &mut Self,
928 registry: &wl_registry::WlRegistry,
929 event: wl_registry::Event,
930 _: &GlobalListContents,
931 _: &Connection,
932 qh: &QueueHandle<Self>,
933 ) {
934 let mut client = this.get_client();
935 let mut state = client.borrow_mut();
936
937 match event {
938 wl_registry::Event::Global {
939 name,
940 interface,
941 version,
942 } => match &interface[..] {
943 "wl_seat" => {
944 if let Some(wl_pointer) = state.wl_pointer.take() {
945 wl_pointer.release();
946 }
947 if let Some(wl_keyboard) = state.wl_keyboard.take() {
948 wl_keyboard.release();
949 }
950 state.wl_seat.release();
951 state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
952 name,
953 wl_seat_version(version),
954 qh,
955 (),
956 );
957 }
958 "wl_output" => {
959 let output = registry.bind::<wl_output::WlOutput, _, _>(
960 name,
961 wl_output_version(version),
962 qh,
963 (),
964 );
965
966 state
967 .in_progress_outputs
968 .insert(output.id(), InProgressOutput::default());
969 }
970 _ => {}
971 },
972 wl_registry::Event::GlobalRemove { name: _ } => {
973 // TODO: handle global removal
974 }
975 _ => {}
976 }
977 }
978}
979
980delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
981delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
982delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
983delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
984delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
985delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
986delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
987delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
988delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
989delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
990delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
991delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
992delegate_noop!(WaylandClientStatePtr: ignore zwlr_layer_shell_v1::ZwlrLayerShellV1);
993delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
994delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
995delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
996delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
997delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
998
999impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
1000 fn event(
1001 state: &mut WaylandClientStatePtr,
1002 _: &wl_callback::WlCallback,
1003 event: wl_callback::Event,
1004 surface_id: &ObjectId,
1005 _: &Connection,
1006 _: &QueueHandle<Self>,
1007 ) {
1008 let client = state.get_client();
1009 let mut state = client.borrow_mut();
1010 let Some(window) = get_window(&mut state, surface_id) else {
1011 return;
1012 };
1013 drop(state);
1014
1015 if let wl_callback::Event::Done { .. } = event {
1016 window.frame();
1017 }
1018 }
1019}
1020
1021pub(crate) fn get_window(
1022 mut state: &mut RefMut<WaylandClientState>,
1023 surface_id: &ObjectId,
1024) -> Option<WaylandWindowStatePtr> {
1025 state.windows.get(surface_id).cloned()
1026}
1027
1028impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
1029 fn event(
1030 this: &mut Self,
1031 surface: &wl_surface::WlSurface,
1032 event: <wl_surface::WlSurface as Proxy>::Event,
1033 _: &(),
1034 _: &Connection,
1035 _: &QueueHandle<Self>,
1036 ) {
1037 let mut client = this.get_client();
1038 let mut state = client.borrow_mut();
1039
1040 let Some(window) = get_window(&mut state, &surface.id()) else {
1041 return;
1042 };
1043 #[allow(clippy::mutable_key_type)]
1044 let outputs = state.outputs.clone();
1045 drop(state);
1046
1047 window.handle_surface_event(event, outputs);
1048 }
1049}
1050
1051impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
1052 fn event(
1053 this: &mut Self,
1054 output: &wl_output::WlOutput,
1055 event: <wl_output::WlOutput as Proxy>::Event,
1056 _: &(),
1057 _: &Connection,
1058 _: &QueueHandle<Self>,
1059 ) {
1060 let mut client = this.get_client();
1061 let mut state = client.borrow_mut();
1062
1063 let Some(mut in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
1064 return;
1065 };
1066
1067 match event {
1068 wl_output::Event::Name { name } => {
1069 in_progress_output.name = Some(name);
1070 }
1071 wl_output::Event::Scale { factor } => {
1072 in_progress_output.scale = Some(factor);
1073 }
1074 wl_output::Event::Geometry { x, y, .. } => {
1075 in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
1076 }
1077 wl_output::Event::Mode { width, height, .. } => {
1078 in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
1079 }
1080 wl_output::Event::Done => {
1081 if let Some(complete) = in_progress_output.complete() {
1082 state.outputs.insert(output.id(), complete);
1083 }
1084 state.in_progress_outputs.remove(&output.id());
1085 }
1086 _ => {}
1087 }
1088 }
1089}
1090
1091impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
1092 fn event(
1093 state: &mut Self,
1094 _: &xdg_surface::XdgSurface,
1095 event: xdg_surface::Event,
1096 surface_id: &ObjectId,
1097 _: &Connection,
1098 _: &QueueHandle<Self>,
1099 ) {
1100 let client = state.get_client();
1101 let mut state = client.borrow_mut();
1102 let Some(window) = get_window(&mut state, surface_id) else {
1103 return;
1104 };
1105 drop(state);
1106 window.handle_xdg_surface_event(event);
1107 }
1108}
1109
1110impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
1111 fn event(
1112 this: &mut Self,
1113 _: &xdg_toplevel::XdgToplevel,
1114 event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
1115 surface_id: &ObjectId,
1116 _: &Connection,
1117 _: &QueueHandle<Self>,
1118 ) {
1119 let client = this.get_client();
1120 let mut state = client.borrow_mut();
1121 let Some(window) = get_window(&mut state, surface_id) else {
1122 return;
1123 };
1124
1125 drop(state);
1126 let should_close = window.handle_toplevel_event(event);
1127
1128 if should_close {
1129 // The close logic will be handled in drop_window()
1130 window.close();
1131 }
1132 }
1133}
1134
1135impl Dispatch<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, ObjectId> for WaylandClientStatePtr {
1136 fn event(
1137 this: &mut Self,
1138 _: &zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
1139 event: <zwlr_layer_surface_v1::ZwlrLayerSurfaceV1 as Proxy>::Event,
1140 surface_id: &ObjectId,
1141 _: &Connection,
1142 _: &QueueHandle<Self>,
1143 ) {
1144 let client = this.get_client();
1145 let mut state = client.borrow_mut();
1146 let Some(window) = get_window(&mut state, surface_id) else {
1147 return;
1148 };
1149
1150 drop(state);
1151 let should_close = window.handle_layersurface_event(event);
1152
1153 if should_close {
1154 // The close logic will be handled in drop_window()
1155 window.close();
1156 }
1157 }
1158}
1159
1160impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1161 fn event(
1162 _: &mut Self,
1163 wm_base: &xdg_wm_base::XdgWmBase,
1164 event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1165 _: &(),
1166 _: &Connection,
1167 _: &QueueHandle<Self>,
1168 ) {
1169 if let xdg_wm_base::Event::Ping { serial } = event {
1170 wm_base.pong(serial);
1171 }
1172 }
1173}
1174
1175impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1176 fn event(
1177 this: &mut Self,
1178 token: &xdg_activation_token_v1::XdgActivationTokenV1,
1179 event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1180 _: &(),
1181 _: &Connection,
1182 _: &QueueHandle<Self>,
1183 ) {
1184 let client = this.get_client();
1185 let mut state = client.borrow_mut();
1186
1187 if let xdg_activation_token_v1::Event::Done { token } = event {
1188 let executor = state.common.background_executor.clone();
1189 match state.pending_activation.take() {
1190 Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1191 Some(PendingActivation::Path(path)) => {
1192 reveal_path_internal(executor, path, Some(token))
1193 }
1194 Some(PendingActivation::Window(window)) => {
1195 let Some(window) = get_window(&mut state, &window) else {
1196 return;
1197 };
1198 let activation = state.globals.activation.as_ref().unwrap();
1199 activation.activate(token, &window.surface());
1200 }
1201 None => log::error!("activation token received with no pending activation"),
1202 }
1203 }
1204
1205 token.destroy();
1206 }
1207}
1208
1209impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1210 fn event(
1211 state: &mut Self,
1212 seat: &wl_seat::WlSeat,
1213 event: wl_seat::Event,
1214 _: &(),
1215 _: &Connection,
1216 qh: &QueueHandle<Self>,
1217 ) {
1218 if let wl_seat::Event::Capabilities {
1219 capabilities: WEnum::Value(capabilities),
1220 } = event
1221 {
1222 let client = state.get_client();
1223 let mut state = client.borrow_mut();
1224 if capabilities.contains(wl_seat::Capability::Keyboard) {
1225 let keyboard = seat.get_keyboard(qh, ());
1226
1227 state.text_input = state
1228 .globals
1229 .text_input_manager
1230 .as_ref()
1231 .map(|text_input_manager| text_input_manager.get_text_input(seat, qh, ()));
1232
1233 if let Some(wl_keyboard) = &state.wl_keyboard {
1234 wl_keyboard.release();
1235 }
1236
1237 state.wl_keyboard = Some(keyboard);
1238 }
1239 if capabilities.contains(wl_seat::Capability::Pointer) {
1240 let pointer = seat.get_pointer(qh, ());
1241 state.cursor_shape_device = state
1242 .globals
1243 .cursor_shape_manager
1244 .as_ref()
1245 .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1246
1247 if let Some(wl_pointer) = &state.wl_pointer {
1248 wl_pointer.release();
1249 }
1250
1251 state.wl_pointer = Some(pointer);
1252 }
1253 }
1254 }
1255}
1256
1257impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1258 fn event(
1259 this: &mut Self,
1260 _: &wl_keyboard::WlKeyboard,
1261 event: wl_keyboard::Event,
1262 _: &(),
1263 _: &Connection,
1264 _: &QueueHandle<Self>,
1265 ) {
1266 let mut client = this.get_client();
1267 let mut state = client.borrow_mut();
1268 match event {
1269 wl_keyboard::Event::RepeatInfo { rate, delay } => {
1270 state.repeat.characters_per_second = rate as u32;
1271 state.repeat.delay = Duration::from_millis(delay as u64);
1272 }
1273 wl_keyboard::Event::Keymap {
1274 format: WEnum::Value(format),
1275 fd,
1276 size,
1277 ..
1278 } => {
1279 if format != wl_keyboard::KeymapFormat::XkbV1 {
1280 log::error!("Received keymap format {:?}, expected XkbV1", format);
1281 return;
1282 }
1283 let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1284 let keymap = unsafe {
1285 xkb::Keymap::new_from_fd(
1286 &xkb_context,
1287 fd,
1288 size as usize,
1289 XKB_KEYMAP_FORMAT_TEXT_V1,
1290 KEYMAP_COMPILE_NO_FLAGS,
1291 )
1292 .log_err()
1293 .flatten()
1294 .expect("Failed to create keymap")
1295 };
1296 state.keymap_state = Some(xkb::State::new(&keymap));
1297 state.compose_state = get_xkb_compose_state(&xkb_context);
1298 drop(state);
1299
1300 this.handle_keyboard_layout_change();
1301 }
1302 wl_keyboard::Event::Enter { surface, .. } => {
1303 state.keyboard_focused_window = get_window(&mut state, &surface.id());
1304 state.enter_token = Some(());
1305
1306 if let Some(window) = state.keyboard_focused_window.clone() {
1307 drop(state);
1308 window.set_focused(true);
1309 }
1310 }
1311 wl_keyboard::Event::Leave { surface, .. } => {
1312 let keyboard_focused_window = get_window(&mut state, &surface.id());
1313 state.keyboard_focused_window = None;
1314 state.enter_token.take();
1315 // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1316 state.repeat.current_id += 1;
1317
1318 if let Some(window) = keyboard_focused_window {
1319 if let Some(ref mut compose) = state.compose_state {
1320 compose.reset();
1321 }
1322 state.pre_edit_text.take();
1323 drop(state);
1324 window.handle_ime(ImeInput::DeleteText);
1325 window.set_focused(false);
1326 }
1327 }
1328 wl_keyboard::Event::Modifiers {
1329 mods_depressed,
1330 mods_latched,
1331 mods_locked,
1332 group,
1333 ..
1334 } => {
1335 let focused_window = state.keyboard_focused_window.clone();
1336
1337 let keymap_state = state.keymap_state.as_mut().unwrap();
1338 let old_layout =
1339 keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1340 keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1341 state.modifiers = Modifiers::from_xkb(keymap_state);
1342 let keymap_state = state.keymap_state.as_mut().unwrap();
1343 state.capslock = Capslock::from_xkb(keymap_state);
1344
1345 let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1346 modifiers: state.modifiers,
1347 capslock: state.capslock,
1348 });
1349 drop(state);
1350
1351 if let Some(focused_window) = focused_window {
1352 focused_window.handle_input(input);
1353 }
1354
1355 if group != old_layout {
1356 this.handle_keyboard_layout_change();
1357 }
1358 }
1359 wl_keyboard::Event::Key {
1360 serial,
1361 key,
1362 state: WEnum::Value(key_state),
1363 ..
1364 } => {
1365 state.serial_tracker.update(SerialKind::KeyPress, serial);
1366
1367 let focused_window = state.keyboard_focused_window.clone();
1368 let Some(focused_window) = focused_window else {
1369 return;
1370 };
1371
1372 let keymap_state = state.keymap_state.as_ref().unwrap();
1373 let keycode = Keycode::from(key + MIN_KEYCODE);
1374 let keysym = keymap_state.key_get_one_sym(keycode);
1375
1376 match key_state {
1377 wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1378 let mut keystroke =
1379 Keystroke::from_xkb(keymap_state, state.modifiers, keycode);
1380 if let Some(mut compose) = state.compose_state.take() {
1381 compose.feed(keysym);
1382 match compose.status() {
1383 xkb::Status::Composing => {
1384 keystroke.key_char = None;
1385 state.pre_edit_text =
1386 compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1387 let pre_edit =
1388 state.pre_edit_text.clone().unwrap_or(String::default());
1389 drop(state);
1390 focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1391 state = client.borrow_mut();
1392 }
1393
1394 xkb::Status::Composed => {
1395 state.pre_edit_text.take();
1396 keystroke.key_char = compose.utf8();
1397 if let Some(keysym) = compose.keysym() {
1398 keystroke.key = xkb::keysym_get_name(keysym);
1399 }
1400 }
1401 xkb::Status::Cancelled => {
1402 let pre_edit = state.pre_edit_text.take();
1403 let new_pre_edit = Keystroke::underlying_dead_key(keysym);
1404 state.pre_edit_text = new_pre_edit.clone();
1405 drop(state);
1406 if let Some(pre_edit) = pre_edit {
1407 focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1408 }
1409 if let Some(current_key) = new_pre_edit {
1410 focused_window
1411 .handle_ime(ImeInput::SetMarkedText(current_key));
1412 }
1413 compose.feed(keysym);
1414 state = client.borrow_mut();
1415 }
1416 _ => {}
1417 }
1418 state.compose_state = Some(compose);
1419 }
1420 let input = PlatformInput::KeyDown(KeyDownEvent {
1421 keystroke: keystroke.clone(),
1422 is_held: false,
1423 prefer_character_input: false,
1424 });
1425
1426 state.repeat.current_id += 1;
1427 state.repeat.current_keycode = Some(keycode);
1428
1429 let rate = state.repeat.characters_per_second;
1430 let repeat_interval = Duration::from_secs(1) / rate.max(1);
1431 let id = state.repeat.current_id;
1432 state
1433 .loop_handle
1434 .insert_source(Timer::from_duration(state.repeat.delay), {
1435 let input = PlatformInput::KeyDown(KeyDownEvent {
1436 keystroke,
1437 is_held: true,
1438 prefer_character_input: false,
1439 });
1440 move |event_timestamp, _metadata, this| {
1441 let mut client = this.get_client();
1442 let mut state = client.borrow_mut();
1443 let is_repeating = id == state.repeat.current_id
1444 && state.repeat.current_keycode.is_some()
1445 && state.keyboard_focused_window.is_some();
1446
1447 if !is_repeating || rate == 0 {
1448 return TimeoutAction::Drop;
1449 }
1450
1451 let focused_window =
1452 state.keyboard_focused_window.as_ref().unwrap().clone();
1453
1454 drop(state);
1455 focused_window.handle_input(input.clone());
1456
1457 // If the new scheduled time is in the past the event will repeat as soon as possible
1458 TimeoutAction::ToInstant(event_timestamp + repeat_interval)
1459 }
1460 })
1461 .unwrap();
1462
1463 drop(state);
1464 focused_window.handle_input(input);
1465 }
1466 wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1467 let input = PlatformInput::KeyUp(KeyUpEvent {
1468 keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
1469 });
1470
1471 if state.repeat.current_keycode == Some(keycode) {
1472 state.repeat.current_keycode = None;
1473 }
1474
1475 drop(state);
1476 focused_window.handle_input(input);
1477 }
1478 _ => {}
1479 }
1480 }
1481 _ => {}
1482 }
1483 }
1484}
1485
1486impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1487 fn event(
1488 this: &mut Self,
1489 text_input: &zwp_text_input_v3::ZwpTextInputV3,
1490 event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1491 _: &(),
1492 _: &Connection,
1493 _: &QueueHandle<Self>,
1494 ) {
1495 let client = this.get_client();
1496 let mut state = client.borrow_mut();
1497 match event {
1498 zwp_text_input_v3::Event::Enter { .. } => {
1499 drop(state);
1500 this.enable_ime();
1501 }
1502 zwp_text_input_v3::Event::Leave { .. } => {
1503 drop(state);
1504 this.disable_ime();
1505 }
1506 zwp_text_input_v3::Event::CommitString { text } => {
1507 state.composing = false;
1508 let Some(window) = state.keyboard_focused_window.clone() else {
1509 return;
1510 };
1511
1512 if let Some(commit_text) = text {
1513 drop(state);
1514 // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1515 // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1516 if commit_text.len() == 1 {
1517 window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1518 keystroke: Keystroke {
1519 modifiers: Modifiers::default(),
1520 key: commit_text.clone(),
1521 key_char: Some(commit_text),
1522 },
1523 is_held: false,
1524 prefer_character_input: false,
1525 }));
1526 } else {
1527 window.handle_ime(ImeInput::InsertText(commit_text));
1528 }
1529 }
1530 }
1531 zwp_text_input_v3::Event::PreeditString { text, .. } => {
1532 state.composing = true;
1533 state.ime_pre_edit = text;
1534 }
1535 zwp_text_input_v3::Event::Done { serial } => {
1536 let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1537 state.serial_tracker.update(SerialKind::InputMethod, serial);
1538 let Some(window) = state.keyboard_focused_window.clone() else {
1539 return;
1540 };
1541
1542 if let Some(text) = state.ime_pre_edit.take() {
1543 drop(state);
1544 window.handle_ime(ImeInput::SetMarkedText(text));
1545 if let Some(area) = window.get_ime_area() {
1546 text_input.set_cursor_rectangle(
1547 area.origin.x.0 as i32,
1548 area.origin.y.0 as i32,
1549 area.size.width.0 as i32,
1550 area.size.height.0 as i32,
1551 );
1552 if last_serial == serial {
1553 text_input.commit();
1554 }
1555 }
1556 } else {
1557 state.composing = false;
1558 drop(state);
1559 window.handle_ime(ImeInput::DeleteText);
1560 }
1561 }
1562 _ => {}
1563 }
1564 }
1565}
1566
1567fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1568 // These values are coming from <linux/input-event-codes.h>.
1569 const BTN_LEFT: u32 = 0x110;
1570 const BTN_RIGHT: u32 = 0x111;
1571 const BTN_MIDDLE: u32 = 0x112;
1572 const BTN_SIDE: u32 = 0x113;
1573 const BTN_EXTRA: u32 = 0x114;
1574 const BTN_FORWARD: u32 = 0x115;
1575 const BTN_BACK: u32 = 0x116;
1576
1577 Some(match button {
1578 BTN_LEFT => MouseButton::Left,
1579 BTN_RIGHT => MouseButton::Right,
1580 BTN_MIDDLE => MouseButton::Middle,
1581 BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1582 BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1583 _ => return None,
1584 })
1585}
1586
1587impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1588 fn event(
1589 this: &mut Self,
1590 wl_pointer: &wl_pointer::WlPointer,
1591 event: wl_pointer::Event,
1592 _: &(),
1593 _: &Connection,
1594 _: &QueueHandle<Self>,
1595 ) {
1596 let mut client = this.get_client();
1597 let mut state = client.borrow_mut();
1598
1599 match event {
1600 wl_pointer::Event::Enter {
1601 serial,
1602 surface,
1603 surface_x,
1604 surface_y,
1605 ..
1606 } => {
1607 state.serial_tracker.update(SerialKind::MouseEnter, serial);
1608 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1609 state.button_pressed = None;
1610
1611 if let Some(window) = get_window(&mut state, &surface.id()) {
1612 state.mouse_focused_window = Some(window.clone());
1613
1614 if state.enter_token.is_some() {
1615 state.enter_token = None;
1616 }
1617 if let Some(style) = state.cursor_style {
1618 if let CursorStyle::None = style {
1619 let wl_pointer = state
1620 .wl_pointer
1621 .clone()
1622 .expect("window is focused by pointer");
1623 wl_pointer.set_cursor(serial, None, 0, 0);
1624 } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1625 cursor_shape_device.set_shape(serial, style.to_shape());
1626 } else {
1627 let scale = window.primary_output_scale();
1628 state
1629 .cursor
1630 .set_icon(wl_pointer, serial, style.to_icon_names(), scale);
1631 }
1632 }
1633 drop(state);
1634 window.set_hovered(true);
1635 }
1636 }
1637 wl_pointer::Event::Leave { .. } => {
1638 if let Some(focused_window) = state.mouse_focused_window.clone() {
1639 let input = PlatformInput::MouseExited(MouseExitEvent {
1640 position: state.mouse_location.unwrap(),
1641 pressed_button: state.button_pressed,
1642 modifiers: state.modifiers,
1643 });
1644 state.mouse_focused_window = None;
1645 state.mouse_location = None;
1646 state.button_pressed = None;
1647
1648 drop(state);
1649 focused_window.handle_input(input);
1650 focused_window.set_hovered(false);
1651 }
1652 }
1653 wl_pointer::Event::Motion {
1654 surface_x,
1655 surface_y,
1656 ..
1657 } => {
1658 if state.mouse_focused_window.is_none() {
1659 return;
1660 }
1661 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1662
1663 if let Some(window) = state.mouse_focused_window.clone() {
1664 if window.is_blocked() {
1665 let default_style = CursorStyle::Arrow;
1666 if state.cursor_style != Some(default_style) {
1667 let serial = state.serial_tracker.get(SerialKind::MouseEnter);
1668 state.cursor_style = Some(default_style);
1669
1670 if let Some(cursor_shape_device) = &state.cursor_shape_device {
1671 cursor_shape_device.set_shape(serial, default_style.to_shape());
1672 } else {
1673 // cursor-shape-v1 isn't supported, set the cursor using a surface.
1674 let wl_pointer = state
1675 .wl_pointer
1676 .clone()
1677 .expect("window is focused by pointer");
1678 let scale = window.primary_output_scale();
1679 state.cursor.set_icon(
1680 &wl_pointer,
1681 serial,
1682 default_style.to_icon_names(),
1683 scale,
1684 );
1685 }
1686 }
1687 }
1688 if state
1689 .keyboard_focused_window
1690 .as_ref()
1691 .is_some_and(|keyboard_window| window.ptr_eq(keyboard_window))
1692 {
1693 state.enter_token = None;
1694 }
1695 let input = PlatformInput::MouseMove(MouseMoveEvent {
1696 position: state.mouse_location.unwrap(),
1697 pressed_button: state.button_pressed,
1698 modifiers: state.modifiers,
1699 });
1700 drop(state);
1701 window.handle_input(input);
1702 }
1703 }
1704 wl_pointer::Event::Button {
1705 serial,
1706 button,
1707 state: WEnum::Value(button_state),
1708 ..
1709 } => {
1710 state.serial_tracker.update(SerialKind::MousePress, serial);
1711 let button = linux_button_to_gpui(button);
1712 let Some(button) = button else { return };
1713 if state.mouse_focused_window.is_none() {
1714 return;
1715 }
1716 match button_state {
1717 wl_pointer::ButtonState::Pressed => {
1718 if let Some(window) = state.keyboard_focused_window.clone() {
1719 if state.composing && state.text_input.is_some() {
1720 drop(state);
1721 // text_input_v3 don't have something like a reset function
1722 this.disable_ime();
1723 this.enable_ime();
1724 window.handle_ime(ImeInput::UnmarkText);
1725 state = client.borrow_mut();
1726 } else if let (Some(text), Some(compose)) =
1727 (state.pre_edit_text.take(), state.compose_state.as_mut())
1728 {
1729 compose.reset();
1730 drop(state);
1731 window.handle_ime(ImeInput::InsertText(text));
1732 state = client.borrow_mut();
1733 }
1734 }
1735 let click_elapsed = state.click.last_click.elapsed();
1736
1737 if click_elapsed < DOUBLE_CLICK_INTERVAL
1738 && state
1739 .click
1740 .last_mouse_button
1741 .is_some_and(|prev_button| prev_button == button)
1742 && is_within_click_distance(
1743 state.click.last_location,
1744 state.mouse_location.unwrap(),
1745 )
1746 {
1747 state.click.current_count += 1;
1748 } else {
1749 state.click.current_count = 1;
1750 }
1751
1752 state.click.last_click = Instant::now();
1753 state.click.last_mouse_button = Some(button);
1754 state.click.last_location = state.mouse_location.unwrap();
1755
1756 state.button_pressed = Some(button);
1757
1758 if let Some(window) = state.mouse_focused_window.clone() {
1759 let input = PlatformInput::MouseDown(MouseDownEvent {
1760 button,
1761 position: state.mouse_location.unwrap(),
1762 modifiers: state.modifiers,
1763 click_count: state.click.current_count,
1764 first_mouse: state.enter_token.take().is_some(),
1765 });
1766 drop(state);
1767 window.handle_input(input);
1768 }
1769 }
1770 wl_pointer::ButtonState::Released => {
1771 state.button_pressed = None;
1772
1773 if let Some(window) = state.mouse_focused_window.clone() {
1774 let input = PlatformInput::MouseUp(MouseUpEvent {
1775 button,
1776 position: state.mouse_location.unwrap(),
1777 modifiers: state.modifiers,
1778 click_count: state.click.current_count,
1779 });
1780 drop(state);
1781 window.handle_input(input);
1782 }
1783 }
1784 _ => {}
1785 }
1786 }
1787
1788 // Axis Events
1789 wl_pointer::Event::AxisSource {
1790 axis_source: WEnum::Value(axis_source),
1791 } => {
1792 state.axis_source = axis_source;
1793 }
1794 wl_pointer::Event::Axis {
1795 axis: WEnum::Value(axis),
1796 value,
1797 ..
1798 } => {
1799 if state.axis_source == AxisSource::Wheel {
1800 return;
1801 }
1802 let axis = if state.modifiers.shift {
1803 wl_pointer::Axis::HorizontalScroll
1804 } else {
1805 axis
1806 };
1807 let axis_modifier = match axis {
1808 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1809 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1810 _ => 1.0,
1811 };
1812 state.scroll_event_received = true;
1813 let scroll_delta = state
1814 .continuous_scroll_delta
1815 .get_or_insert(point(px(0.0), px(0.0)));
1816 let modifier = 3.0;
1817 match axis {
1818 wl_pointer::Axis::VerticalScroll => {
1819 scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1820 }
1821 wl_pointer::Axis::HorizontalScroll => {
1822 scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1823 }
1824 _ => unreachable!(),
1825 }
1826 }
1827 wl_pointer::Event::AxisDiscrete {
1828 axis: WEnum::Value(axis),
1829 discrete,
1830 } => {
1831 state.scroll_event_received = true;
1832 let axis = if state.modifiers.shift {
1833 wl_pointer::Axis::HorizontalScroll
1834 } else {
1835 axis
1836 };
1837 let axis_modifier = match axis {
1838 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1839 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1840 _ => 1.0,
1841 };
1842
1843 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1844 match axis {
1845 wl_pointer::Axis::VerticalScroll => {
1846 scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1847 }
1848 wl_pointer::Axis::HorizontalScroll => {
1849 scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1850 }
1851 _ => unreachable!(),
1852 }
1853 }
1854 wl_pointer::Event::AxisValue120 {
1855 axis: WEnum::Value(axis),
1856 value120,
1857 } => {
1858 state.scroll_event_received = true;
1859 let axis = if state.modifiers.shift {
1860 wl_pointer::Axis::HorizontalScroll
1861 } else {
1862 axis
1863 };
1864 let axis_modifier = match axis {
1865 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1866 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1867 _ => unreachable!(),
1868 };
1869
1870 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1871 let wheel_percent = value120 as f32 / 120.0;
1872 match axis {
1873 wl_pointer::Axis::VerticalScroll => {
1874 scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1875 }
1876 wl_pointer::Axis::HorizontalScroll => {
1877 scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1878 }
1879 _ => unreachable!(),
1880 }
1881 }
1882 wl_pointer::Event::Frame => {
1883 if state.scroll_event_received {
1884 state.scroll_event_received = false;
1885 let continuous = state.continuous_scroll_delta.take();
1886 let discrete = state.discrete_scroll_delta.take();
1887 if let Some(continuous) = continuous {
1888 if let Some(window) = state.mouse_focused_window.clone() {
1889 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1890 position: state.mouse_location.unwrap(),
1891 delta: ScrollDelta::Pixels(continuous),
1892 modifiers: state.modifiers,
1893 touch_phase: TouchPhase::Moved,
1894 });
1895 drop(state);
1896 window.handle_input(input);
1897 }
1898 } else if let Some(discrete) = discrete
1899 && let Some(window) = state.mouse_focused_window.clone()
1900 {
1901 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1902 position: state.mouse_location.unwrap(),
1903 delta: ScrollDelta::Lines(discrete),
1904 modifiers: state.modifiers,
1905 touch_phase: TouchPhase::Moved,
1906 });
1907 drop(state);
1908 window.handle_input(input);
1909 }
1910 }
1911 }
1912 _ => {}
1913 }
1914 }
1915}
1916
1917impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1918 fn event(
1919 this: &mut Self,
1920 _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1921 event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1922 surface_id: &ObjectId,
1923 _: &Connection,
1924 _: &QueueHandle<Self>,
1925 ) {
1926 let client = this.get_client();
1927 let mut state = client.borrow_mut();
1928
1929 let Some(window) = get_window(&mut state, surface_id) else {
1930 return;
1931 };
1932
1933 drop(state);
1934 window.handle_fractional_scale_event(event);
1935 }
1936}
1937
1938impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1939 for WaylandClientStatePtr
1940{
1941 fn event(
1942 this: &mut Self,
1943 _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1944 event: zxdg_toplevel_decoration_v1::Event,
1945 surface_id: &ObjectId,
1946 _: &Connection,
1947 _: &QueueHandle<Self>,
1948 ) {
1949 let client = this.get_client();
1950 let mut state = client.borrow_mut();
1951 let Some(window) = get_window(&mut state, surface_id) else {
1952 return;
1953 };
1954
1955 drop(state);
1956 window.handle_toplevel_decoration_event(event);
1957 }
1958}
1959
1960impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1961 fn event(
1962 this: &mut Self,
1963 _: &wl_data_device::WlDataDevice,
1964 event: wl_data_device::Event,
1965 _: &(),
1966 _: &Connection,
1967 _: &QueueHandle<Self>,
1968 ) {
1969 let client = this.get_client();
1970 let mut state = client.borrow_mut();
1971
1972 match event {
1973 // Clipboard
1974 wl_data_device::Event::DataOffer { id: data_offer } => {
1975 state.data_offers.push(DataOffer::new(data_offer));
1976 if state.data_offers.len() > 2 {
1977 // At most we store a clipboard offer and a drag and drop offer.
1978 state.data_offers.remove(0).inner.destroy();
1979 }
1980 }
1981 wl_data_device::Event::Selection { id: data_offer } => {
1982 if let Some(offer) = data_offer {
1983 let offer = state
1984 .data_offers
1985 .iter()
1986 .find(|wrapper| wrapper.inner.id() == offer.id());
1987 let offer = offer.cloned();
1988 state.clipboard.set_offer(offer);
1989 } else {
1990 state.clipboard.set_offer(None);
1991 }
1992 }
1993
1994 // Drag and drop
1995 wl_data_device::Event::Enter {
1996 serial,
1997 surface,
1998 x,
1999 y,
2000 id: data_offer,
2001 } => {
2002 state.serial_tracker.update(SerialKind::DataDevice, serial);
2003 if let Some(data_offer) = data_offer {
2004 let Some(drag_window) = get_window(&mut state, &surface.id()) else {
2005 return;
2006 };
2007
2008 const ACTIONS: DndAction = DndAction::Copy;
2009 data_offer.set_actions(ACTIONS, ACTIONS);
2010
2011 let pipe = Pipe::new().unwrap();
2012 data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
2013 BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
2014 });
2015 let fd = pipe.read;
2016 drop(pipe.write);
2017
2018 let read_task = state.common.background_executor.spawn(async {
2019 let buffer = unsafe { read_fd(fd)? };
2020 let text = String::from_utf8(buffer)?;
2021 anyhow::Ok(text)
2022 });
2023
2024 let this = this.clone();
2025 state
2026 .common
2027 .foreground_executor
2028 .spawn(async move {
2029 let file_list = match read_task.await {
2030 Ok(list) => list,
2031 Err(err) => {
2032 log::error!("error reading drag and drop pipe: {err:?}");
2033 return;
2034 }
2035 };
2036
2037 let paths: SmallVec<[_; 2]> = file_list
2038 .lines()
2039 .filter_map(|path| Url::parse(path).log_err())
2040 .filter_map(|url| url.to_file_path().log_err())
2041 .collect();
2042 let position = Point::new(x.into(), y.into());
2043
2044 // Prevent dropping text from other programs.
2045 if paths.is_empty() {
2046 data_offer.destroy();
2047 return;
2048 }
2049
2050 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
2051 position,
2052 paths: crate::ExternalPaths(paths),
2053 });
2054
2055 let client = this.get_client();
2056 let mut state = client.borrow_mut();
2057 state.drag.data_offer = Some(data_offer);
2058 state.drag.window = Some(drag_window.clone());
2059 state.drag.position = position;
2060
2061 drop(state);
2062 drag_window.handle_input(input);
2063 })
2064 .detach();
2065 }
2066 }
2067 wl_data_device::Event::Motion { x, y, .. } => {
2068 let Some(drag_window) = state.drag.window.clone() else {
2069 return;
2070 };
2071 let position = Point::new(x.into(), y.into());
2072 state.drag.position = position;
2073
2074 let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
2075 drop(state);
2076 drag_window.handle_input(input);
2077 }
2078 wl_data_device::Event::Leave => {
2079 let Some(drag_window) = state.drag.window.clone() else {
2080 return;
2081 };
2082 let data_offer = state.drag.data_offer.clone().unwrap();
2083 data_offer.destroy();
2084
2085 state.drag.data_offer = None;
2086 state.drag.window = None;
2087
2088 let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
2089 drop(state);
2090 drag_window.handle_input(input);
2091 }
2092 wl_data_device::Event::Drop => {
2093 let Some(drag_window) = state.drag.window.clone() else {
2094 return;
2095 };
2096 let data_offer = state.drag.data_offer.clone().unwrap();
2097 data_offer.finish();
2098 data_offer.destroy();
2099
2100 state.drag.data_offer = None;
2101 state.drag.window = None;
2102
2103 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
2104 position: state.drag.position,
2105 });
2106 drop(state);
2107 drag_window.handle_input(input);
2108 }
2109 _ => {}
2110 }
2111 }
2112
2113 event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
2114 wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
2115 ]);
2116}
2117
2118impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
2119 fn event(
2120 this: &mut Self,
2121 data_offer: &wl_data_offer::WlDataOffer,
2122 event: wl_data_offer::Event,
2123 _: &(),
2124 _: &Connection,
2125 _: &QueueHandle<Self>,
2126 ) {
2127 let client = this.get_client();
2128 let mut state = client.borrow_mut();
2129
2130 if let wl_data_offer::Event::Offer { mime_type } = event {
2131 // Drag and drop
2132 if mime_type == FILE_LIST_MIME_TYPE {
2133 let serial = state.serial_tracker.get(SerialKind::DataDevice);
2134 let mime_type = mime_type.clone();
2135 data_offer.accept(serial, Some(mime_type));
2136 }
2137
2138 // Clipboard
2139 if let Some(offer) = state
2140 .data_offers
2141 .iter_mut()
2142 .find(|wrapper| wrapper.inner.id() == data_offer.id())
2143 {
2144 offer.add_mime_type(mime_type);
2145 }
2146 }
2147 }
2148}
2149
2150impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
2151 fn event(
2152 this: &mut Self,
2153 data_source: &wl_data_source::WlDataSource,
2154 event: wl_data_source::Event,
2155 _: &(),
2156 _: &Connection,
2157 _: &QueueHandle<Self>,
2158 ) {
2159 let client = this.get_client();
2160 let mut state = client.borrow_mut();
2161
2162 match event {
2163 wl_data_source::Event::Send { mime_type, fd } => {
2164 state.clipboard.send(mime_type, fd);
2165 }
2166 wl_data_source::Event::Cancelled => {
2167 data_source.destroy();
2168 }
2169 _ => {}
2170 }
2171 }
2172}
2173
2174impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2175 for WaylandClientStatePtr
2176{
2177 fn event(
2178 this: &mut Self,
2179 _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2180 event: zwp_primary_selection_device_v1::Event,
2181 _: &(),
2182 _: &Connection,
2183 _: &QueueHandle<Self>,
2184 ) {
2185 let client = this.get_client();
2186 let mut state = client.borrow_mut();
2187
2188 match event {
2189 zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2190 let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2191 if let Some(old_offer) = old_offer {
2192 old_offer.inner.destroy();
2193 }
2194 }
2195 zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2196 if data_offer.is_some() {
2197 let offer = state.primary_data_offer.clone();
2198 state.clipboard.set_primary_offer(offer);
2199 } else {
2200 state.clipboard.set_primary_offer(None);
2201 }
2202 }
2203 _ => {}
2204 }
2205 }
2206
2207 event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2208 zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2209 ]);
2210}
2211
2212impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2213 for WaylandClientStatePtr
2214{
2215 fn event(
2216 this: &mut Self,
2217 _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2218 event: zwp_primary_selection_offer_v1::Event,
2219 _: &(),
2220 _: &Connection,
2221 _: &QueueHandle<Self>,
2222 ) {
2223 let client = this.get_client();
2224 let mut state = client.borrow_mut();
2225
2226 if let zwp_primary_selection_offer_v1::Event::Offer { mime_type } = event
2227 && let Some(offer) = state.primary_data_offer.as_mut()
2228 {
2229 offer.add_mime_type(mime_type);
2230 }
2231 }
2232}
2233
2234impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2235 for WaylandClientStatePtr
2236{
2237 fn event(
2238 this: &mut Self,
2239 selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2240 event: zwp_primary_selection_source_v1::Event,
2241 _: &(),
2242 _: &Connection,
2243 _: &QueueHandle<Self>,
2244 ) {
2245 let client = this.get_client();
2246 let mut state = client.borrow_mut();
2247
2248 match event {
2249 zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2250 state.clipboard.send_primary(mime_type, fd);
2251 }
2252 zwp_primary_selection_source_v1::Event::Cancelled => {
2253 selection_source.destroy();
2254 }
2255 _ => {}
2256 }
2257 }
2258}
2259
2260impl Dispatch<XdgWmDialogV1, ()> for WaylandClientStatePtr {
2261 fn event(
2262 _: &mut Self,
2263 _: &XdgWmDialogV1,
2264 _: <XdgWmDialogV1 as Proxy>::Event,
2265 _: &(),
2266 _: &Connection,
2267 _: &QueueHandle<Self>,
2268 ) {
2269 }
2270}
2271
2272impl Dispatch<XdgDialogV1, ()> for WaylandClientStatePtr {
2273 fn event(
2274 _state: &mut Self,
2275 _proxy: &XdgDialogV1,
2276 _event: <XdgDialogV1 as Proxy>::Event,
2277 _data: &(),
2278 _conn: &Connection,
2279 _qhandle: &QueueHandle<Self>,
2280 ) {
2281 }
2282}