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::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 state.clipboard.set_offer(None);
1124
1125 if let Some(window) = keyboard_focused_window {
1126 if let Some(ref mut compose) = state.compose_state {
1127 compose.reset();
1128 }
1129 state.pre_edit_text.take();
1130 drop(state);
1131 window.handle_ime(ImeInput::DeleteText);
1132 window.set_focused(false);
1133 }
1134 }
1135 wl_keyboard::Event::Modifiers {
1136 mods_depressed,
1137 mods_latched,
1138 mods_locked,
1139 group,
1140 ..
1141 } => {
1142 let focused_window = state.keyboard_focused_window.clone();
1143
1144 let keymap_state = state.keymap_state.as_mut().unwrap();
1145 keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1146 state.modifiers = Modifiers::from_xkb(keymap_state);
1147
1148 let Some(focused_window) = focused_window else {
1149 return;
1150 };
1151
1152 let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1153 modifiers: state.modifiers,
1154 });
1155
1156 drop(state);
1157 focused_window.handle_input(input);
1158 }
1159 wl_keyboard::Event::Key {
1160 serial,
1161 key,
1162 state: WEnum::Value(key_state),
1163 ..
1164 } => {
1165 state.serial_tracker.update(SerialKind::KeyPress, serial);
1166
1167 let focused_window = state.keyboard_focused_window.clone();
1168 let Some(focused_window) = focused_window else {
1169 return;
1170 };
1171 let focused_window = focused_window.clone();
1172
1173 let keymap_state = state.keymap_state.as_ref().unwrap();
1174 let keycode = Keycode::from(key + MIN_KEYCODE);
1175 let keysym = keymap_state.key_get_one_sym(keycode);
1176
1177 match key_state {
1178 wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1179 let mut keystroke =
1180 Keystroke::from_xkb(&keymap_state, state.modifiers, keycode);
1181 if let Some(mut compose) = state.compose_state.take() {
1182 compose.feed(keysym);
1183 match compose.status() {
1184 xkb::Status::Composing => {
1185 keystroke.ime_key = None;
1186 state.pre_edit_text =
1187 compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1188 let pre_edit =
1189 state.pre_edit_text.clone().unwrap_or(String::default());
1190 drop(state);
1191 focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1192 state = client.borrow_mut();
1193 }
1194
1195 xkb::Status::Composed => {
1196 state.pre_edit_text.take();
1197 keystroke.ime_key = compose.utf8();
1198 if let Some(keysym) = compose.keysym() {
1199 keystroke.key = xkb::keysym_get_name(keysym);
1200 }
1201 }
1202 xkb::Status::Cancelled => {
1203 let pre_edit = state.pre_edit_text.take();
1204 drop(state);
1205 if let Some(pre_edit) = pre_edit {
1206 focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1207 }
1208 if let Some(current_key) =
1209 Keystroke::underlying_dead_key(keysym)
1210 {
1211 focused_window
1212 .handle_ime(ImeInput::SetMarkedText(current_key));
1213 }
1214 compose.feed(keysym);
1215 state = client.borrow_mut();
1216 }
1217 _ => {}
1218 }
1219 state.compose_state = Some(compose);
1220 }
1221 let input = PlatformInput::KeyDown(KeyDownEvent {
1222 keystroke: keystroke.clone(),
1223 is_held: false,
1224 });
1225
1226 state.repeat.current_id += 1;
1227 state.repeat.current_keycode = Some(keycode);
1228
1229 let rate = state.repeat.characters_per_second;
1230 let id = state.repeat.current_id;
1231 state
1232 .loop_handle
1233 .insert_source(Timer::from_duration(state.repeat.delay), {
1234 let input = PlatformInput::KeyDown(KeyDownEvent {
1235 keystroke,
1236 is_held: true,
1237 });
1238 move |_event, _metadata, this| {
1239 let mut client = this.get_client();
1240 let mut state = client.borrow_mut();
1241 let is_repeating = id == state.repeat.current_id
1242 && state.repeat.current_keycode.is_some()
1243 && state.keyboard_focused_window.is_some();
1244
1245 if !is_repeating || rate == 0 {
1246 return TimeoutAction::Drop;
1247 }
1248
1249 let focused_window =
1250 state.keyboard_focused_window.as_ref().unwrap().clone();
1251
1252 drop(state);
1253 focused_window.handle_input(input.clone());
1254
1255 TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
1256 }
1257 })
1258 .unwrap();
1259
1260 drop(state);
1261 focused_window.handle_input(input);
1262 }
1263 wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1264 let input = PlatformInput::KeyUp(KeyUpEvent {
1265 keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
1266 });
1267
1268 if state.repeat.current_keycode == Some(keycode) {
1269 state.repeat.current_keycode = None;
1270 }
1271
1272 drop(state);
1273 focused_window.handle_input(input);
1274 }
1275 _ => {}
1276 }
1277 }
1278 _ => {}
1279 }
1280 }
1281}
1282impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1283 fn event(
1284 this: &mut Self,
1285 text_input: &zwp_text_input_v3::ZwpTextInputV3,
1286 event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1287 _: &(),
1288 _: &Connection,
1289 _: &QueueHandle<Self>,
1290 ) {
1291 let client = this.get_client();
1292 let mut state = client.borrow_mut();
1293 match event {
1294 zwp_text_input_v3::Event::Enter { .. } => {
1295 drop(state);
1296 this.enable_ime();
1297 }
1298 zwp_text_input_v3::Event::Leave { .. } => {
1299 drop(state);
1300 this.disable_ime();
1301 }
1302 zwp_text_input_v3::Event::CommitString { text } => {
1303 state.composing = false;
1304 let Some(window) = state.keyboard_focused_window.clone() else {
1305 return;
1306 };
1307
1308 if let Some(commit_text) = text {
1309 drop(state);
1310 // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1311 // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1312 if commit_text.len() == 1 {
1313 window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1314 keystroke: Keystroke {
1315 modifiers: Modifiers::default(),
1316 key: commit_text.clone(),
1317 ime_key: Some(commit_text),
1318 },
1319 is_held: false,
1320 }));
1321 } else {
1322 window.handle_ime(ImeInput::InsertText(commit_text));
1323 }
1324 }
1325 }
1326 zwp_text_input_v3::Event::PreeditString { text, .. } => {
1327 state.composing = true;
1328 state.pre_edit_text = text;
1329 }
1330 zwp_text_input_v3::Event::Done { serial } => {
1331 let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1332 state.serial_tracker.update(SerialKind::InputMethod, serial);
1333 let Some(window) = state.keyboard_focused_window.clone() else {
1334 return;
1335 };
1336
1337 if let Some(text) = state.pre_edit_text.take() {
1338 drop(state);
1339 window.handle_ime(ImeInput::SetMarkedText(text));
1340 if let Some(area) = window.get_ime_area() {
1341 text_input.set_cursor_rectangle(
1342 area.origin.x.0 as i32,
1343 area.origin.y.0 as i32,
1344 area.size.width.0 as i32,
1345 area.size.height.0 as i32,
1346 );
1347 if last_serial == serial {
1348 text_input.commit();
1349 }
1350 }
1351 } else {
1352 drop(state);
1353 window.handle_ime(ImeInput::DeleteText);
1354 }
1355 }
1356 _ => {}
1357 }
1358 }
1359}
1360
1361fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1362 // These values are coming from <linux/input-event-codes.h>.
1363 const BTN_LEFT: u32 = 0x110;
1364 const BTN_RIGHT: u32 = 0x111;
1365 const BTN_MIDDLE: u32 = 0x112;
1366 const BTN_SIDE: u32 = 0x113;
1367 const BTN_EXTRA: u32 = 0x114;
1368 const BTN_FORWARD: u32 = 0x115;
1369 const BTN_BACK: u32 = 0x116;
1370
1371 Some(match button {
1372 BTN_LEFT => MouseButton::Left,
1373 BTN_RIGHT => MouseButton::Right,
1374 BTN_MIDDLE => MouseButton::Middle,
1375 BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1376 BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1377 _ => return None,
1378 })
1379}
1380
1381impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1382 fn event(
1383 this: &mut Self,
1384 wl_pointer: &wl_pointer::WlPointer,
1385 event: wl_pointer::Event,
1386 _: &(),
1387 _: &Connection,
1388 _: &QueueHandle<Self>,
1389 ) {
1390 let mut client = this.get_client();
1391 let mut state = client.borrow_mut();
1392
1393 match event {
1394 wl_pointer::Event::Enter {
1395 serial,
1396 surface,
1397 surface_x,
1398 surface_y,
1399 ..
1400 } => {
1401 state.serial_tracker.update(SerialKind::MouseEnter, serial);
1402 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1403 state.button_pressed = None;
1404
1405 if let Some(window) = get_window(&mut state, &surface.id()) {
1406 state.mouse_focused_window = Some(window.clone());
1407 if state.enter_token.is_some() {
1408 state.enter_token = None;
1409 }
1410 if let Some(style) = state.cursor_style {
1411 if let Some(cursor_shape_device) = &state.cursor_shape_device {
1412 cursor_shape_device.set_shape(serial, style.to_shape());
1413 } else {
1414 state
1415 .cursor
1416 .set_icon(&wl_pointer, serial, &style.to_icon_name());
1417 }
1418 }
1419 drop(state);
1420 window.set_focused(true);
1421 }
1422 }
1423 wl_pointer::Event::Leave { .. } => {
1424 if let Some(focused_window) = state.mouse_focused_window.clone() {
1425 let input = PlatformInput::MouseExited(MouseExitEvent {
1426 position: state.mouse_location.unwrap(),
1427 pressed_button: state.button_pressed,
1428 modifiers: state.modifiers,
1429 });
1430 state.mouse_focused_window = None;
1431 state.mouse_location = None;
1432 state.button_pressed = None;
1433
1434 drop(state);
1435 focused_window.handle_input(input);
1436 focused_window.set_focused(false);
1437 }
1438 }
1439 wl_pointer::Event::Motion {
1440 surface_x,
1441 surface_y,
1442 ..
1443 } => {
1444 if state.mouse_focused_window.is_none() {
1445 return;
1446 }
1447 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1448
1449 if let Some(window) = state.mouse_focused_window.clone() {
1450 if state
1451 .keyboard_focused_window
1452 .as_ref()
1453 .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1454 {
1455 state.enter_token = None;
1456 }
1457 let input = PlatformInput::MouseMove(MouseMoveEvent {
1458 position: state.mouse_location.unwrap(),
1459 pressed_button: state.button_pressed,
1460 modifiers: state.modifiers,
1461 });
1462 drop(state);
1463 window.handle_input(input);
1464 }
1465 }
1466 wl_pointer::Event::Button {
1467 serial,
1468 button,
1469 state: WEnum::Value(button_state),
1470 ..
1471 } => {
1472 state.serial_tracker.update(SerialKind::MousePress, serial);
1473 let button = linux_button_to_gpui(button);
1474 let Some(button) = button else { return };
1475 if state.mouse_focused_window.is_none() {
1476 return;
1477 }
1478 match button_state {
1479 wl_pointer::ButtonState::Pressed => {
1480 if let Some(window) = state.keyboard_focused_window.clone() {
1481 if state.composing && state.text_input.is_some() {
1482 drop(state);
1483 // text_input_v3 don't have something like a reset function
1484 this.disable_ime();
1485 this.enable_ime();
1486 window.handle_ime(ImeInput::UnmarkText);
1487 state = client.borrow_mut();
1488 } else if let (Some(text), Some(compose)) =
1489 (state.pre_edit_text.take(), state.compose_state.as_mut())
1490 {
1491 compose.reset();
1492 drop(state);
1493 window.handle_ime(ImeInput::InsertText(text));
1494 state = client.borrow_mut();
1495 }
1496 }
1497 let click_elapsed = state.click.last_click.elapsed();
1498
1499 if click_elapsed < DOUBLE_CLICK_INTERVAL
1500 && is_within_click_distance(
1501 state.click.last_location,
1502 state.mouse_location.unwrap(),
1503 )
1504 {
1505 state.click.current_count += 1;
1506 } else {
1507 state.click.current_count = 1;
1508 }
1509
1510 state.click.last_click = Instant::now();
1511 state.click.last_location = state.mouse_location.unwrap();
1512
1513 state.button_pressed = Some(button);
1514
1515 if let Some(window) = state.mouse_focused_window.clone() {
1516 let input = PlatformInput::MouseDown(MouseDownEvent {
1517 button,
1518 position: state.mouse_location.unwrap(),
1519 modifiers: state.modifiers,
1520 click_count: state.click.current_count,
1521 first_mouse: state.enter_token.take().is_some(),
1522 });
1523 drop(state);
1524 window.handle_input(input);
1525 }
1526 }
1527 wl_pointer::ButtonState::Released => {
1528 state.button_pressed = None;
1529
1530 if let Some(window) = state.mouse_focused_window.clone() {
1531 let input = PlatformInput::MouseUp(MouseUpEvent {
1532 button,
1533 position: state.mouse_location.unwrap(),
1534 modifiers: state.modifiers,
1535 click_count: state.click.current_count,
1536 });
1537 drop(state);
1538 window.handle_input(input);
1539 }
1540 }
1541 _ => {}
1542 }
1543 }
1544
1545 // Axis Events
1546 wl_pointer::Event::AxisSource {
1547 axis_source: WEnum::Value(axis_source),
1548 } => {
1549 state.axis_source = axis_source;
1550 }
1551 wl_pointer::Event::Axis {
1552 axis: WEnum::Value(axis),
1553 value,
1554 ..
1555 } => {
1556 if state.axis_source == AxisSource::Wheel {
1557 return;
1558 }
1559 let axis = if state.modifiers.shift {
1560 wl_pointer::Axis::HorizontalScroll
1561 } else {
1562 axis
1563 };
1564 let axis_modifier = match axis {
1565 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1566 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1567 _ => 1.0,
1568 };
1569 state.scroll_event_received = true;
1570 let scroll_delta = state
1571 .continuous_scroll_delta
1572 .get_or_insert(point(px(0.0), px(0.0)));
1573 let modifier = 3.0;
1574 match axis {
1575 wl_pointer::Axis::VerticalScroll => {
1576 scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1577 }
1578 wl_pointer::Axis::HorizontalScroll => {
1579 scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1580 }
1581 _ => unreachable!(),
1582 }
1583 }
1584 wl_pointer::Event::AxisDiscrete {
1585 axis: WEnum::Value(axis),
1586 discrete,
1587 } => {
1588 state.scroll_event_received = true;
1589 let axis = if state.modifiers.shift {
1590 wl_pointer::Axis::HorizontalScroll
1591 } else {
1592 axis
1593 };
1594 let axis_modifier = match axis {
1595 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1596 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1597 _ => 1.0,
1598 };
1599
1600 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1601 match axis {
1602 wl_pointer::Axis::VerticalScroll => {
1603 scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES as f32;
1604 }
1605 wl_pointer::Axis::HorizontalScroll => {
1606 scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES as f32;
1607 }
1608 _ => unreachable!(),
1609 }
1610 }
1611 wl_pointer::Event::AxisValue120 {
1612 axis: WEnum::Value(axis),
1613 value120,
1614 } => {
1615 state.scroll_event_received = true;
1616 let axis = if state.modifiers.shift {
1617 wl_pointer::Axis::HorizontalScroll
1618 } else {
1619 axis
1620 };
1621 let axis_modifier = match axis {
1622 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1623 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1624 _ => unreachable!(),
1625 };
1626
1627 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1628 let wheel_percent = value120 as f32 / 120.0;
1629 match axis {
1630 wl_pointer::Axis::VerticalScroll => {
1631 scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES as f32;
1632 }
1633 wl_pointer::Axis::HorizontalScroll => {
1634 scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES as f32;
1635 }
1636 _ => unreachable!(),
1637 }
1638 }
1639 wl_pointer::Event::Frame => {
1640 if state.scroll_event_received {
1641 state.scroll_event_received = false;
1642 let continuous = state.continuous_scroll_delta.take();
1643 let discrete = state.discrete_scroll_delta.take();
1644 if let Some(continuous) = continuous {
1645 if let Some(window) = state.mouse_focused_window.clone() {
1646 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1647 position: state.mouse_location.unwrap(),
1648 delta: ScrollDelta::Pixels(continuous),
1649 modifiers: state.modifiers,
1650 touch_phase: TouchPhase::Moved,
1651 });
1652 drop(state);
1653 window.handle_input(input);
1654 }
1655 } else if let Some(discrete) = discrete {
1656 if let Some(window) = state.mouse_focused_window.clone() {
1657 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1658 position: state.mouse_location.unwrap(),
1659 delta: ScrollDelta::Lines(discrete),
1660 modifiers: state.modifiers,
1661 touch_phase: TouchPhase::Moved,
1662 });
1663 drop(state);
1664 window.handle_input(input);
1665 }
1666 }
1667 }
1668 }
1669 _ => {}
1670 }
1671 }
1672}
1673
1674impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1675 fn event(
1676 this: &mut Self,
1677 _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1678 event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1679 surface_id: &ObjectId,
1680 _: &Connection,
1681 _: &QueueHandle<Self>,
1682 ) {
1683 let client = this.get_client();
1684 let mut state = client.borrow_mut();
1685
1686 let Some(window) = get_window(&mut state, surface_id) else {
1687 return;
1688 };
1689
1690 drop(state);
1691 window.handle_fractional_scale_event(event);
1692 }
1693}
1694
1695impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1696 for WaylandClientStatePtr
1697{
1698 fn event(
1699 this: &mut Self,
1700 _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1701 event: zxdg_toplevel_decoration_v1::Event,
1702 surface_id: &ObjectId,
1703 _: &Connection,
1704 _: &QueueHandle<Self>,
1705 ) {
1706 let client = this.get_client();
1707 let mut state = client.borrow_mut();
1708 let Some(window) = get_window(&mut state, surface_id) else {
1709 return;
1710 };
1711
1712 drop(state);
1713 window.handle_toplevel_decoration_event(event);
1714 }
1715}
1716
1717impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1718 fn event(
1719 this: &mut Self,
1720 _: &wl_data_device::WlDataDevice,
1721 event: wl_data_device::Event,
1722 _: &(),
1723 _: &Connection,
1724 _: &QueueHandle<Self>,
1725 ) {
1726 let client = this.get_client();
1727 let mut state = client.borrow_mut();
1728
1729 match event {
1730 // Clipboard
1731 wl_data_device::Event::DataOffer { id: data_offer } => {
1732 state.data_offers.push(DataOffer::new(data_offer));
1733 if state.data_offers.len() > 2 {
1734 // At most we store a clipboard offer and a drag and drop offer.
1735 state.data_offers.remove(0).inner.destroy();
1736 }
1737 }
1738 wl_data_device::Event::Selection { id: data_offer } => {
1739 if let Some(offer) = data_offer {
1740 let offer = state
1741 .data_offers
1742 .iter()
1743 .find(|wrapper| wrapper.inner.id() == offer.id());
1744 let offer = offer.cloned();
1745 state.clipboard.set_offer(offer);
1746 } else {
1747 state.clipboard.set_offer(None);
1748 }
1749 }
1750
1751 // Drag and drop
1752 wl_data_device::Event::Enter {
1753 serial,
1754 surface,
1755 x,
1756 y,
1757 id: data_offer,
1758 } => {
1759 state.serial_tracker.update(SerialKind::DataDevice, serial);
1760 if let Some(data_offer) = data_offer {
1761 let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1762 return;
1763 };
1764
1765 const ACTIONS: DndAction = DndAction::Copy;
1766 data_offer.set_actions(ACTIONS, ACTIONS);
1767
1768 let pipe = Pipe::new().unwrap();
1769 data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1770 BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1771 });
1772 let fd = pipe.read;
1773 drop(pipe.write);
1774
1775 let read_task = state
1776 .common
1777 .background_executor
1778 .spawn(async { unsafe { read_fd(fd) } });
1779
1780 let this = this.clone();
1781 state
1782 .common
1783 .foreground_executor
1784 .spawn(async move {
1785 let file_list = match read_task.await {
1786 Ok(list) => list,
1787 Err(err) => {
1788 log::error!("error reading drag and drop pipe: {err:?}");
1789 return;
1790 }
1791 };
1792
1793 let paths: SmallVec<[_; 2]> = file_list
1794 .lines()
1795 .filter_map(|path| Url::parse(path).log_err())
1796 .filter_map(|url| url.to_file_path().log_err())
1797 .collect();
1798 let position = Point::new(x.into(), y.into());
1799
1800 // Prevent dropping text from other programs.
1801 if paths.is_empty() {
1802 data_offer.finish();
1803 data_offer.destroy();
1804 return;
1805 }
1806
1807 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1808 position,
1809 paths: crate::ExternalPaths(paths),
1810 });
1811
1812 let client = this.get_client();
1813 let mut state = client.borrow_mut();
1814 state.drag.data_offer = Some(data_offer);
1815 state.drag.window = Some(drag_window.clone());
1816 state.drag.position = position;
1817
1818 drop(state);
1819 drag_window.handle_input(input);
1820 })
1821 .detach();
1822 }
1823 }
1824 wl_data_device::Event::Motion { x, y, .. } => {
1825 let Some(drag_window) = state.drag.window.clone() else {
1826 return;
1827 };
1828 let position = Point::new(x.into(), y.into());
1829 state.drag.position = position;
1830
1831 let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1832 drop(state);
1833 drag_window.handle_input(input);
1834 }
1835 wl_data_device::Event::Leave => {
1836 let Some(drag_window) = state.drag.window.clone() else {
1837 return;
1838 };
1839 let data_offer = state.drag.data_offer.clone().unwrap();
1840 data_offer.destroy();
1841
1842 state.drag.data_offer = None;
1843 state.drag.window = None;
1844
1845 let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1846 drop(state);
1847 drag_window.handle_input(input);
1848 }
1849 wl_data_device::Event::Drop => {
1850 let Some(drag_window) = state.drag.window.clone() else {
1851 return;
1852 };
1853 let data_offer = state.drag.data_offer.clone().unwrap();
1854 data_offer.finish();
1855 data_offer.destroy();
1856
1857 state.drag.data_offer = None;
1858 state.drag.window = None;
1859
1860 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1861 position: state.drag.position,
1862 });
1863 drop(state);
1864 drag_window.handle_input(input);
1865 }
1866 _ => {}
1867 }
1868 }
1869
1870 event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
1871 wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
1872 ]);
1873}
1874
1875impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
1876 fn event(
1877 this: &mut Self,
1878 data_offer: &wl_data_offer::WlDataOffer,
1879 event: wl_data_offer::Event,
1880 _: &(),
1881 _: &Connection,
1882 _: &QueueHandle<Self>,
1883 ) {
1884 let client = this.get_client();
1885 let mut state = client.borrow_mut();
1886
1887 match event {
1888 wl_data_offer::Event::Offer { mime_type } => {
1889 // Drag and drop
1890 if mime_type == FILE_LIST_MIME_TYPE {
1891 let serial = state.serial_tracker.get(SerialKind::DataDevice);
1892 let mime_type = mime_type.clone();
1893 data_offer.accept(serial, Some(mime_type));
1894 }
1895
1896 // Clipboard
1897 if let Some(offer) = state
1898 .data_offers
1899 .iter_mut()
1900 .find(|wrapper| wrapper.inner.id() == data_offer.id())
1901 {
1902 offer.add_mime_type(mime_type);
1903 }
1904 }
1905 _ => {}
1906 }
1907 }
1908}
1909
1910impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
1911 fn event(
1912 this: &mut Self,
1913 data_source: &wl_data_source::WlDataSource,
1914 event: wl_data_source::Event,
1915 _: &(),
1916 _: &Connection,
1917 _: &QueueHandle<Self>,
1918 ) {
1919 let client = this.get_client();
1920 let mut state = client.borrow_mut();
1921
1922 match event {
1923 wl_data_source::Event::Send { mime_type, fd } => {
1924 state.clipboard.send(mime_type, fd);
1925 }
1926 wl_data_source::Event::Cancelled => {
1927 data_source.destroy();
1928 }
1929 _ => {}
1930 }
1931 }
1932}
1933
1934impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
1935 for WaylandClientStatePtr
1936{
1937 fn event(
1938 this: &mut Self,
1939 _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
1940 event: zwp_primary_selection_device_v1::Event,
1941 _: &(),
1942 _: &Connection,
1943 _: &QueueHandle<Self>,
1944 ) {
1945 let client = this.get_client();
1946 let mut state = client.borrow_mut();
1947
1948 match event {
1949 zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
1950 let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
1951 if let Some(old_offer) = old_offer {
1952 old_offer.inner.destroy();
1953 }
1954 }
1955 zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
1956 if data_offer.is_some() {
1957 let offer = state.primary_data_offer.clone();
1958 state.clipboard.set_primary_offer(offer);
1959 } else {
1960 state.clipboard.set_primary_offer(None);
1961 }
1962 }
1963 _ => {}
1964 }
1965 }
1966
1967 event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
1968 zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
1969 ]);
1970}
1971
1972impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
1973 for WaylandClientStatePtr
1974{
1975 fn event(
1976 this: &mut Self,
1977 _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
1978 event: zwp_primary_selection_offer_v1::Event,
1979 _: &(),
1980 _: &Connection,
1981 _: &QueueHandle<Self>,
1982 ) {
1983 let client = this.get_client();
1984 let mut state = client.borrow_mut();
1985
1986 match event {
1987 zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
1988 if let Some(offer) = state.primary_data_offer.as_mut() {
1989 offer.add_mime_type(mime_type);
1990 }
1991 }
1992 _ => {}
1993 }
1994 }
1995}
1996
1997impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
1998 for WaylandClientStatePtr
1999{
2000 fn event(
2001 this: &mut Self,
2002 selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2003 event: zwp_primary_selection_source_v1::Event,
2004 _: &(),
2005 _: &Connection,
2006 _: &QueueHandle<Self>,
2007 ) {
2008 let client = this.get_client();
2009 let mut state = client.borrow_mut();
2010
2011 match event {
2012 zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2013 state.clipboard.send_primary(mime_type, fd);
2014 }
2015 zwp_primary_selection_source_v1::Event::Cancelled => {
2016 selection_source.destroy();
2017 }
2018 _ => {}
2019 }
2020 }
2021}