forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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