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