Skip to main content

winit_wayland/
lib.rs

1//! # Winit's Wayland backend.
2//!
3//! **Note:** Windows don't appear on Wayland until you draw/present to them.
4//!
5//! By default, Winit loads system libraries using `dlopen`. This can be
6//! disabled by disabling the `"wayland-dlopen"` cargo feature.
7//!
8//! ## Client-side decorations
9//!
10//! Winit provides client-side decorations by default, but the behaviour can
11//! be controlled with the following feature flags:
12//!
13//! * `wayland-csd-adwaita` (default).
14//! * `wayland-csd-adwaita-crossfont`.
15//! * `wayland-csd-adwaita-notitle`.
16//! * `wayland-csd-adwaita-notitlebar`.
17
18#![allow(clippy::mutable_key_type)]
19#![warn(clippy::exhaustive_enums)]
20
21use std::ffi::c_void;
22use std::hash::BuildHasher;
23use std::ptr::NonNull;
24
25use dpi::{LogicalSize, PhysicalSize};
26use sctk::reexports::client::Proxy;
27use sctk::reexports::client::backend::ObjectId;
28use sctk::reexports::client::protocol::wl_surface::WlSurface;
29use sctk::shm::slot::{Buffer, CreateBufferError, SlotPool};
30use wayland_client::protocol::wl_shm::Format;
31use winit_core::data_transfer::DataTransferId;
32use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop;
33use winit_core::window::{
34    ActivationToken, PlatformWindowAttributes, Window as CoreWindow, WindowId,
35};
36
37macro_rules! os_error {
38    ($error:expr) => {{ winit_core::error::OsError::new(line!(), file!(), $error) }};
39}
40
41mod dnd;
42mod event_loop;
43mod output;
44mod popup;
45mod seat;
46mod state;
47mod types;
48mod window;
49
50pub use self::dnd::{DataOffer, DragSource, MimeData, MimeType};
51pub use self::event_loop::{ActiveEventLoop, EventLoop};
52pub use self::popup::Popup;
53pub use self::window::Window;
54
55/// Additional methods on [`ActiveEventLoop`] that are specific to Wayland.
56pub trait ActiveEventLoopExtWayland {
57    /// True if the [`ActiveEventLoop`] uses Wayland.
58    fn is_wayland(&self) -> bool;
59}
60
61impl ActiveEventLoopExtWayland for dyn CoreActiveEventLoop + '_ {
62    #[inline]
63    fn is_wayland(&self) -> bool {
64        self.cast_ref::<ActiveEventLoop>().is_some()
65    }
66}
67
68/// Additional methods on [`EventLoop`] that are specific to Wayland.
69pub trait EventLoopExtWayland {
70    /// True if the [`EventLoop`] uses Wayland.
71    fn is_wayland(&self) -> bool;
72}
73
74/// Additional methods when building event loop that are specific to Wayland.
75pub trait EventLoopBuilderExtWayland {
76    /// Force using Wayland.
77    fn with_wayland(&mut self) -> &mut Self;
78
79    /// Whether to allow the event loop to be created off of the main thread.
80    ///
81    /// By default, the window is only allowed to be created on the main
82    /// thread, to make platform compatibility easier.
83    fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
84}
85
86/// Additional methods on [`Window`] that are specific to Wayland.
87///
88/// [`Window`]: crate::window::Window
89pub trait WindowExtWayland {
90    /// Returns `xdg_toplevel` of the window or [`None`] if the window is X11 window.
91    fn xdg_toplevel(&self) -> Option<NonNull<c_void>>;
92}
93
94impl WindowExtWayland for dyn CoreWindow + '_ {
95    #[inline]
96    fn xdg_toplevel(&self) -> Option<NonNull<c_void>> {
97        self.cast_ref::<Window>()?.xdg_toplevel()
98    }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub(crate) struct ApplicationName {
103    pub(crate) general: String,
104    pub(crate) instance: String,
105}
106
107/// Window attributes methods specific to Wayland.
108#[derive(Debug, Default, Clone)]
109pub struct WindowAttributesWayland {
110    pub(crate) name: Option<ApplicationName>,
111    pub(crate) activation_token: Option<ActivationToken>,
112    pub(crate) prefer_csd: bool,
113}
114
115impl WindowAttributesWayland {
116    /// Build window with the given name.
117    ///
118    /// The `general` name sets an application ID, which should match the `.desktop`
119    /// file distributed with your program. The `instance` is a `no-op`.
120    ///
121    /// For details about application ID conventions, see the
122    /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
123    #[inline]
124    pub fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
125        self.name = Some(ApplicationName { general: general.into(), instance: instance.into() });
126        self
127    }
128
129    /// Sets an activation token to use when creating the window.
130    ///
131    /// The activation token allows the compositor to grant focus to the new window,
132    /// overriding focus-stealing prevention. Obtain a token via
133    /// [`ActiveEventLoop::request_activation_token`].
134    #[inline]
135    pub fn with_activation_token(mut self, token: ActivationToken) -> Self {
136        self.activation_token = Some(token);
137        self
138    }
139
140    /// Builds the window with a given preference for client-side decorations.
141    ///
142    /// When set to `true`, the window will tell the compositor that it prefers
143    /// client-side decorations, even if server-side decorations are available.
144    /// When set to `false` (the default), the window will indicate a preference
145    /// for server-side decorations.
146    #[inline]
147    pub fn with_prefer_csd(mut self, prefer_csd: bool) -> Self {
148        self.prefer_csd = prefer_csd;
149        self
150    }
151}
152
153impl PlatformWindowAttributes for WindowAttributesWayland {
154    fn box_clone(&self) -> Box<dyn PlatformWindowAttributes> {
155        Box::from(self.clone())
156    }
157}
158
159/// Get the WindowId out of the surface.
160#[inline]
161fn make_wid(surface: &WlSurface) -> WindowId {
162    WindowId::from_raw(surface.id().as_ptr() as usize)
163}
164
165/// Create a `DataTransferId` for the given data device and serial.
166///
167/// It's currently unclear if this will result in the same ID when transferring to the same
168/// application.
169#[inline]
170fn make_data_transfer_id(data_device_id: ObjectId, serial: u32) -> DataTransferId {
171    const BUILD_HASHER: foldhash::fast::FixedState = foldhash::fast::FixedState::with_seed(0);
172
173    DataTransferId::from_raw(BUILD_HASHER.hash_one((data_device_id, serial)) as i64)
174}
175
176/// The default routine does floor, but we need round on Wayland.
177fn logical_to_physical_rounded(size: LogicalSize<u32>, scale_factor: f64) -> PhysicalSize<u32> {
178    let width = size.width as f64 * scale_factor;
179    let height = size.height as f64 * scale_factor;
180    (width.round(), height.round()).into()
181}
182
183/// Converts an image buffer to a Wayland buffer (`wl_buffer`)
184fn image_to_buffer(
185    width: i32,
186    height: i32,
187    data: &[u8],
188    format: Format,
189    pool: &mut SlotPool,
190) -> Result<Buffer, CreateBufferError> {
191    let (buffer, canvas) = pool.create_buffer(width, height, 4 * width, format)?;
192
193    for (canvas_chunk, rgba) in canvas.chunks_exact_mut(4).zip(data.chunks_exact(4)) {
194        // Alpha in buffer is premultiplied.
195        let alpha = rgba[3] as f32 / 255.;
196        let r = (rgba[0] as f32 * alpha) as u32;
197        let g = (rgba[1] as f32 * alpha) as u32;
198        let b = (rgba[2] as f32 * alpha) as u32;
199        let color = ((rgba[3] as u32) << 24) + (r << 16) + (g << 8) + b;
200        let array: &mut [u8; 4] = canvas_chunk.try_into().unwrap();
201        *array = color.to_le_bytes();
202    }
203
204    Ok(buffer)
205}