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