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 println!("\n==> Wayland Key event: {:#?}", key_state);
1299 state.serial_tracker.update(SerialKind::KeyPress, serial);
1300
1301 let focused_window = state.keyboard_focused_window.clone();
1302 let Some(focused_window) = focused_window else {
1303 return;
1304 };
1305 let focused_window = focused_window.clone();
1306
1307 let keymap_state = state.keymap_state.as_ref().unwrap();
1308 let keyboard_mapper = state.keyboard_mapper.as_ref().unwrap();
1309 let keycode = Keycode::from(key + MIN_KEYCODE);
1310 let keysym = keymap_state.key_get_one_sym(keycode);
1311
1312 println!("is modifier key: {}", keysym.is_modifier_key());
1313 match key_state {
1314 wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1315 let mut keystroke = Keystroke::from_xkb(
1316 keymap_state,
1317 keyboard_mapper,
1318 state.modifiers,
1319 keycode,
1320 );
1321 println!("Wayland Before {:#?}", keystroke);
1322 if let Some(mut compose) = state.compose_state.take() {
1323 compose.feed(keysym);
1324 match compose.status() {
1325 xkb::Status::Composing => {
1326 keystroke.key_char = None;
1327 state.pre_edit_text =
1328 compose.utf8().or(underlying_dead_key(keysym));
1329 let pre_edit =
1330 state.pre_edit_text.clone().unwrap_or(String::default());
1331 drop(state);
1332 focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1333 state = client.borrow_mut();
1334 }
1335
1336 xkb::Status::Composed => {
1337 state.pre_edit_text.take();
1338 keystroke.key_char = compose.utf8();
1339 if let Some(keysym) = compose.keysym() {
1340 keystroke.key = xkb::keysym_get_name(keysym);
1341 }
1342 }
1343 xkb::Status::Cancelled => {
1344 let pre_edit = state.pre_edit_text.take();
1345 let new_pre_edit = underlying_dead_key(keysym);
1346 state.pre_edit_text = new_pre_edit.clone();
1347 drop(state);
1348 if let Some(pre_edit) = pre_edit {
1349 focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1350 }
1351 if let Some(current_key) = new_pre_edit {
1352 focused_window
1353 .handle_ime(ImeInput::SetMarkedText(current_key));
1354 }
1355 compose.feed(keysym);
1356 state = client.borrow_mut();
1357 }
1358 _ => {}
1359 }
1360 state.compose_state = Some(compose);
1361 }
1362 println!("Wayland Key pressed: {:#?}", keystroke);
1363 let input = PlatformInput::KeyDown(KeyDownEvent {
1364 keystroke: keystroke.clone(),
1365 is_held: false,
1366 });
1367
1368 state.repeat.current_id += 1;
1369 state.repeat.current_keycode = Some(keycode);
1370
1371 let rate = state.repeat.characters_per_second;
1372 let id = state.repeat.current_id;
1373 state
1374 .loop_handle
1375 .insert_source(Timer::from_duration(state.repeat.delay), {
1376 let input = PlatformInput::KeyDown(KeyDownEvent {
1377 keystroke,
1378 is_held: true,
1379 });
1380 move |_event, _metadata, this| {
1381 let mut client = this.get_client();
1382 let mut state = client.borrow_mut();
1383 let is_repeating = id == state.repeat.current_id
1384 && state.repeat.current_keycode.is_some()
1385 && state.keyboard_focused_window.is_some();
1386
1387 if !is_repeating || rate == 0 {
1388 return TimeoutAction::Drop;
1389 }
1390
1391 let focused_window =
1392 state.keyboard_focused_window.as_ref().unwrap().clone();
1393
1394 drop(state);
1395 focused_window.handle_input(input.clone());
1396
1397 TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
1398 }
1399 })
1400 .unwrap();
1401
1402 drop(state);
1403 focused_window.handle_input(input);
1404 }
1405 wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1406 let input = PlatformInput::KeyUp(KeyUpEvent {
1407 keystroke: Keystroke::from_xkb(
1408 keymap_state,
1409 keyboard_mapper,
1410 state.modifiers,
1411 keycode,
1412 ),
1413 });
1414
1415 if state.repeat.current_keycode == Some(keycode) {
1416 state.repeat.current_keycode = None;
1417 }
1418
1419 println!("\nWayland Key released: {:#?}", input);
1420 drop(state);
1421 focused_window.handle_input(input);
1422 }
1423 _ => {}
1424 }
1425 }
1426 _ => {}
1427 }
1428 }
1429}
1430
1431impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1432 fn event(
1433 this: &mut Self,
1434 text_input: &zwp_text_input_v3::ZwpTextInputV3,
1435 event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1436 _: &(),
1437 _: &Connection,
1438 _: &QueueHandle<Self>,
1439 ) {
1440 let client = this.get_client();
1441 let mut state = client.borrow_mut();
1442 match event {
1443 zwp_text_input_v3::Event::Enter { .. } => {
1444 drop(state);
1445 this.enable_ime();
1446 }
1447 zwp_text_input_v3::Event::Leave { .. } => {
1448 drop(state);
1449 this.disable_ime();
1450 }
1451 zwp_text_input_v3::Event::CommitString { text } => {
1452 state.composing = false;
1453 let Some(window) = state.keyboard_focused_window.clone() else {
1454 return;
1455 };
1456
1457 if let Some(commit_text) = text {
1458 drop(state);
1459 // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1460 // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1461 if commit_text.len() == 1 {
1462 window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1463 keystroke: Keystroke {
1464 modifiers: Modifiers::default(),
1465 key: commit_text.clone(),
1466 key_char: Some(commit_text),
1467 },
1468 is_held: false,
1469 }));
1470 } else {
1471 window.handle_ime(ImeInput::InsertText(commit_text));
1472 }
1473 }
1474 }
1475 zwp_text_input_v3::Event::PreeditString { text, .. } => {
1476 state.composing = true;
1477 state.ime_pre_edit = text;
1478 }
1479 zwp_text_input_v3::Event::Done { serial } => {
1480 let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1481 state.serial_tracker.update(SerialKind::InputMethod, serial);
1482 let Some(window) = state.keyboard_focused_window.clone() else {
1483 return;
1484 };
1485
1486 if let Some(text) = state.ime_pre_edit.take() {
1487 drop(state);
1488 window.handle_ime(ImeInput::SetMarkedText(text));
1489 if let Some(area) = window.get_ime_area() {
1490 text_input.set_cursor_rectangle(
1491 area.origin.x.0 as i32,
1492 area.origin.y.0 as i32,
1493 area.size.width.0 as i32,
1494 area.size.height.0 as i32,
1495 );
1496 if last_serial == serial {
1497 text_input.commit();
1498 }
1499 }
1500 } else {
1501 state.composing = false;
1502 drop(state);
1503 window.handle_ime(ImeInput::DeleteText);
1504 }
1505 }
1506 _ => {}
1507 }
1508 }
1509}
1510
1511fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1512 // These values are coming from <linux/input-event-codes.h>.
1513 const BTN_LEFT: u32 = 0x110;
1514 const BTN_RIGHT: u32 = 0x111;
1515 const BTN_MIDDLE: u32 = 0x112;
1516 const BTN_SIDE: u32 = 0x113;
1517 const BTN_EXTRA: u32 = 0x114;
1518 const BTN_FORWARD: u32 = 0x115;
1519 const BTN_BACK: u32 = 0x116;
1520
1521 Some(match button {
1522 BTN_LEFT => MouseButton::Left,
1523 BTN_RIGHT => MouseButton::Right,
1524 BTN_MIDDLE => MouseButton::Middle,
1525 BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1526 BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1527 _ => return None,
1528 })
1529}
1530
1531impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1532 fn event(
1533 this: &mut Self,
1534 wl_pointer: &wl_pointer::WlPointer,
1535 event: wl_pointer::Event,
1536 _: &(),
1537 _: &Connection,
1538 _: &QueueHandle<Self>,
1539 ) {
1540 let mut client = this.get_client();
1541 let mut state = client.borrow_mut();
1542
1543 match event {
1544 wl_pointer::Event::Enter {
1545 serial,
1546 surface,
1547 surface_x,
1548 surface_y,
1549 ..
1550 } => {
1551 state.serial_tracker.update(SerialKind::MouseEnter, serial);
1552 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1553 state.button_pressed = None;
1554
1555 if let Some(window) = get_window(&mut state, &surface.id()) {
1556 state.mouse_focused_window = Some(window.clone());
1557
1558 if state.enter_token.is_some() {
1559 state.enter_token = None;
1560 }
1561 if let Some(style) = state.cursor_style {
1562 if let CursorStyle::None = style {
1563 let wl_pointer = state
1564 .wl_pointer
1565 .clone()
1566 .expect("window is focused by pointer");
1567 wl_pointer.set_cursor(serial, None, 0, 0);
1568 } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1569 cursor_shape_device.set_shape(serial, style.to_shape());
1570 } else {
1571 let scale = window.primary_output_scale();
1572 state.cursor.set_icon(
1573 &wl_pointer,
1574 serial,
1575 style.to_icon_names(),
1576 scale,
1577 );
1578 }
1579 }
1580 drop(state);
1581 window.set_hovered(true);
1582 }
1583 }
1584 wl_pointer::Event::Leave { .. } => {
1585 if let Some(focused_window) = state.mouse_focused_window.clone() {
1586 let input = PlatformInput::MouseExited(MouseExitEvent {
1587 position: state.mouse_location.unwrap(),
1588 pressed_button: state.button_pressed,
1589 modifiers: state.modifiers,
1590 });
1591 state.mouse_focused_window = None;
1592 state.mouse_location = None;
1593 state.button_pressed = None;
1594
1595 drop(state);
1596 focused_window.handle_input(input);
1597 focused_window.set_hovered(false);
1598 }
1599 }
1600 wl_pointer::Event::Motion {
1601 surface_x,
1602 surface_y,
1603 ..
1604 } => {
1605 if state.mouse_focused_window.is_none() {
1606 return;
1607 }
1608 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1609
1610 if let Some(window) = state.mouse_focused_window.clone() {
1611 if state
1612 .keyboard_focused_window
1613 .as_ref()
1614 .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1615 {
1616 state.enter_token = None;
1617 }
1618 let input = PlatformInput::MouseMove(MouseMoveEvent {
1619 position: state.mouse_location.unwrap(),
1620 pressed_button: state.button_pressed,
1621 modifiers: state.modifiers,
1622 });
1623 drop(state);
1624 window.handle_input(input);
1625 }
1626 }
1627 wl_pointer::Event::Button {
1628 serial,
1629 button,
1630 state: WEnum::Value(button_state),
1631 ..
1632 } => {
1633 state.serial_tracker.update(SerialKind::MousePress, serial);
1634 let button = linux_button_to_gpui(button);
1635 let Some(button) = button else { return };
1636 if state.mouse_focused_window.is_none() {
1637 return;
1638 }
1639 match button_state {
1640 wl_pointer::ButtonState::Pressed => {
1641 if let Some(window) = state.keyboard_focused_window.clone() {
1642 if state.composing && state.text_input.is_some() {
1643 drop(state);
1644 // text_input_v3 don't have something like a reset function
1645 this.disable_ime();
1646 this.enable_ime();
1647 window.handle_ime(ImeInput::UnmarkText);
1648 state = client.borrow_mut();
1649 } else if let (Some(text), Some(compose)) =
1650 (state.pre_edit_text.take(), state.compose_state.as_mut())
1651 {
1652 compose.reset();
1653 drop(state);
1654 window.handle_ime(ImeInput::InsertText(text));
1655 state = client.borrow_mut();
1656 }
1657 }
1658 let click_elapsed = state.click.last_click.elapsed();
1659
1660 if click_elapsed < DOUBLE_CLICK_INTERVAL
1661 && state
1662 .click
1663 .last_mouse_button
1664 .is_some_and(|prev_button| prev_button == button)
1665 && is_within_click_distance(
1666 state.click.last_location,
1667 state.mouse_location.unwrap(),
1668 )
1669 {
1670 state.click.current_count += 1;
1671 } else {
1672 state.click.current_count = 1;
1673 }
1674
1675 state.click.last_click = Instant::now();
1676 state.click.last_mouse_button = Some(button);
1677 state.click.last_location = state.mouse_location.unwrap();
1678
1679 state.button_pressed = Some(button);
1680
1681 if let Some(window) = state.mouse_focused_window.clone() {
1682 let input = PlatformInput::MouseDown(MouseDownEvent {
1683 button,
1684 position: state.mouse_location.unwrap(),
1685 modifiers: state.modifiers,
1686 click_count: state.click.current_count,
1687 first_mouse: state.enter_token.take().is_some(),
1688 });
1689 drop(state);
1690 window.handle_input(input);
1691 }
1692 }
1693 wl_pointer::ButtonState::Released => {
1694 state.button_pressed = None;
1695
1696 if let Some(window) = state.mouse_focused_window.clone() {
1697 let input = PlatformInput::MouseUp(MouseUpEvent {
1698 button,
1699 position: state.mouse_location.unwrap(),
1700 modifiers: state.modifiers,
1701 click_count: state.click.current_count,
1702 });
1703 drop(state);
1704 window.handle_input(input);
1705 }
1706 }
1707 _ => {}
1708 }
1709 }
1710
1711 // Axis Events
1712 wl_pointer::Event::AxisSource {
1713 axis_source: WEnum::Value(axis_source),
1714 } => {
1715 state.axis_source = axis_source;
1716 }
1717 wl_pointer::Event::Axis {
1718 axis: WEnum::Value(axis),
1719 value,
1720 ..
1721 } => {
1722 if state.axis_source == AxisSource::Wheel {
1723 return;
1724 }
1725 let axis = if state.modifiers.shift {
1726 wl_pointer::Axis::HorizontalScroll
1727 } else {
1728 axis
1729 };
1730 let axis_modifier = match axis {
1731 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1732 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1733 _ => 1.0,
1734 };
1735 state.scroll_event_received = true;
1736 let scroll_delta = state
1737 .continuous_scroll_delta
1738 .get_or_insert(point(px(0.0), px(0.0)));
1739 let modifier = 3.0;
1740 match axis {
1741 wl_pointer::Axis::VerticalScroll => {
1742 scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1743 }
1744 wl_pointer::Axis::HorizontalScroll => {
1745 scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1746 }
1747 _ => unreachable!(),
1748 }
1749 }
1750 wl_pointer::Event::AxisDiscrete {
1751 axis: WEnum::Value(axis),
1752 discrete,
1753 } => {
1754 state.scroll_event_received = true;
1755 let axis = if state.modifiers.shift {
1756 wl_pointer::Axis::HorizontalScroll
1757 } else {
1758 axis
1759 };
1760 let axis_modifier = match axis {
1761 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1762 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1763 _ => 1.0,
1764 };
1765
1766 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1767 match axis {
1768 wl_pointer::Axis::VerticalScroll => {
1769 scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1770 }
1771 wl_pointer::Axis::HorizontalScroll => {
1772 scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1773 }
1774 _ => unreachable!(),
1775 }
1776 }
1777 wl_pointer::Event::AxisValue120 {
1778 axis: WEnum::Value(axis),
1779 value120,
1780 } => {
1781 state.scroll_event_received = true;
1782 let axis = if state.modifiers.shift {
1783 wl_pointer::Axis::HorizontalScroll
1784 } else {
1785 axis
1786 };
1787 let axis_modifier = match axis {
1788 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1789 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1790 _ => unreachable!(),
1791 };
1792
1793 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1794 let wheel_percent = value120 as f32 / 120.0;
1795 match axis {
1796 wl_pointer::Axis::VerticalScroll => {
1797 scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1798 }
1799 wl_pointer::Axis::HorizontalScroll => {
1800 scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1801 }
1802 _ => unreachable!(),
1803 }
1804 }
1805 wl_pointer::Event::Frame => {
1806 if state.scroll_event_received {
1807 state.scroll_event_received = false;
1808 let continuous = state.continuous_scroll_delta.take();
1809 let discrete = state.discrete_scroll_delta.take();
1810 if let Some(continuous) = continuous {
1811 if let Some(window) = state.mouse_focused_window.clone() {
1812 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1813 position: state.mouse_location.unwrap(),
1814 delta: ScrollDelta::Pixels(continuous),
1815 modifiers: state.modifiers,
1816 touch_phase: TouchPhase::Moved,
1817 });
1818 drop(state);
1819 window.handle_input(input);
1820 }
1821 } else if let Some(discrete) = discrete {
1822 if let Some(window) = state.mouse_focused_window.clone() {
1823 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1824 position: state.mouse_location.unwrap(),
1825 delta: ScrollDelta::Lines(discrete),
1826 modifiers: state.modifiers,
1827 touch_phase: TouchPhase::Moved,
1828 });
1829 drop(state);
1830 window.handle_input(input);
1831 }
1832 }
1833 }
1834 }
1835 _ => {}
1836 }
1837 }
1838}
1839
1840impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1841 fn event(
1842 this: &mut Self,
1843 _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1844 event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1845 surface_id: &ObjectId,
1846 _: &Connection,
1847 _: &QueueHandle<Self>,
1848 ) {
1849 let client = this.get_client();
1850 let mut state = client.borrow_mut();
1851
1852 let Some(window) = get_window(&mut state, surface_id) else {
1853 return;
1854 };
1855
1856 drop(state);
1857 window.handle_fractional_scale_event(event);
1858 }
1859}
1860
1861impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1862 for WaylandClientStatePtr
1863{
1864 fn event(
1865 this: &mut Self,
1866 _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1867 event: zxdg_toplevel_decoration_v1::Event,
1868 surface_id: &ObjectId,
1869 _: &Connection,
1870 _: &QueueHandle<Self>,
1871 ) {
1872 let client = this.get_client();
1873 let mut state = client.borrow_mut();
1874 let Some(window) = get_window(&mut state, surface_id) else {
1875 return;
1876 };
1877
1878 drop(state);
1879 window.handle_toplevel_decoration_event(event);
1880 }
1881}
1882
1883impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1884 fn event(
1885 this: &mut Self,
1886 _: &wl_data_device::WlDataDevice,
1887 event: wl_data_device::Event,
1888 _: &(),
1889 _: &Connection,
1890 _: &QueueHandle<Self>,
1891 ) {
1892 let client = this.get_client();
1893 let mut state = client.borrow_mut();
1894
1895 match event {
1896 // Clipboard
1897 wl_data_device::Event::DataOffer { id: data_offer } => {
1898 state.data_offers.push(DataOffer::new(data_offer));
1899 if state.data_offers.len() > 2 {
1900 // At most we store a clipboard offer and a drag and drop offer.
1901 state.data_offers.remove(0).inner.destroy();
1902 }
1903 }
1904 wl_data_device::Event::Selection { id: data_offer } => {
1905 if let Some(offer) = data_offer {
1906 let offer = state
1907 .data_offers
1908 .iter()
1909 .find(|wrapper| wrapper.inner.id() == offer.id());
1910 let offer = offer.cloned();
1911 state.clipboard.set_offer(offer);
1912 } else {
1913 state.clipboard.set_offer(None);
1914 }
1915 }
1916
1917 // Drag and drop
1918 wl_data_device::Event::Enter {
1919 serial,
1920 surface,
1921 x,
1922 y,
1923 id: data_offer,
1924 } => {
1925 state.serial_tracker.update(SerialKind::DataDevice, serial);
1926 if let Some(data_offer) = data_offer {
1927 let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1928 return;
1929 };
1930
1931 const ACTIONS: DndAction = DndAction::Copy;
1932 data_offer.set_actions(ACTIONS, ACTIONS);
1933
1934 let pipe = Pipe::new().unwrap();
1935 data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1936 BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1937 });
1938 let fd = pipe.read;
1939 drop(pipe.write);
1940
1941 let read_task = state.common.background_executor.spawn(async {
1942 let buffer = unsafe { read_fd(fd)? };
1943 let text = String::from_utf8(buffer)?;
1944 anyhow::Ok(text)
1945 });
1946
1947 let this = this.clone();
1948 state
1949 .common
1950 .foreground_executor
1951 .spawn(async move {
1952 let file_list = match read_task.await {
1953 Ok(list) => list,
1954 Err(err) => {
1955 log::error!("error reading drag and drop pipe: {err:?}");
1956 return;
1957 }
1958 };
1959
1960 let paths: SmallVec<[_; 2]> = file_list
1961 .lines()
1962 .filter_map(|path| Url::parse(path).log_err())
1963 .filter_map(|url| url.to_file_path().log_err())
1964 .collect();
1965 let position = Point::new(x.into(), y.into());
1966
1967 // Prevent dropping text from other programs.
1968 if paths.is_empty() {
1969 data_offer.destroy();
1970 return;
1971 }
1972
1973 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1974 position,
1975 paths: crate::ExternalPaths(paths),
1976 });
1977
1978 let client = this.get_client();
1979 let mut state = client.borrow_mut();
1980 state.drag.data_offer = Some(data_offer);
1981 state.drag.window = Some(drag_window.clone());
1982 state.drag.position = position;
1983
1984 drop(state);
1985 drag_window.handle_input(input);
1986 })
1987 .detach();
1988 }
1989 }
1990 wl_data_device::Event::Motion { x, y, .. } => {
1991 let Some(drag_window) = state.drag.window.clone() else {
1992 return;
1993 };
1994 let position = Point::new(x.into(), y.into());
1995 state.drag.position = position;
1996
1997 let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1998 drop(state);
1999 drag_window.handle_input(input);
2000 }
2001 wl_data_device::Event::Leave => {
2002 let Some(drag_window) = state.drag.window.clone() else {
2003 return;
2004 };
2005 let data_offer = state.drag.data_offer.clone().unwrap();
2006 data_offer.destroy();
2007
2008 state.drag.data_offer = None;
2009 state.drag.window = None;
2010
2011 let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
2012 drop(state);
2013 drag_window.handle_input(input);
2014 }
2015 wl_data_device::Event::Drop => {
2016 let Some(drag_window) = state.drag.window.clone() else {
2017 return;
2018 };
2019 let data_offer = state.drag.data_offer.clone().unwrap();
2020 data_offer.finish();
2021 data_offer.destroy();
2022
2023 state.drag.data_offer = None;
2024 state.drag.window = None;
2025
2026 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
2027 position: state.drag.position,
2028 });
2029 drop(state);
2030 drag_window.handle_input(input);
2031 }
2032 _ => {}
2033 }
2034 }
2035
2036 event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
2037 wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
2038 ]);
2039}
2040
2041impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
2042 fn event(
2043 this: &mut Self,
2044 data_offer: &wl_data_offer::WlDataOffer,
2045 event: wl_data_offer::Event,
2046 _: &(),
2047 _: &Connection,
2048 _: &QueueHandle<Self>,
2049 ) {
2050 let client = this.get_client();
2051 let mut state = client.borrow_mut();
2052
2053 match event {
2054 wl_data_offer::Event::Offer { mime_type } => {
2055 // Drag and drop
2056 if mime_type == FILE_LIST_MIME_TYPE {
2057 let serial = state.serial_tracker.get(SerialKind::DataDevice);
2058 let mime_type = mime_type.clone();
2059 data_offer.accept(serial, Some(mime_type));
2060 }
2061
2062 // Clipboard
2063 if let Some(offer) = state
2064 .data_offers
2065 .iter_mut()
2066 .find(|wrapper| wrapper.inner.id() == data_offer.id())
2067 {
2068 offer.add_mime_type(mime_type);
2069 }
2070 }
2071 _ => {}
2072 }
2073 }
2074}
2075
2076impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
2077 fn event(
2078 this: &mut Self,
2079 data_source: &wl_data_source::WlDataSource,
2080 event: wl_data_source::Event,
2081 _: &(),
2082 _: &Connection,
2083 _: &QueueHandle<Self>,
2084 ) {
2085 let client = this.get_client();
2086 let mut state = client.borrow_mut();
2087
2088 match event {
2089 wl_data_source::Event::Send { mime_type, fd } => {
2090 state.clipboard.send(mime_type, fd);
2091 }
2092 wl_data_source::Event::Cancelled => {
2093 data_source.destroy();
2094 }
2095 _ => {}
2096 }
2097 }
2098}
2099
2100impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2101 for WaylandClientStatePtr
2102{
2103 fn event(
2104 this: &mut Self,
2105 _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2106 event: zwp_primary_selection_device_v1::Event,
2107 _: &(),
2108 _: &Connection,
2109 _: &QueueHandle<Self>,
2110 ) {
2111 let client = this.get_client();
2112 let mut state = client.borrow_mut();
2113
2114 match event {
2115 zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2116 let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2117 if let Some(old_offer) = old_offer {
2118 old_offer.inner.destroy();
2119 }
2120 }
2121 zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2122 if data_offer.is_some() {
2123 let offer = state.primary_data_offer.clone();
2124 state.clipboard.set_primary_offer(offer);
2125 } else {
2126 state.clipboard.set_primary_offer(None);
2127 }
2128 }
2129 _ => {}
2130 }
2131 }
2132
2133 event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2134 zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2135 ]);
2136}
2137
2138impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2139 for WaylandClientStatePtr
2140{
2141 fn event(
2142 this: &mut Self,
2143 _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2144 event: zwp_primary_selection_offer_v1::Event,
2145 _: &(),
2146 _: &Connection,
2147 _: &QueueHandle<Self>,
2148 ) {
2149 let client = this.get_client();
2150 let mut state = client.borrow_mut();
2151
2152 match event {
2153 zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
2154 if let Some(offer) = state.primary_data_offer.as_mut() {
2155 offer.add_mime_type(mime_type);
2156 }
2157 }
2158 _ => {}
2159 }
2160 }
2161}
2162
2163impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2164 for WaylandClientStatePtr
2165{
2166 fn event(
2167 this: &mut Self,
2168 selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2169 event: zwp_primary_selection_source_v1::Event,
2170 _: &(),
2171 _: &Connection,
2172 _: &QueueHandle<Self>,
2173 ) {
2174 let client = this.get_client();
2175 let mut state = client.borrow_mut();
2176
2177 match event {
2178 zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2179 state.clipboard.send_primary(mime_type, fd);
2180 }
2181 zwp_primary_selection_source_v1::Event::Cancelled => {
2182 selection_source.destroy();
2183 }
2184 _ => {}
2185 }
2186 }
2187}
2188
2189fn update_keyboard_mapper(
2190 client: &mut WaylandClientState,
2191 keyboard_layout: LinuxKeyboardLayout,
2192 group: u32,
2193) {
2194 client.keyboard_mapper =
2195 if let Some(mapper) = client.keyboard_mapper_cache.get(keyboard_layout.id()) {
2196 Some(mapper.clone())
2197 } else {
2198 let mapper = Rc::new(LinuxKeyboardMapper::new(0, 0, group));
2199 client.keyboard_mapper = Some(mapper.clone());
2200 client
2201 .keyboard_mapper_cache
2202 .insert(keyboard_layout.id().to_string(), mapper.clone());
2203 Some(mapper)
2204 };
2205 client.keyboard_layout = Box::new(keyboard_layout);
2206}