ailloli_ui_winit/
native_overlay.rs

1//! Portable native_overlay contracts and Linux backend selection.
2
3use std::fmt;
4
5/// Logical desktop rectangle used to select and place an overlay exactly.
6///
7/// Coordinates and dimensions are compositor logical pixels. Negative origins
8/// are valid for monitors left of or above the desktop origin; all components
9/// must be finite and both dimensions must be strictly positive before native
10/// creation.
11///
12/// # Examples
13///
14/// ```
15/// use ailloli_ui_winit::native_overlay::NativeOverlayRect;
16/// let rect = NativeOverlayRect::new(-1920.0, 0.0, 1920.0, 1080.0);
17/// assert_eq!((rect.x, rect.width), (-1920.0, 1920.0));
18/// ```
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct NativeOverlayRect {
21    /// Left edge in logical desktop coordinates.
22    pub x: f64,
23    /// Top edge in logical desktop coordinates.
24    pub y: f64,
25    /// Strictly positive logical width.
26    pub width: f64,
27    /// Strictly positive logical height.
28    pub height: f64,
29}
30
31/// Construction and validation of a logical output rectangle.
32impl NativeOverlayRect {
33    /// Creates a rectangle without validation or normalization.
34    ///
35    /// Native creation later rejects non-finite coordinates and non-positive
36    /// dimensions with [`NativeOverlayError::InvalidTarget`].
37    ///
38    /// # Examples
39    ///
40    /// ```
41    /// use ailloli_ui_winit::native_overlay::NativeOverlayRect;
42    /// let rect = NativeOverlayRect::new(10.0, 20.0, 640.0, 480.0);
43    /// assert_eq!((rect.y, rect.height), (20.0, 480.0));
44    /// ```
45    pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
46        Self {
47            x,
48            y,
49            width,
50            height,
51        }
52    }
53
54    /// Accepts finite coordinates and strictly positive finite dimensions.
55    ///
56    /// # Errors
57    ///
58    /// Returns [`NativeOverlayError::InvalidTarget`] when either coordinate is
59    /// non-finite or either dimension is non-finite or not strictly positive.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// // Native constructors apply this validation before contacting a backend.
65    /// let invalid_width = 0.0_f64;
66    /// assert!(invalid_width <= 0.0);
67    /// ```
68    pub(crate) fn validate(self) -> Result<Self, NativeOverlayError> {
69        if !self.x.is_finite()
70            || !self.y.is_finite()
71            || !self.width.is_finite()
72            || !self.height.is_finite()
73            || self.width <= 0.0
74            || self.height <= 0.0
75        {
76            return Err(NativeOverlayError::InvalidTarget);
77        }
78        Ok(self)
79    }
80}
81
82/// Output selected by the portal/compositor logical desktop rectangle.
83///
84/// The rectangle is authoritative. An optional output name only narrows an
85/// otherwise exact rectangle match and never substitutes for its geometry.
86///
87/// # Examples
88///
89/// ```
90/// use ailloli_ui_winit::native_overlay::{NativeOverlayRect, NativeOverlayTarget};
91/// let target = NativeOverlayTarget::new(NativeOverlayRect::new(0.0, 0.0, 1920.0, 1080.0))
92///     .output_name("DP-1");
93/// assert_eq!(target.output_name.as_deref(), Some("DP-1"));
94/// ```
95#[derive(Debug, Clone, PartialEq)]
96pub struct NativeOverlayTarget {
97    /// Exact logical desktop rectangle supplied by the capture/portal workflow.
98    pub logical_rect: NativeOverlayRect,
99    /// Optional stable output name used as an additional, never substitute, discriminator.
100    pub output_name: Option<String>,
101}
102
103/// Exact-geometry target construction and optional name discrimination.
104impl NativeOverlayTarget {
105    /// Creates an unnamed target for the exact logical rectangle.
106    ///
107    /// # Examples
108    ///
109    /// ```
110    /// use ailloli_ui_winit::native_overlay::{NativeOverlayRect, NativeOverlayTarget};
111    /// let target = NativeOverlayTarget::new(NativeOverlayRect::new(0.0, 0.0, 800.0, 600.0));
112    /// assert!(target.output_name.is_none());
113    /// ```
114    pub const fn new(logical_rect: NativeOverlayRect) -> Self {
115        Self {
116            logical_rect,
117            output_name: None,
118        }
119    }
120
121    /// Adds a stable output-name discriminator.
122    ///
123    /// An empty string is retained as an exact name and will generally produce
124    /// [`NativeOverlayError::OutputMatchMissing`] rather than being treated as absent.
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use ailloli_ui_winit::native_overlay::{NativeOverlayRect, NativeOverlayTarget};
130    /// let target = NativeOverlayTarget::new(NativeOverlayRect::new(0.0, 0.0, 1.0, 1.0))
131    ///     .output_name("HDMI-A-1");
132    /// assert_eq!(target.output_name.as_deref(), Some("HDMI-A-1"));
133    /// ```
134    pub fn output_name(mut self, name: impl Into<String>) -> Self {
135        self.output_name = Some(name.into());
136        self
137    }
138}
139
140/// Pointer behavior of the native overlay. Keyboard focus is never requested.
141///
142/// # Examples
143///
144/// ```
145/// use ailloli_ui_winit::native_overlay::NativeOverlayInputMode;
146/// assert_eq!(NativeOverlayInputMode::default(), NativeOverlayInputMode::PassThrough);
147/// ```
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
149pub enum NativeOverlayInputMode {
150    /// Installs an empty input region so pointer events reach content underneath.
151    #[default]
152    PassThrough,
153    /// Lets the full overlay surface receive and block pointer events.
154    BlockPointer,
155}
156
157/// Native overlay creation options.
158///
159/// # Examples
160///
161/// ```
162/// use ailloli_ui_winit::native_overlay::{
163///     NativeOverlayInputMode, NativeOverlayOptions, NativeOverlayRect, NativeOverlayTarget,
164/// };
165/// let options = NativeOverlayOptions::new(NativeOverlayTarget::new(
166///     NativeOverlayRect::new(0.0, 0.0, 1280.0, 720.0),
167/// )).input_mode(NativeOverlayInputMode::BlockPointer);
168/// assert_eq!(options.input_mode, NativeOverlayInputMode::BlockPointer);
169/// ```
170#[derive(Debug, Clone, PartialEq)]
171pub struct NativeOverlayOptions {
172    /// Exact compositor output target.
173    pub target: NativeOverlayTarget,
174    /// Pointer policy; defaults to pass-through.
175    pub input_mode: NativeOverlayInputMode,
176}
177
178/// Builder-style native overlay configuration.
179impl NativeOverlayOptions {
180    /// Creates pass-through options for `target`.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use ailloli_ui_winit::native_overlay::*;
186    /// let options = NativeOverlayOptions::new(NativeOverlayTarget::new(
187    ///     NativeOverlayRect::new(0.0, 0.0, 100.0, 100.0),
188    /// ));
189    /// assert_eq!(options.input_mode, NativeOverlayInputMode::PassThrough);
190    /// ```
191    pub const fn new(target: NativeOverlayTarget) -> Self {
192        Self {
193            target,
194            input_mode: NativeOverlayInputMode::PassThrough,
195        }
196    }
197
198    /// Replaces the pointer policy.
199    ///
200    /// This never enables keyboard focus; both modes keep keyboard interactivity disabled.
201    ///
202    /// # Examples
203    ///
204    /// ```
205    /// use ailloli_ui_winit::native_overlay::*;
206    /// let options = NativeOverlayOptions::new(NativeOverlayTarget::new(
207    ///     NativeOverlayRect::new(0.0, 0.0, 100.0, 100.0),
208    /// )).input_mode(NativeOverlayInputMode::BlockPointer);
209    /// assert_eq!(options.input_mode, NativeOverlayInputMode::BlockPointer);
210    /// ```
211    pub const fn input_mode(mut self, input_mode: NativeOverlayInputMode) -> Self {
212        self.input_mode = input_mode;
213        self
214    }
215}
216
217/// Backend that actually established the overlay invariants.
218///
219/// # Examples
220///
221/// ```
222/// use ailloli_ui_winit::native_overlay::NativeOverlayBackend;
223/// let backend = NativeOverlayBackend::WaylandLayerShell;
224/// assert_ne!(backend, NativeOverlayBackend::X11);
225/// ```
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum NativeOverlayBackend {
228    /// X11 dock/override behavior established through the winit window path.
229    X11,
230    /// Wayland `wlr-layer-shell` overlay surface.
231    WaylandLayerShell,
232}
233
234/// Capabilities are returned only after every required overlay invariant is active.
235///
236/// `pointer_pass_through` describes the selected pointer policy and is not part
237/// of [`Self::is_fully_effective`], because blocking mode is also a valid fully
238/// effective overlay. All other booleans must be true for full effectiveness.
239///
240/// # Examples
241///
242/// ```
243/// use ailloli_ui_winit::native_overlay::{NativeOverlayBackend, NativeOverlayCapabilities};
244/// let partial = NativeOverlayCapabilities {
245///     backend: NativeOverlayBackend::X11,
246///     placed: true,
247///     topmost: false,
248///     transparent: true,
249///     non_activating: true,
250///     keyboard_focus_disabled: true,
251///     pointer_pass_through: true,
252/// };
253/// assert!(!partial.is_fully_effective());
254/// ```
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub struct NativeOverlayCapabilities {
257    /// Native backend that established these claims.
258    pub backend: NativeOverlayBackend,
259    /// Exact target placement was confirmed.
260    pub placed: bool,
261    /// The surface is above ordinary application windows.
262    pub topmost: bool,
263    /// The native surface supports alpha transparency.
264    pub transparent: bool,
265    /// Showing the surface does not activate it.
266    pub non_activating: bool,
267    /// Keyboard focus is disabled at the native protocol level.
268    pub keyboard_focus_disabled: bool,
269    /// Pointer events pass through to underlying surfaces.
270    pub pointer_pass_through: bool,
271}
272
273/// Capability construction and invariant checking.
274impl NativeOverlayCapabilities {
275    /// Records a backend whose required invariants were all established.
276    ///
277    /// Pointer pass-through mirrors `mode`; pointer blocking remains fully effective.
278    ///
279    /// # Examples
280    ///
281    /// ```
282    /// // Backends expose an established capability record only after setup succeeds.
283    /// use ailloli_ui_winit::native_overlay::NativeOverlayInputMode;
284    /// assert_eq!(NativeOverlayInputMode::default(), NativeOverlayInputMode::PassThrough);
285    /// ```
286    pub(crate) const fn established(
287        backend: NativeOverlayBackend,
288        mode: NativeOverlayInputMode,
289    ) -> Self {
290        Self {
291            backend,
292            placed: true,
293            topmost: true,
294            transparent: true,
295            non_activating: true,
296            keyboard_focus_disabled: true,
297            pointer_pass_through: matches!(mode, NativeOverlayInputMode::PassThrough),
298        }
299    }
300
301    /// Returns whether placement, z-order, transparency, non-activation, and
302    /// keyboard-focus suppression are all active.
303    ///
304    /// # Examples
305    ///
306    /// ```
307    /// use ailloli_ui_winit::native_overlay::{NativeOverlayBackend, NativeOverlayCapabilities};
308    /// let caps = NativeOverlayCapabilities {
309    ///     backend: NativeOverlayBackend::WaylandLayerShell,
310    ///     placed: true, topmost: true, transparent: true,
311    ///     non_activating: true, keyboard_focus_disabled: true,
312    ///     pointer_pass_through: false,
313    /// };
314    /// assert!(caps.is_fully_effective());
315    /// ```
316    pub const fn is_fully_effective(self) -> bool {
317        self.placed
318            && self.topmost
319            && self.transparent
320            && self.non_activating
321            && self.keyboard_focus_disabled
322    }
323}
324
325/// Failure to validate, establish, or retain a native overlay.
326///
327/// # Examples
328///
329/// ```
330/// use ailloli_ui_winit::native_overlay::NativeOverlayError;
331/// assert_eq!(NativeOverlayError::Closed.to_string(), "native overlay was closed by the compositor");
332/// ```
333#[derive(Debug, Clone, PartialEq, Eq)]
334pub enum NativeOverlayError {
335    /// The current operating system or display backend has no supported implementation.
336    Unsupported,
337    /// Geometry was non-finite, non-positive, fractional where exact integers are required, or out of range.
338    InvalidTarget,
339    /// No compositor output matched the exact rectangle and optional name.
340    OutputMatchMissing,
341    /// More than one compositor output matched the requested identity.
342    OutputMatchAmbiguous,
343    /// A native protocol or operating-system operation failed with this message.
344    Backend(String),
345    /// The compositor closed the overlay surface.
346    Closed,
347}
348
349/// Stable human-readable category messages for native overlay failures.
350impl fmt::Display for NativeOverlayError {
351    /// Formats the platform, target, capability, or geometry failure.
352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353        match self {
354            Self::Unsupported => write!(f, "native overlays are unsupported on this platform"),
355            Self::InvalidTarget => write!(f, "native overlay target is invalid"),
356            Self::OutputMatchMissing => {
357                write!(
358                    f,
359                    "no compositor output matches the requested logical rectangle"
360                )
361            }
362            Self::OutputMatchAmbiguous => {
363                write!(
364                    f,
365                    "multiple compositor outputs match the requested logical rectangle"
366                )
367            }
368            Self::Backend(message) => write!(f, "native overlay backend failed: {message}"),
369            Self::Closed => write!(f, "native overlay was closed by the compositor"),
370        }
371    }
372}
373
374/// Marks native overlay failures as standard errors without an additional source.
375impl std::error::Error for NativeOverlayError {}
376
377#[cfg(all(target_os = "linux", feature = "native_overlay"))]
378/// Linux Wayland layer-shell implementation and raw-window-handle owner.
379pub(crate) mod wayland;
380
381#[cfg(feature = "native_overlay")]
382/// Wayland output probing and capture-calibration marker service.
383mod calibration;
384#[cfg(feature = "native_overlay")]
385pub use calibration::{
386    NativeCalibrationMarkerGuard, NativeCalibrationMarkerPixel, NativeCalibrationMarkerSpec,
387    NativeOutputDescriptor, NativeOutputProbeService, NativeOutputScale, NativeOutputTransform,
388};
389
390#[cfg(test)]
391/// Target validation and effective-capability policy scenarios.
392mod tests {
393    use super::*;
394
395    #[test]
396    fn native_overlay_rejects_non_finite_or_empty_targets() {
397        assert_eq!(
398            NativeOverlayRect::new(0.0, 0.0, 0.0, 10.0).validate(),
399            Err(NativeOverlayError::InvalidTarget)
400        );
401        assert_eq!(
402            NativeOverlayRect::new(f64::NAN, 0.0, 10.0, 10.0).validate(),
403            Err(NativeOverlayError::InvalidTarget)
404        );
405    }
406
407    #[test]
408    fn capabilities_distinguish_pointer_blocking() {
409        let pass = NativeOverlayCapabilities::established(
410            NativeOverlayBackend::X11,
411            NativeOverlayInputMode::PassThrough,
412        );
413        let block = NativeOverlayCapabilities::established(
414            NativeOverlayBackend::X11,
415            NativeOverlayInputMode::BlockPointer,
416        );
417        assert!(pass.pointer_pass_through);
418        assert!(!block.pointer_pass_through);
419        assert!(pass.is_fully_effective());
420        assert!(block.is_fully_effective());
421    }
422}