Skip to main content

winit_x11/
lib.rs

1//! # X11
2
3#![warn(clippy::exhaustive_enums)]
4
5use dpi::Size;
6#[cfg(feature = "serde")]
7use serde::{Deserialize, Serialize};
8use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop;
9use winit_core::window::{ActivationToken, PlatformWindowAttributes, Window as CoreWindow};
10
11pub use crate::event_loop::{ActiveEventLoop, EventLoop};
12pub use crate::window::Window;
13
14macro_rules! os_error {
15    ($error:expr) => {{ winit_core::error::OsError::new(line!(), file!(), $error) }};
16}
17
18mod activation;
19mod atoms;
20mod dnd;
21mod event_loop;
22mod event_processor;
23pub mod ffi;
24mod ime;
25mod monitor;
26mod util;
27mod window;
28#[doc(hidden)]
29pub mod x11_util;
30mod xdisplay;
31mod xsettings;
32
33pub use dnd::{Selection, SelectionReader, SelectionType, UriListParseError};
34
35/// X window type. Maps directly to
36/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).
37#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
38#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
39#[non_exhaustive]
40pub enum WindowType {
41    /// A desktop feature. This can include a single window containing desktop icons with the same
42    /// dimensions as the screen, allowing the desktop environment to have full control of the
43    /// desktop, without the need for proxying root window clicks.
44    Desktop,
45    /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all
46    /// other windows.
47    Dock,
48    /// Toolbar windows. "Torn off" from the main application.
49    Toolbar,
50    /// Pinnable menu windows. "Torn off" from the main application.
51    Menu,
52    /// A small persistent utility window, such as a palette or toolbox.
53    Utility,
54    /// The window is a splash screen displayed as an application is starting up.
55    Splash,
56    /// This is a dialog window.
57    Dialog,
58    /// A dropdown menu that usually appears when the user clicks on an item in a menu bar.
59    /// This property is typically used on override-redirect windows.
60    DropdownMenu,
61    /// A popup menu that usually appears when the user right clicks on an object.
62    /// This property is typically used on override-redirect windows.
63    PopupMenu,
64    /// A tooltip window. Usually used to show additional information when hovering over an object
65    /// with the cursor. This property is typically used on override-redirect windows.
66    Tooltip,
67    /// The window is a notification.
68    /// This property is typically used on override-redirect windows.
69    Notification,
70    /// This should be used on the windows that are popped up by combo boxes.
71    /// This property is typically used on override-redirect windows.
72    Combo,
73    /// This indicates the window is being dragged.
74    /// This property is typically used on override-redirect windows.
75    Dnd,
76    /// This is a normal, top-level window.
77    #[default]
78    Normal,
79}
80
81/// The first argument in the provided hook will be the pointer to `XDisplay`
82/// and the second one the pointer to [`XErrorEvent`]. The returned `bool` is an
83/// indicator whether the error was handled by the callback.
84///
85/// [`XErrorEvent`]: https://linux.die.net/man/3/xerrorevent
86pub type XlibErrorHook =
87    Box<dyn Fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> bool + Send + Sync>;
88
89/// A unique identifier for an X11 visual.
90pub type XVisualID = u32;
91
92/// A unique identifier for an X11 window.
93pub type XWindow = u32;
94
95/// Hook to winit's xlib error handling callback.
96///
97/// This method is provided as a safe way to handle the errors coming from X11
98/// when using xlib in external crates, like glutin for GLX access. Trying to
99/// handle errors by speculating with `XSetErrorHandler` is [`unsafe`].
100///
101/// **Be aware that your hook is always invoked and returning `true` from it will
102/// prevent `winit` from getting the error itself. It's wise to always return
103/// `false` if you're not initiated the `Sync`.**
104///
105/// [`unsafe`]: https://www.remlab.net/op/xlib.shtml
106#[inline]
107pub fn register_xlib_error_hook(hook: XlibErrorHook) {
108    // Append new hook.
109    crate::event_loop::XLIB_ERROR_HOOKS.lock().unwrap().push(hook);
110}
111
112/// Additional methods on [`ActiveEventLoop`] that are specific to X11.
113///
114/// [`ActiveEventLoop`]: winit_core::event_loop::ActiveEventLoop
115pub trait ActiveEventLoopExtX11 {
116    /// True if the event loop uses X11.
117    fn is_x11(&self) -> bool;
118}
119
120impl ActiveEventLoopExtX11 for dyn CoreActiveEventLoop + '_ {
121    #[inline]
122    fn is_x11(&self) -> bool {
123        self.cast_ref::<ActiveEventLoop>().is_some()
124    }
125}
126
127/// Additional methods on [`EventLoop`] that are specific to X11.
128pub trait EventLoopExtX11 {
129    /// True if the [`EventLoop`] uses X11.
130    fn is_x11(&self) -> bool;
131}
132
133/// Additional methods when building event loop that are specific to X11.
134pub trait EventLoopBuilderExtX11 {
135    /// Force using X11.
136    fn with_x11(&mut self) -> &mut Self;
137
138    /// Whether to allow the event loop to be created off of the main thread.
139    ///
140    /// By default, the window is only allowed to be created on the main
141    /// thread, to make platform compatibility easier.
142    fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
143}
144
145/// Additional methods on [`Window`] that are specific to X11.
146///
147/// [`Window`]: crate::window::Window
148pub trait WindowExtX11 {}
149
150impl WindowExtX11 for dyn CoreWindow {}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub(crate) struct ApplicationName {
154    pub(crate) general: String,
155    pub(crate) instance: String,
156}
157
158#[derive(Clone, Debug)]
159pub struct WindowAttributesX11 {
160    pub(crate) name: Option<ApplicationName>,
161    pub(crate) activation_token: Option<ActivationToken>,
162    pub(crate) visual_id: Option<XVisualID>,
163    pub(crate) screen_id: Option<i32>,
164    pub(crate) base_size: Option<Size>,
165    pub(crate) override_redirect: bool,
166    pub(crate) x11_window_types: Vec<WindowType>,
167
168    /// The parent window to embed this window into.
169    pub(crate) embed_window: Option<XWindow>,
170}
171
172impl Default for WindowAttributesX11 {
173    fn default() -> Self {
174        Self {
175            name: None,
176            activation_token: None,
177            visual_id: None,
178            screen_id: None,
179            base_size: None,
180            override_redirect: false,
181            x11_window_types: vec![WindowType::Normal],
182            embed_window: None,
183        }
184    }
185}
186
187impl WindowAttributesX11 {
188    /// Create this window with a specific X11 visual.
189    pub fn with_x11_visual(mut self, visual_id: XVisualID) -> Self {
190        self.visual_id = Some(visual_id);
191        self
192    }
193
194    pub fn with_x11_screen(mut self, screen_id: i32) -> Self {
195        self.screen_id = Some(screen_id);
196        self
197    }
198
199    /// Build window with the given `general` and `instance` names.
200    ///
201    /// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the
202    /// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance",
203    /// "general"`.
204    ///
205    /// For details about application ID conventions, see the
206    /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
207    pub fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
208        self.name = Some(ApplicationName { general: general.into(), instance: instance.into() });
209        self
210    }
211
212    /// Build window with override-redirect flag; defaults to false.
213    pub fn with_override_redirect(mut self, override_redirect: bool) -> Self {
214        self.override_redirect = override_redirect;
215        self
216    }
217
218    /// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`.
219    pub fn with_x11_window_type(mut self, x11_window_types: Vec<WindowType>) -> Self {
220        self.x11_window_types = x11_window_types;
221        self
222    }
223
224    /// Build window with base size hint.
225    ///
226    /// ```
227    /// # use winit::dpi::{LogicalSize, PhysicalSize};
228    /// # use winit::window::{Window, WindowAttributes};
229    /// # use winit::platform::x11::WindowAttributesX11;
230    /// // Specify the size in logical dimensions like this:
231    /// WindowAttributesX11::default().with_base_size(LogicalSize::new(400.0, 200.0));
232    ///
233    /// // Or specify the size in physical dimensions like this:
234    /// WindowAttributesX11::default().with_base_size(PhysicalSize::new(400, 200));
235    /// ```
236    pub fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self {
237        self.base_size = Some(base_size.into());
238        self
239    }
240
241    /// Embed this window into another parent window.
242    ///
243    /// # Example
244    ///
245    /// ```no_run
246    /// use winit::window::{Window, WindowAttributes};
247    /// use winit::event_loop::ActiveEventLoop;
248    /// use winit::platform::x11::{XWindow, WindowAttributesX11};
249    /// # fn create_window(event_loop: &dyn ActiveEventLoop) -> Result<(), Box<dyn std::error::Error>> {
250    /// let parent_window_id = std::env::args().nth(1).unwrap().parse::<XWindow>()?;
251    /// let window_x11_attributes = WindowAttributesX11::default().with_embed_parent_window(parent_window_id);
252    /// let window_attributes = WindowAttributes::default().with_platform_attributes(Box::new(window_x11_attributes));
253    /// let window = event_loop.create_window(window_attributes)?;
254    /// # Ok(()) }
255    /// ```
256    pub fn with_embed_parent_window(mut self, parent_window_id: XWindow) -> Self {
257        self.embed_window = Some(parent_window_id);
258        self
259    }
260
261    #[inline]
262    pub fn with_activation_token(mut self, token: ActivationToken) -> Self {
263        self.activation_token = Some(token);
264        self
265    }
266}
267
268impl PlatformWindowAttributes for WindowAttributesX11 {
269    fn box_clone(&self) -> Box<dyn PlatformWindowAttributes> {
270        Box::from(self.clone())
271    }
272}