ailloli_ui_winit/native_overlay/
calibration.rs

1//! Native-output catalogue and temporary visual calibration marker.
2
3use std::sync::mpsc;
4#[cfg(target_os = "linux")]
5use std::thread::JoinHandle;
6use std::time::Duration;
7
8use super::{NativeOverlayError, NativeOverlayRect};
9
10/// Maximum synchronous wait for worker startup, catalogue, show, or hide replies.
11const COMMAND_TIMEOUT: Duration = Duration::from_secs(6);
12/// Thickness of the marker perimeter in compositor logical pixels.
13///
14/// # Examples
15///
16/// ```
17/// assert_eq!(ailloli_ui_winit::NativeCalibrationMarkerSpec::new(1, 0)
18///     .pixel_role(100, 100, 4, 50),
19///     ailloli_ui_winit::NativeCalibrationMarkerPixel::Border);
20/// ```
21pub const CALIBRATION_BORDER_LOGICAL_PX: u32 = 5;
22
23/// Reduces a positive integer ratio using Euclid's algorithm.
24///
25/// Zero in either component is invalid and returns `None`.
26fn reduced_ratio(numerator: u32, denominator: u32) -> Option<(u32, u32)> {
27    if numerator == 0 || denominator == 0 {
28        return None;
29    }
30    let mut left = numerator;
31    let mut right = denominator;
32    while right != 0 {
33        let remainder = left % right;
34        left = right;
35        right = remainder;
36    }
37    Some((numerator / left, denominator / left))
38}
39
40/// Exact positive rational scale from logical output units to physical pixels.
41///
42/// Catalogue snapshots reduce the fraction to lowest terms. The public fields
43/// permit construction of zero values, but such values are not emitted by the
44/// native probe.
45///
46/// # Examples
47///
48/// ```
49/// use ailloli_ui_winit::NativeOutputScale;
50/// let scale = NativeOutputScale::integer(2);
51/// assert_eq!((scale.numerator, scale.denominator), (2, 1));
52/// ```
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct NativeOutputScale {
55    /// Physical-pixel numerator of the reduced scale ratio.
56    pub numerator: u32,
57    /// Logical-unit denominator of the reduced scale ratio.
58    pub denominator: u32,
59}
60
61/// Integer-scale construction.
62impl NativeOutputScale {
63    /// Creates the exact ratio `value / 1` without validation.
64    ///
65    /// # Examples
66    ///
67    /// ```
68    /// let scale = ailloli_ui_winit::NativeOutputScale::integer(3);
69    /// assert_eq!(scale.denominator, 1);
70    /// ```
71    pub const fn integer(value: u32) -> Self {
72        Self {
73            numerator: value,
74            denominator: 1,
75        }
76    }
77}
78
79/// Native output transform reported by the compositor.
80///
81/// # Examples
82///
83/// ```
84/// use ailloli_ui_winit::NativeOutputTransform;
85/// let transform = NativeOutputTransform::Rotate90;
86/// assert_ne!(transform, NativeOutputTransform::Normal);
87/// ```
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum NativeOutputTransform {
90    /// No rotation or reflection.
91    Normal,
92    /// Clockwise quarter turn.
93    Rotate90,
94    /// Half turn.
95    Rotate180,
96    /// Clockwise three-quarter turn.
97    Rotate270,
98    /// Reflected without rotation.
99    Flipped,
100    /// Reflected and rotated by 90 degrees.
101    Flipped90,
102    /// Reflected and rotated by 180 degrees.
103    Flipped180,
104    /// Reflected and rotated by 270 degrees.
105    Flipped270,
106    /// Backend value was unavailable or not recognized.
107    Unknown,
108}
109
110/// One output in a generation-stamped native compositor catalogue.
111///
112/// The logical rectangle drives exact matching. Physical dimensions are pixels;
113/// scale is a reduced rational; the fingerprint is stable only for the supplied
114/// metadata and is not a hardware authentication token.
115///
116/// # Examples
117///
118/// ```
119/// use ailloli_ui_winit::{NativeOutputDescriptor, NativeOutputScale, NativeOutputTransform};
120/// use ailloli_ui_winit::native_overlay::NativeOverlayRect;
121/// let output = NativeOutputDescriptor {
122///     fingerprint: "demo".into(), output_name: Some("DP-1".into()),
123///     logical_rect: NativeOverlayRect::new(0.0, 0.0, 1920.0, 1080.0),
124///     physical_width_px: 3840, physical_height_px: 2160,
125///     scale: NativeOutputScale::integer(2),
126///     transform: NativeOutputTransform::Normal, catalog_generation: 7,
127/// };
128/// assert_eq!(output.physical_width_px, 3840);
129/// ```
130#[derive(Debug, Clone, PartialEq)]
131pub struct NativeOutputDescriptor {
132    /// Deterministic hash of the native output metadata in this catalogue.
133    pub fingerprint: String,
134    /// Stable connector/name when the compositor exposes one.
135    pub output_name: Option<String>,
136    /// Exact compositor logical desktop rectangle.
137    pub logical_rect: NativeOverlayRect,
138    /// Native output width in physical pixels.
139    pub physical_width_px: u32,
140    /// Native output height in physical pixels.
141    pub physical_height_px: u32,
142    /// Reduced physical-to-logical scale ratio.
143    pub scale: NativeOutputScale,
144    /// Rotation/reflection applied by the compositor.
145    pub transform: NativeOutputTransform,
146    /// Monotonic service generation for detecting stale descriptors.
147    pub catalog_generation: u64,
148}
149
150/// Deterministic marker identity used to correlate a native output with a capture.
151///
152/// A nonce distinguishes calibration attempts and `candidate_ordinal`
153/// distinguishes outputs within one attempt. Both values feed the asymmetric
154/// perimeter signature; they are identifiers, not cryptographic secrets.
155///
156/// # Examples
157///
158/// ```
159/// let spec = ailloli_ui_winit::NativeCalibrationMarkerSpec::new(42, 3);
160/// assert_eq!((spec.nonce, spec.candidate_ordinal), (42, 3));
161/// ```
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub struct NativeCalibrationMarkerSpec {
164    /// Attempt-specific signature seed.
165    pub nonce: u64,
166    /// Zero-based candidate index mixed into the signature.
167    pub candidate_ordinal: u32,
168}
169
170/// Marker construction and expected-pixel classification.
171impl NativeCalibrationMarkerSpec {
172    /// Opaque red RGBA8 color for ordinary perimeter pixels.
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// assert_eq!(ailloli_ui_winit::NativeCalibrationMarkerSpec::BORDER_RGBA, [239, 24, 24, 255]);
178    /// ```
179    pub const BORDER_RGBA: [u8; 4] = [239, 24, 24, 255];
180    /// Opaque cyan RGBA8 color for nonce/candidate signature pixels.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// assert_eq!(ailloli_ui_winit::NativeCalibrationMarkerSpec::SIGNATURE_RGBA, [0, 221, 255, 255]);
186    /// ```
187    pub const SIGNATURE_RGBA: [u8; 4] = [0, 221, 255, 255];
188    /// Fully transparent black RGBA8 used outside the perimeter.
189    ///
190    /// # Examples
191    ///
192    /// ```
193    /// assert_eq!(ailloli_ui_winit::NativeCalibrationMarkerSpec::TRANSPARENT_RGBA, [0, 0, 0, 0]);
194    /// ```
195    pub const TRANSPARENT_RGBA: [u8; 4] = [0, 0, 0, 0];
196
197    /// Creates a deterministic marker specification.
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// let spec = ailloli_ui_winit::NativeCalibrationMarkerSpec::new(9, 2);
203    /// assert_eq!(spec.candidate_ordinal, 2);
204    /// ```
205    pub const fn new(nonce: u64, candidate_ordinal: u32) -> Self {
206        Self {
207            nonce,
208            candidate_ordinal,
209        }
210    }
211
212    /// Classifies one logical marker coordinate.
213    ///
214    /// Coordinates outside the supplied extent and interior pixels are
215    /// transparent. A five-logical-pixel perimeter is split deterministically
216    /// between red border and cyan signature pixels. Saturating arithmetic keeps
217    /// dimensions smaller than twice the border well-defined.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// use ailloli_ui_winit::{NativeCalibrationMarkerPixel, NativeCalibrationMarkerSpec};
223    /// let spec = NativeCalibrationMarkerSpec::new(1, 0);
224    /// assert_eq!(spec.pixel_role(100, 100, 50, 50), NativeCalibrationMarkerPixel::Transparent);
225    /// assert_eq!(spec.pixel_role(100, 100, 100, 0), NativeCalibrationMarkerPixel::Transparent);
226    /// ```
227    pub fn pixel_role(
228        self,
229        logical_width: u32,
230        logical_height: u32,
231        x: u32,
232        y: u32,
233    ) -> NativeCalibrationMarkerPixel {
234        if x >= logical_width || y >= logical_height {
235            return NativeCalibrationMarkerPixel::Transparent;
236        }
237        let border = CALIBRATION_BORDER_LOGICAL_PX;
238        let right = logical_width.saturating_sub(border);
239        let bottom = logical_height.saturating_sub(border);
240        let on_border = x < border || y < border || x >= right || y >= bottom;
241        if !on_border {
242            return NativeCalibrationMarkerPixel::Transparent;
243        }
244
245        let seed = self.nonce.rotate_left(self.candidate_ordinal % 63)
246            ^ u64::from(self.candidate_ordinal).wrapping_mul(0x9e37_79b9_7f4a_7c15);
247        let signature = if y < border && x >= border && x < right {
248            signature_bit(seed, x - border, right.saturating_sub(border), 0)
249        } else if y >= bottom && x >= border && x < right {
250            signature_bit(seed.rotate_left(17), right - 1 - x, right - border, 16)
251        } else if x < border && y >= border && y < bottom {
252            signature_bit(seed.rotate_left(31), y - border, bottom - border, 32)
253        } else if x >= right && y >= border && y < bottom {
254            signature_bit(seed.rotate_left(47), bottom - 1 - y, bottom - border, 48)
255        } else {
256            (x < border && y < border)
257                || (x >= right && y >= bottom && self.candidate_ordinal.is_multiple_of(2))
258        };
259        if signature {
260            NativeCalibrationMarkerPixel::Signature
261        } else {
262            NativeCalibrationMarkerPixel::Border
263        }
264    }
265
266    /// Returns the exact RGBA8 value expected at one logical marker coordinate.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// use ailloli_ui_winit::NativeCalibrationMarkerSpec;
272    /// let spec = NativeCalibrationMarkerSpec::new(1, 0);
273    /// assert_eq!(spec.expected_rgba(100, 100, 50, 50), NativeCalibrationMarkerSpec::TRANSPARENT_RGBA);
274    /// ```
275    pub fn expected_rgba(self, logical_width: u32, logical_height: u32, x: u32, y: u32) -> [u8; 4] {
276        match self.pixel_role(logical_width, logical_height, x, y) {
277            NativeCalibrationMarkerPixel::Transparent => Self::TRANSPARENT_RGBA,
278            NativeCalibrationMarkerPixel::Border => Self::BORDER_RGBA,
279            NativeCalibrationMarkerPixel::Signature => Self::SIGNATURE_RGBA,
280        }
281    }
282}
283
284/// Selects one of sixteen signature cells along an edge using saturating math.
285fn signature_bit(seed: u64, position: u32, extent: u32, bit_offset: u32) -> bool {
286    if extent == 0 {
287        return false;
288    }
289    let cell = position.saturating_mul(16) / extent;
290    let bit = (cell.min(15) + bit_offset) % 64;
291    ((seed >> bit) & 1) != 0
292}
293
294/// Semantic class of a logical marker pixel.
295///
296/// # Examples
297///
298/// ```
299/// use ailloli_ui_winit::NativeCalibrationMarkerPixel;
300/// assert_ne!(NativeCalibrationMarkerPixel::Border, NativeCalibrationMarkerPixel::Signature);
301/// ```
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub enum NativeCalibrationMarkerPixel {
304    /// Fully transparent interior or out-of-bounds pixel.
305    Transparent,
306    /// Ordinary opaque red perimeter pixel.
307    Border,
308    /// Opaque cyan perimeter pixel encoding the marker identity.
309    Signature,
310}
311
312#[cfg(target_os = "linux")]
313/// Unbounded worker commands; synchronous operations pair commands with reply channels.
314enum Command {
315    /// Request a generation-stamped output catalogue.
316    Snapshot(mpsc::Sender<Result<Vec<NativeOutputDescriptor>, NativeOverlayError>>),
317    /// Display one marker and acknowledge presentation or failure.
318    Show {
319        /// Native output on which the marker must be displayed.
320        descriptor: NativeOutputDescriptor,
321        /// Marker geometry and encoded identity to present.
322        spec: NativeCalibrationMarkerSpec,
323        /// One-shot channel used to report presentation success or failure.
324        response: mpsc::Sender<Result<(), NativeOverlayError>>,
325    },
326    /// Remove the marker, optionally acknowledging an explicit caller.
327    Hide(Option<mpsc::Sender<Result<(), NativeOverlayError>>>),
328    /// Stop the worker and remove any active marker.
329    Shutdown,
330}
331
332/// Dedicated native-output probe and calibration-marker worker.
333///
334/// On Linux, connection starts one named thread and each synchronous command
335/// waits at most six seconds. Other platforms return [`NativeOverlayError::Unsupported`].
336/// Dropping or consuming the service sends shutdown and joins the worker.
337///
338/// # Examples
339///
340/// ```no_run
341/// let service: ailloli_ui_winit::NativeOutputProbeService =
342///     ailloli_ui_winit::NativeOutputProbeService::connect().unwrap();
343/// service.shutdown();
344/// ```
345pub struct NativeOutputProbeService {
346    #[cfg(target_os = "linux")]
347    /// Unbounded command sender owned by API callers and marker guards.
348    commands: mpsc::Sender<Command>,
349    #[cfg(target_os = "linux")]
350    /// Join handle consumed exactly once by shutdown or drop.
351    worker: Option<JoinHandle<()>>,
352}
353
354/// Hides platform channel details from debug output.
355impl std::fmt::Debug for NativeOutputProbeService {
356    /// Omits worker-channel internals while identifying the service type.
357    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        formatter
359            .debug_struct("NativeOutputProbeService")
360            .finish_non_exhaustive()
361    }
362}
363
364/// Probe lifecycle and synchronous command interface.
365impl NativeOutputProbeService {
366    /// Connects to the native output protocol and starts the worker.
367    ///
368    /// # Errors
369    ///
370    /// Returns `Unsupported` off Linux, or a backend/timeout error if the worker
371    /// cannot start and initialize within six seconds.
372    ///
373    /// # Examples
374    ///
375    /// ```no_run
376    /// let service = ailloli_ui_winit::NativeOutputProbeService::connect()?;
377    /// service.shutdown();
378    /// # Ok::<(), ailloli_ui_winit::NativeOverlayError>(())
379    /// ```
380    pub fn connect() -> Result<Self, NativeOverlayError> {
381        #[cfg(target_os = "linux")]
382        {
383            let (commands, receiver) = mpsc::channel();
384            let (ready_tx, ready_rx) = mpsc::sync_channel(1);
385            let worker = std::thread::Builder::new()
386                .name("ailloli_ui-output-probe".into())
387                .spawn(move || linux::run(receiver, ready_tx))
388                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
389            ready_rx.recv_timeout(COMMAND_TIMEOUT).map_err(|_| {
390                NativeOverlayError::Backend("native output probe startup timed out".into())
391            })??;
392            Ok(Self {
393                commands,
394                worker: Some(worker),
395            })
396        }
397        #[cfg(not(target_os = "linux"))]
398        Err(NativeOverlayError::Unsupported)
399    }
400
401    /// Returns the current generation-stamped output catalogue.
402    ///
403    /// # Errors
404    ///
405    /// Returns `Unsupported` off Linux, `Closed` if the worker ended, or a
406    /// backend timeout/error if no reply arrives within six seconds.
407    ///
408    /// # Examples
409    ///
410    /// ```no_run
411    /// let service = ailloli_ui_winit::NativeOutputProbeService::connect()?;
412    /// let outputs: Vec<ailloli_ui_winit::NativeOutputDescriptor> = service.snapshot_outputs()?;
413    /// # Ok::<(), ailloli_ui_winit::NativeOverlayError>(())
414    /// ```
415    pub fn snapshot_outputs(&self) -> Result<Vec<NativeOutputDescriptor>, NativeOverlayError> {
416        #[cfg(target_os = "linux")]
417        {
418            let (sender, receiver) = mpsc::channel();
419            self.commands
420                .send(Command::Snapshot(sender))
421                .map_err(|_| NativeOverlayError::Closed)?;
422            receiver.recv_timeout(COMMAND_TIMEOUT).map_err(|_| {
423                NativeOverlayError::Backend("native output catalogue timed out".into())
424            })?
425        }
426        #[cfg(not(target_os = "linux"))]
427        Err(NativeOverlayError::Unsupported)
428    }
429
430    /// Shows a temporary marker for one descriptor and returns its RAII guard.
431    ///
432    /// The worker rejects a descriptor from a stale catalogue generation.
433    /// Success means the compositor acknowledged and the marker buffer was
434    /// presented. Only one marker is active; showing another replaces it.
435    ///
436    /// # Errors
437    ///
438    /// Returns platform, stale-descriptor, channel, timeout, or backend failures.
439    ///
440    /// # Examples
441    ///
442    /// ```no_run
443    /// let service = ailloli_ui_winit::NativeOutputProbeService::connect()?;
444    /// let output = service.snapshot_outputs()?.remove(0);
445    /// let guard: ailloli_ui_winit::NativeCalibrationMarkerGuard = service.show_marker(
446    ///     &output,
447    ///     ailloli_ui_winit::NativeCalibrationMarkerSpec::new(123, 0),
448    /// )?;
449    /// guard.hide()?;
450    /// # Ok::<(), ailloli_ui_winit::NativeOverlayError>(())
451    /// ```
452    pub fn show_marker(
453        &self,
454        descriptor: &NativeOutputDescriptor,
455        spec: NativeCalibrationMarkerSpec,
456    ) -> Result<NativeCalibrationMarkerGuard, NativeOverlayError> {
457        #[cfg(target_os = "linux")]
458        {
459            let (sender, receiver) = mpsc::channel();
460            self.commands
461                .send(Command::Show {
462                    descriptor: descriptor.clone(),
463                    spec,
464                    response: sender,
465                })
466                .map_err(|_| NativeOverlayError::Closed)?;
467            receiver.recv_timeout(COMMAND_TIMEOUT).map_err(|_| {
468                NativeOverlayError::Backend("native calibration marker timed out".into())
469            })??;
470            Ok(NativeCalibrationMarkerGuard {
471                commands: self.commands.clone(),
472                visible: true,
473            })
474        }
475        #[cfg(not(target_os = "linux"))]
476        {
477            let _ = (descriptor, spec);
478            Err(NativeOverlayError::Unsupported)
479        }
480    }
481
482    /// Explicitly removes the active marker, if any.
483    ///
484    /// # Errors
485    ///
486    /// Returns platform, closed-worker, timeout, or backend errors. Hiding when
487    /// no marker is active is successful.
488    ///
489    /// # Examples
490    ///
491    /// ```no_run
492    /// let service = ailloli_ui_winit::NativeOutputProbeService::connect()?;
493    /// service.hide_marker()?;
494    /// # Ok::<(), ailloli_ui_winit::NativeOverlayError>(())
495    /// ```
496    pub fn hide_marker(&self) -> Result<(), NativeOverlayError> {
497        #[cfg(target_os = "linux")]
498        {
499            let (sender, receiver) = mpsc::channel();
500            self.commands
501                .send(Command::Hide(Some(sender)))
502                .map_err(|_| NativeOverlayError::Closed)?;
503            receiver.recv_timeout(COMMAND_TIMEOUT).map_err(|_| {
504                NativeOverlayError::Backend("native calibration marker removal timed out".into())
505            })?
506        }
507        #[cfg(not(target_os = "linux"))]
508        Err(NativeOverlayError::Unsupported)
509    }
510
511    /// Sends shutdown and joins the worker before returning.
512    ///
513    /// Command-send and worker-panic failures are deliberately ignored during teardown.
514    ///
515    /// # Examples
516    ///
517    /// ```no_run
518    /// let service = ailloli_ui_winit::NativeOutputProbeService::connect()?;
519    /// service.shutdown();
520    /// # Ok::<(), ailloli_ui_winit::NativeOverlayError>(())
521    /// ```
522    pub fn shutdown(mut self) {
523        self.shutdown_inner();
524    }
525
526    /// Idempotent teardown shared by explicit shutdown and drop.
527    fn shutdown_inner(&mut self) {
528        #[cfg(target_os = "linux")]
529        {
530            let _ = self.commands.send(Command::Shutdown);
531            if let Some(worker) = self.worker.take() {
532                let _ = worker.join();
533            }
534        }
535    }
536}
537
538/// Ensures a live probe worker is stopped and joined on scope exit.
539impl Drop for NativeOutputProbeService {
540    /// Requests shutdown and joins the worker at most once.
541    fn drop(&mut self) {
542        self.shutdown_inner();
543    }
544}
545
546/// RAII ownership of one visible native calibration marker.
547///
548/// [`Self::hide`] reports removal failures. Dropping a still-visible guard sends
549/// a best-effort asynchronous hide command and cannot report failure.
550///
551/// # Examples
552///
553/// ```no_run
554/// fn remove(guard: ailloli_ui_winit::NativeCalibrationMarkerGuard) {
555///     guard.hide().unwrap();
556/// }
557/// ```
558pub struct NativeCalibrationMarkerGuard {
559    #[cfg(target_os = "linux")]
560    /// Worker command sender used for explicit or best-effort removal.
561    commands: mpsc::Sender<Command>,
562    /// Prevents duplicate hide commands after successful explicit removal.
563    visible: bool,
564}
565
566/// Reports only whether the marker guard remains visible.
567impl std::fmt::Debug for NativeCalibrationMarkerGuard {
568    /// Exposes only whether the guard still owns a visible marker.
569    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
570        formatter
571            .debug_struct("NativeCalibrationMarkerGuard")
572            .field("visible", &self.visible)
573            .finish()
574    }
575}
576
577/// Explicit marker removal.
578impl NativeCalibrationMarkerGuard {
579    /// Removes the marker and consumes the guard.
580    ///
581    /// # Errors
582    ///
583    /// Returns platform, worker-closure, timeout, or backend failures. An
584    /// already-hidden internal guard is successful.
585    ///
586    /// # Examples
587    ///
588    /// ```no_run
589    /// fn hide(guard: ailloli_ui_winit::NativeCalibrationMarkerGuard) {
590    ///     guard.hide().unwrap();
591    /// }
592    /// ```
593    pub fn hide(mut self) -> Result<(), NativeOverlayError> {
594        if !self.visible {
595            return Ok(());
596        }
597        #[cfg(target_os = "linux")]
598        {
599            let (sender, receiver) = mpsc::channel();
600            self.commands
601                .send(Command::Hide(Some(sender)))
602                .map_err(|_| NativeOverlayError::Closed)?;
603            receiver.recv_timeout(COMMAND_TIMEOUT).map_err(|_| {
604                NativeOverlayError::Backend("native calibration marker removal timed out".into())
605            })??;
606        }
607        #[cfg(not(target_os = "linux"))]
608        return Err(NativeOverlayError::Unsupported);
609        self.visible = false;
610        Ok(())
611    }
612}
613
614/// Sends a nonblocking best-effort hide when explicit removal was not requested.
615impl Drop for NativeCalibrationMarkerGuard {
616    /// Sends a nonblocking best-effort hide for a still-visible marker.
617    fn drop(&mut self) {
618        if !self.visible {
619            return;
620        }
621        #[cfg(target_os = "linux")]
622        let _ = self.commands.send(Command::Hide(None));
623        self.visible = false;
624    }
625}
626
627#[cfg(target_os = "linux")]
628/// Wayland catalogue and temporary layer-shell marker worker implementation.
629mod linux {
630    use std::collections::hash_map::DefaultHasher;
631    use std::hash::{Hash, Hasher};
632    use std::os::fd::{AsFd, AsRawFd};
633    use std::sync::mpsc;
634
635    use smithay_client_toolkit::compositor::{CompositorHandler, CompositorState, Region};
636    use smithay_client_toolkit::output::{OutputHandler, OutputState};
637    use smithay_client_toolkit::registry::{ProvidesRegistryState, RegistryState};
638    use smithay_client_toolkit::shell::wlr_layer::{
639        Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface,
640        LayerSurfaceConfigure,
641    };
642    use smithay_client_toolkit::shell::WaylandSurface;
643    use smithay_client_toolkit::shm::{slot::SlotPool, Shm, ShmHandler};
644    use smithay_client_toolkit::{
645        delegate_compositor, delegate_layer, delegate_output, delegate_registry, delegate_shm,
646        registry_handlers,
647    };
648    use wayland_client::globals::registry_queue_init;
649    use wayland_client::protocol::{wl_output, wl_shm, wl_surface};
650    use wayland_client::{Connection, QueueHandle};
651
652    use super::{
653        Command, NativeCalibrationMarkerSpec, NativeOutputDescriptor, NativeOutputScale,
654        NativeOutputTransform,
655    };
656    use crate::{NativeOverlayError, NativeOverlayRect};
657
658    /// Owns the Wayland connection until shutdown, polling protocol events every 20 ms.
659    ///
660    /// Initialization is reported through the capacity-one `ready` channel;
661    /// dropped command/reply receivers are treated as teardown, not panics.
662    ///
663    /// # Examples
664    ///
665    /// ```no_run
666    /// // `connect` starts this worker and waits for its readiness reply.
667    /// let service = ailloli_ui_winit::NativeOutputProbeService::connect()?;
668    /// service.shutdown();
669    /// # Ok::<(), ailloli_ui_winit::NativeOverlayError>(())
670    /// ```
671    pub(super) fn run(
672        commands: mpsc::Receiver<Command>,
673        ready: mpsc::SyncSender<Result<(), NativeOverlayError>>,
674    ) {
675        let initialized = Runtime::connect();
676        let Ok((mut event_queue, mut runtime)) = initialized else {
677            let _ = ready.send(initialized.map(|_| ()));
678            return;
679        };
680        let _ = ready.send(Ok(()));
681
682        let mut running = true;
683        while running {
684            if event_queue.dispatch_pending(&mut runtime).is_err() {
685                break;
686            }
687            while let Ok(command) = commands.try_recv() {
688                running = runtime.handle(command, &mut event_queue);
689                if !running {
690                    break;
691                }
692            }
693            if !running {
694                break;
695            }
696            let Some(read_guard) = event_queue.prepare_read() else {
697                continue;
698            };
699            if event_queue.flush().is_err() {
700                break;
701            }
702            let mut descriptor = libc::pollfd {
703                fd: event_queue.as_fd().as_raw_fd(),
704                events: libc::POLLIN,
705                revents: 0,
706            };
707            // SAFETY: `descriptor` points to one valid pollfd during the call.
708            let ready = unsafe { libc::poll(&mut descriptor, 1, 20) };
709            if ready > 0 && descriptor.revents & libc::POLLIN != 0 {
710                let _ = read_guard.read();
711            }
712        }
713        runtime.hide();
714    }
715
716    /// Wayland objects and acknowledgement state for the sole active marker.
717    struct ActiveMarker {
718        /// Layer-shell surface spanning the selected output.
719        layer: LayerSurface,
720        /// Empty region retained so the marker never intercepts pointer input.
721        _input_region: Region,
722        /// Generation-stamped output identity used for stale-catalogue detection.
723        descriptor: NativeOutputDescriptor,
724        /// Pixel signature specification.
725        spec: NativeCalibrationMarkerSpec,
726        /// Whether layer-shell delivered the expected configure.
727        configured: bool,
728        /// Whether a frame callback confirmed presentation.
729        presented: bool,
730        /// Deferred configure/draw failure returned to the command caller.
731        failure: Option<String>,
732    }
733
734    /// Worker-owned Wayland globals, output catalogue, shared-memory pool, and marker.
735    struct Runtime {
736        /// Registry state required by toolkit delegation.
737        registry_state: RegistryState,
738        /// Live compositor output metadata.
739        output_state: OutputState,
740        /// Surface factory.
741        compositor: CompositorState,
742        /// Layer-shell global used for overlay surfaces.
743        layer_shell: LayerShell,
744        /// Shared-memory global paired with `pool`.
745        shm: Shm,
746        /// Reusable shared-memory allocation pool, initially four bytes.
747        pool: SlotPool,
748        /// Saturating catalogue revision; zero precedes the first snapshot.
749        generation: u64,
750        /// Sorted semantic output signature from the previous refresh.
751        catalog_signature: Vec<String>,
752        /// Whether output callbacks require rebuilding the signature.
753        catalog_dirty: bool,
754        /// Sole active marker; `None` means no native calibration surface.
755        active: Option<ActiveMarker>,
756    }
757
758    /// Wayland setup, command dispatch, catalogue maintenance, and marker rendering.
759    impl Runtime {
760        /// Connects required globals, performs two metadata round trips, and snapshots outputs.
761        ///
762        /// # Errors
763        ///
764        /// Returns [`NativeOverlayError::Backend`] for Wayland connection,
765        /// registry/global binding, shared-memory pool, or round-trip failures.
766        fn connect() -> Result<(wayland_client::EventQueue<Self>, Self), NativeOverlayError> {
767            let connection = Connection::connect_to_env()
768                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
769            let (globals, mut event_queue) = registry_queue_init(&connection)
770                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
771            let qh = event_queue.handle();
772            let compositor = CompositorState::bind(&globals, &qh)
773                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
774            let layer_shell = LayerShell::bind(&globals, &qh)
775                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
776            let shm = Shm::bind(&globals, &qh)
777                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
778            let pool = SlotPool::new(4, &shm)
779                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
780            let mut runtime = Self {
781                registry_state: RegistryState::new(&globals),
782                output_state: OutputState::new(&globals, &qh),
783                compositor,
784                layer_shell,
785                shm,
786                pool,
787                generation: 0,
788                catalog_signature: Vec::new(),
789                catalog_dirty: true,
790                active: None,
791            };
792            event_queue
793                .roundtrip(&mut runtime)
794                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
795            event_queue
796                .roundtrip(&mut runtime)
797                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
798            runtime.refresh_catalogue();
799            Ok((event_queue, runtime))
800        }
801
802        /// Executes one worker command; returns `false` only for shutdown.
803        fn handle(
804            &mut self,
805            command: Command,
806            event_queue: &mut wayland_client::EventQueue<Self>,
807        ) -> bool {
808            match command {
809                Command::Snapshot(response) => {
810                    self.refresh_catalogue();
811                    let _ = response.send(Ok(self.descriptors()));
812                }
813                Command::Show {
814                    descriptor,
815                    spec,
816                    response,
817                } => {
818                    let result = self.show(descriptor, spec, event_queue);
819                    let _ = response.send(result);
820                }
821                Command::Hide(response) => {
822                    self.hide();
823                    if let Some(response) = response {
824                        let _ = response.send(Ok(()));
825                    }
826                }
827                Command::Shutdown => return false,
828            }
829            true
830        }
831
832        /// Materializes descriptors for outputs with complete valid metadata.
833        fn descriptors(&self) -> Vec<NativeOutputDescriptor> {
834            self.output_state
835                .outputs()
836                .filter_map(|output| self.descriptor_for(&output))
837                .collect()
838        }
839
840        /// Recomputes a sorted signature and saturating generation after output changes.
841        fn refresh_catalogue(&mut self) {
842            if !self.catalog_dirty && !self.catalog_signature.is_empty() {
843                return;
844            }
845            let mut signature = self
846                .output_state
847                .outputs()
848                .filter_map(|output| self.descriptor_for(&output))
849                .map(|descriptor| {
850                    format!(
851                        "{}|{:?}|{:?}|{}x{}|{}/{}|{:?}",
852                        descriptor.fingerprint,
853                        descriptor.output_name,
854                        descriptor.logical_rect,
855                        descriptor.physical_width_px,
856                        descriptor.physical_height_px,
857                        descriptor.scale.numerator,
858                        descriptor.scale.denominator,
859                        descriptor.transform
860                    )
861                })
862                .collect::<Vec<_>>();
863            signature.sort();
864            if signature != self.catalog_signature {
865                self.generation = self.generation.saturating_add(1);
866                self.catalog_signature = signature;
867            }
868            self.catalog_dirty = false;
869        }
870
871        /// Converts complete positive Wayland metadata into one descriptor.
872        ///
873        /// Rotated logical axes are swapped before scale calculation. Unequal
874        /// horizontal/vertical ratios fall back to the compositor's integer scale.
875        fn descriptor_for(&self, output: &wl_output::WlOutput) -> Option<NativeOutputDescriptor> {
876            let info = self.output_state.info(output)?;
877            let (x, y) = info.logical_position?;
878            let (logical_width, logical_height) = info.logical_size?;
879            if logical_width <= 0 || logical_height <= 0 {
880                return None;
881            }
882            let mode = info.modes.iter().find(|mode| mode.current)?;
883            if mode.dimensions.0 <= 0 || mode.dimensions.1 <= 0 {
884                return None;
885            }
886            let transform = transform(info.transform);
887            let mut hasher = DefaultHasher::new();
888            info.id.hash(&mut hasher);
889            info.name.hash(&mut hasher);
890            (x, y, logical_width, logical_height).hash(&mut hasher);
891            mode.dimensions.hash(&mut hasher);
892            info.scale_factor.hash(&mut hasher);
893            format!("{transform:?}").hash(&mut hasher);
894            let fingerprint = format!("wayland-output-{:016x}", hasher.finish());
895            let rotated = matches!(
896                transform,
897                NativeOutputTransform::Rotate90
898                    | NativeOutputTransform::Rotate270
899                    | NativeOutputTransform::Flipped90
900                    | NativeOutputTransform::Flipped270
901            );
902            let (logical_axis_width, logical_axis_height) = if rotated {
903                (logical_height as u32, logical_width as u32)
904            } else {
905                (logical_width as u32, logical_height as u32)
906            };
907            let width_ratio = super::reduced_ratio(mode.dimensions.0 as u32, logical_axis_width)?;
908            let height_ratio = super::reduced_ratio(mode.dimensions.1 as u32, logical_axis_height)?;
909            let scale = if width_ratio == height_ratio {
910                NativeOutputScale {
911                    numerator: width_ratio.0,
912                    denominator: width_ratio.1,
913                }
914            } else {
915                NativeOutputScale::integer(info.scale_factor.max(1) as u32)
916            };
917            Some(NativeOutputDescriptor {
918                fingerprint,
919                output_name: info.name,
920                logical_rect: NativeOverlayRect::new(
921                    f64::from(x),
922                    f64::from(y),
923                    f64::from(logical_width),
924                    f64::from(logical_height),
925                ),
926                physical_width_px: mode.dimensions.0 as u32,
927                physical_height_px: mode.dimensions.1 as u32,
928                scale,
929                transform,
930                catalog_generation: self.generation,
931            })
932        }
933
934        /// Replaces the active marker and waits up to eight protocol round trips for presentation.
935        ///
936        /// The descriptor must still exactly match one output in the current generation.
937        ///
938        /// # Errors
939        ///
940        /// Returns an output-missing/ambiguous error, or
941        /// [`NativeOverlayError::Backend`] for a stale catalogue, marker creation,
942        /// drawing, protocol dispatch, or unconfirmed presentation.
943        fn show(
944            &mut self,
945            descriptor: NativeOutputDescriptor,
946            spec: NativeCalibrationMarkerSpec,
947            event_queue: &mut wayland_client::EventQueue<Self>,
948        ) -> Result<(), NativeOverlayError> {
949            self.hide();
950            self.refresh_catalogue();
951            if descriptor.catalog_generation != self.generation {
952                return Err(NativeOverlayError::Backend(
953                    "native output catalogue changed during calibration".into(),
954                ));
955            }
956            let expected_generation = descriptor.catalog_generation;
957            let mut matches = self.output_state.outputs().filter(|output| {
958                self.descriptor_for(output)
959                    .is_some_and(|current| current == descriptor)
960            });
961            let output = matches
962                .next()
963                .ok_or(NativeOverlayError::OutputMatchMissing)?;
964            if matches.next().is_some() {
965                return Err(NativeOverlayError::OutputMatchAmbiguous);
966            }
967            let qh = event_queue.handle();
968            let surface = self.compositor.create_surface(&qh);
969            surface.set_buffer_scale(descriptor.scale.numerator.max(1) as i32);
970            let input_region = Region::new(&self.compositor)
971                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
972            surface.set_input_region(Some(input_region.wl_region()));
973            let layer = self.layer_shell.create_layer_surface(
974                &qh,
975                surface,
976                Layer::Overlay,
977                Some("ailloli_ui-output-calibration"),
978                Some(&output),
979            );
980            layer.set_anchor(Anchor::TOP | Anchor::RIGHT | Anchor::BOTTOM | Anchor::LEFT);
981            layer.set_size(0, 0);
982            // Cover the complete output without reserving space and without being
983            // constrained by panels that already own a positive exclusive zone.
984            layer.set_exclusive_zone(-1);
985            layer.set_keyboard_interactivity(KeyboardInteractivity::None);
986            self.active = Some(ActiveMarker {
987                layer: layer.clone(),
988                _input_region: input_region,
989                descriptor,
990                spec,
991                configured: false,
992                presented: false,
993                failure: None,
994            });
995            layer.commit();
996            for _ in 0..8 {
997                event_queue
998                    .roundtrip(self)
999                    .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
1000                if let Some(message) = self
1001                    .active
1002                    .as_ref()
1003                    .and_then(|active| active.failure.clone())
1004                {
1005                    self.hide();
1006                    return Err(NativeOverlayError::Backend(message));
1007                }
1008                if self.active.as_ref().is_some_and(|active| active.presented) {
1009                    self.refresh_catalogue();
1010                    if expected_generation != self.generation {
1011                        self.hide();
1012                        return Err(NativeOverlayError::Backend(
1013                            "native output catalogue changed during calibration".into(),
1014                        ));
1015                    }
1016                    return Ok(());
1017                }
1018            }
1019            self.hide();
1020            Err(NativeOverlayError::Backend(
1021                "calibration marker was not presented".into(),
1022            ))
1023        }
1024
1025        /// Detaches the active buffer and commits removal, if a marker exists.
1026        fn hide(&mut self) {
1027            if let Some(active) = self.active.take() {
1028                active.layer.wl_surface().attach(None, 0, 0);
1029                active.layer.commit();
1030            }
1031        }
1032
1033        /// Rasterizes the logical marker into scaled BGRA shared memory and commits it.
1034        ///
1035        /// Checked arithmetic reports dimension/stride overflow before allocation.
1036        ///
1037        /// # Errors
1038        ///
1039        /// Returns [`NativeOverlayError::Closed`] without an active marker, or a
1040        /// backend error for size/stride conversion overflow or shared-memory
1041        /// buffer creation failure.
1042        fn draw_active(&mut self, qh: &QueueHandle<Self>) -> Result<(), NativeOverlayError> {
1043            let active = self.active.as_mut().ok_or(NativeOverlayError::Closed)?;
1044            let logical_width = active.descriptor.logical_rect.width as u32;
1045            let logical_height = active.descriptor.logical_rect.height as u32;
1046            let scale = active.descriptor.scale.numerator.max(1);
1047            let width = logical_width
1048                .checked_mul(scale)
1049                .ok_or_else(|| NativeOverlayError::Backend("marker width overflow".into()))?;
1050            let height = logical_height
1051                .checked_mul(scale)
1052                .ok_or_else(|| NativeOverlayError::Backend("marker height overflow".into()))?;
1053            let stride = width
1054                .checked_mul(4)
1055                .and_then(|value| i32::try_from(value).ok())
1056                .ok_or_else(|| NativeOverlayError::Backend("marker stride overflow".into()))?;
1057            let (buffer, canvas) = self
1058                .pool
1059                .create_buffer(
1060                    i32::try_from(width).map_err(|_| {
1061                        NativeOverlayError::Backend("marker width does not fit i32".into())
1062                    })?,
1063                    i32::try_from(height).map_err(|_| {
1064                        NativeOverlayError::Backend("marker height does not fit i32".into())
1065                    })?,
1066                    stride,
1067                    wl_shm::Format::Argb8888,
1068                )
1069                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
1070            for physical_y in 0..height {
1071                for physical_x in 0..width {
1072                    let rgba = active.spec.expected_rgba(
1073                        logical_width,
1074                        logical_height,
1075                        physical_x / scale,
1076                        physical_y / scale,
1077                    );
1078                    let index = ((physical_y as usize * width as usize) + physical_x as usize) * 4;
1079                    canvas[index..index + 4].copy_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
1080                }
1081            }
1082            let surface = active.layer.wl_surface();
1083            surface.damage_buffer(0, 0, width as i32, height as i32);
1084            surface.frame(qh, surface.clone());
1085            buffer
1086                .attach_to(surface)
1087                .map_err(|error| NativeOverlayError::Backend(error.to_string()))?;
1088            active.layer.commit();
1089            Ok(())
1090        }
1091    }
1092
1093    /// Tracks marker presentation through compositor frame callbacks.
1094    impl CompositorHandler for Runtime {
1095        /// Ignores surface scale changes because the selected descriptor owns calibration scale.
1096        fn scale_factor_changed(
1097            &mut self,
1098            _connection: &Connection,
1099            _queue_handle: &QueueHandle<Self>,
1100            _surface: &wl_surface::WlSurface,
1101            _new_factor: i32,
1102        ) {
1103        }
1104
1105        /// Ignores live transform changes; output callbacks invalidate the catalogue instead.
1106        fn transform_changed(
1107            &mut self,
1108            _connection: &Connection,
1109            _queue_handle: &QueueHandle<Self>,
1110            _surface: &wl_surface::WlSurface,
1111            _new_transform: wl_output::Transform,
1112        ) {
1113        }
1114
1115        /// Marks the active marker presented when its requested frame callback arrives.
1116        fn frame(
1117            &mut self,
1118            _connection: &Connection,
1119            _queue_handle: &QueueHandle<Self>,
1120            surface: &wl_surface::WlSurface,
1121            _time: u32,
1122        ) {
1123            if let Some(active) = self.active.as_mut() {
1124                if active.layer.wl_surface() == surface {
1125                    active.presented = true;
1126                }
1127            }
1128        }
1129
1130        /// Ignores surface entry because the layer surface is pinned to one selected output.
1131        fn surface_enter(
1132            &mut self,
1133            _connection: &Connection,
1134            _queue_handle: &QueueHandle<Self>,
1135            _surface: &wl_surface::WlSurface,
1136            _output: &wl_output::WlOutput,
1137        ) {
1138        }
1139
1140        /// Ignores surface leave; closure and output callbacks handle invalidation.
1141        fn surface_leave(
1142            &mut self,
1143            _connection: &Connection,
1144            _queue_handle: &QueueHandle<Self>,
1145            _surface: &wl_surface::WlSurface,
1146            _output: &wl_output::WlOutput,
1147        ) {
1148        }
1149    }
1150
1151    /// Marks the catalogue dirty on every output lifecycle or metadata change.
1152    impl OutputHandler for Runtime {
1153        /// Returns mutable toolkit output state for delegated dispatch.
1154        fn output_state(&mut self) -> &mut OutputState {
1155            &mut self.output_state
1156        }
1157
1158        /// Invalidates the catalogue when an output appears.
1159        fn new_output(
1160            &mut self,
1161            _connection: &Connection,
1162            _queue_handle: &QueueHandle<Self>,
1163            _output: wl_output::WlOutput,
1164        ) {
1165            self.catalog_dirty = true;
1166        }
1167
1168        /// Invalidates the catalogue when output metadata changes.
1169        fn update_output(
1170            &mut self,
1171            _connection: &Connection,
1172            _queue_handle: &QueueHandle<Self>,
1173            _output: wl_output::WlOutput,
1174        ) {
1175            self.catalog_dirty = true;
1176        }
1177
1178        /// Invalidates the catalogue when an output disappears.
1179        fn output_destroyed(
1180            &mut self,
1181            _connection: &Connection,
1182            _queue_handle: &QueueHandle<Self>,
1183            _output: wl_output::WlOutput,
1184        ) {
1185            self.catalog_dirty = true;
1186        }
1187    }
1188
1189    /// Validates layer configure size, initiates drawing, and observes closure.
1190    impl LayerShellHandler for Runtime {
1191        /// Clears the active marker when the compositor closes its layer surface.
1192        fn closed(
1193            &mut self,
1194            _connection: &Connection,
1195            _queue_handle: &QueueHandle<Self>,
1196            layer: &LayerSurface,
1197        ) {
1198            if self
1199                .active
1200                .as_ref()
1201                .is_some_and(|active| &active.layer == layer)
1202            {
1203                self.active = None;
1204            }
1205        }
1206
1207        /// Accepts only the expected logical output size, then draws exactly once.
1208        fn configure(
1209            &mut self,
1210            _connection: &Connection,
1211            queue_handle: &QueueHandle<Self>,
1212            layer: &LayerSurface,
1213            configure: LayerSurfaceConfigure,
1214            _serial: u32,
1215        ) {
1216            let Some(active) = self.active.as_mut() else {
1217                return;
1218            };
1219            if &active.layer != layer || active.configured {
1220                return;
1221            }
1222            let expected = (
1223                active.descriptor.logical_rect.width as u32,
1224                active.descriptor.logical_rect.height as u32,
1225            );
1226            if configure.new_size != expected {
1227                active.failure = Some(format!(
1228                    "calibration marker configure size {:?} differs from expected {expected:?}",
1229                    configure.new_size
1230                ));
1231                return;
1232            }
1233            active.configured = true;
1234            if let Err(error) = self.draw_active(queue_handle) {
1235                if let Some(active) = self.active.as_mut() {
1236                    active.failure = Some(error.to_string());
1237                }
1238            }
1239        }
1240    }
1241
1242    /// Exposes the bound shared-memory global to delegated toolkit handlers.
1243    impl ShmHandler for Runtime {
1244        /// Returns mutable shared-memory state.
1245        fn shm_state(&mut self) -> &mut Shm {
1246            &mut self.shm
1247        }
1248    }
1249
1250    delegate_compositor!(Runtime);
1251    delegate_output!(Runtime);
1252    delegate_layer!(Runtime);
1253    delegate_shm!(Runtime);
1254    delegate_registry!(Runtime);
1255
1256    /// Exposes registry state and subscribes delegated output handlers.
1257    impl ProvidesRegistryState for Runtime {
1258        /// Returns mutable registry state.
1259        fn registry(&mut self) -> &mut RegistryState {
1260            &mut self.registry_state
1261        }
1262
1263        registry_handlers![OutputState];
1264    }
1265
1266    /// Maps every known Wayland transform and preserves future values as `Unknown`.
1267    fn transform(value: wl_output::Transform) -> NativeOutputTransform {
1268        match value {
1269            wl_output::Transform::Normal => NativeOutputTransform::Normal,
1270            wl_output::Transform::_90 => NativeOutputTransform::Rotate90,
1271            wl_output::Transform::_180 => NativeOutputTransform::Rotate180,
1272            wl_output::Transform::_270 => NativeOutputTransform::Rotate270,
1273            wl_output::Transform::Flipped => NativeOutputTransform::Flipped,
1274            wl_output::Transform::Flipped90 => NativeOutputTransform::Flipped90,
1275            wl_output::Transform::Flipped180 => NativeOutputTransform::Flipped180,
1276            wl_output::Transform::Flipped270 => NativeOutputTransform::Flipped270,
1277            _ => NativeOutputTransform::Unknown,
1278        }
1279    }
1280}
1281
1282#[cfg(test)]
1283/// Marker border width, asymmetry, and nonce/candidate binding scenarios.
1284mod tests {
1285    use super::*;
1286
1287    #[test]
1288    fn native_output_calibration_marker_is_asymmetric_and_nonce_bound() {
1289        let first = NativeCalibrationMarkerSpec::new(7, 0);
1290        let second = NativeCalibrationMarkerSpec::new(8, 1);
1291        let mut first_signature = Vec::new();
1292        let mut second_signature = Vec::new();
1293        for y in 0..720 {
1294            for x in 0..1024 {
1295                if first.pixel_role(1024, 720, x, y) == NativeCalibrationMarkerPixel::Signature {
1296                    first_signature.push((x, y));
1297                }
1298                if second.pixel_role(1024, 720, x, y) == NativeCalibrationMarkerPixel::Signature {
1299                    second_signature.push((x, y));
1300                }
1301            }
1302        }
1303        assert!(!first_signature.is_empty());
1304        assert_ne!(first_signature, second_signature);
1305        assert_eq!(
1306            first.pixel_role(1024, 720, 512, 360),
1307            NativeCalibrationMarkerPixel::Transparent
1308        );
1309    }
1310
1311    #[test]
1312    fn native_output_calibration_marker_has_five_pixel_border() {
1313        let spec = NativeCalibrationMarkerSpec::new(42, 3);
1314        assert_ne!(
1315            spec.pixel_role(800, 600, 4, 300),
1316            NativeCalibrationMarkerPixel::Transparent
1317        );
1318        assert_eq!(
1319            spec.pixel_role(800, 600, 5, 300),
1320            NativeCalibrationMarkerPixel::Transparent
1321        );
1322    }
1323}