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