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