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