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