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