1use std::sync::mpsc;
4#[cfg(target_os = "linux")]
5use std::thread::JoinHandle;
6use std::time::Duration;
7
8use super::{NativeOverlayError, NativeOverlayRect};
9
10const COMMAND_TIMEOUT: Duration = Duration::from_secs(6);
12pub const CALIBRATION_BORDER_LOGICAL_PX: u32 = 5;
22
23fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct NativeOutputScale {
55 pub numerator: u32,
57 pub denominator: u32,
59}
60
61impl NativeOutputScale {
63 pub const fn integer(value: u32) -> Self {
72 Self {
73 numerator: value,
74 denominator: 1,
75 }
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum NativeOutputTransform {
90 Normal,
92 Rotate90,
94 Rotate180,
96 Rotate270,
98 Flipped,
100 Flipped90,
102 Flipped180,
104 Flipped270,
106 Unknown,
108}
109
110#[derive(Debug, Clone, PartialEq)]
131pub struct NativeOutputDescriptor {
132 pub fingerprint: String,
134 pub output_name: Option<String>,
136 pub logical_rect: NativeOverlayRect,
138 pub physical_width_px: u32,
140 pub physical_height_px: u32,
142 pub scale: NativeOutputScale,
144 pub transform: NativeOutputTransform,
146 pub catalog_generation: u64,
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub struct NativeCalibrationMarkerSpec {
164 pub nonce: u64,
166 pub candidate_ordinal: u32,
168}
169
170impl NativeCalibrationMarkerSpec {
172 pub const BORDER_RGBA: [u8; 4] = [239, 24, 24, 255];
180 pub const SIGNATURE_RGBA: [u8; 4] = [0, 221, 255, 255];
188 pub const TRANSPARENT_RGBA: [u8; 4] = [0, 0, 0, 0];
196
197 pub const fn new(nonce: u64, candidate_ordinal: u32) -> Self {
206 Self {
207 nonce,
208 candidate_ordinal,
209 }
210 }
211
212 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 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
284fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub enum NativeCalibrationMarkerPixel {
304 Transparent,
306 Border,
308 Signature,
310}
311
312#[cfg(target_os = "linux")]
313enum Command {
315 Snapshot(mpsc::Sender<Result<Vec<NativeOutputDescriptor>, NativeOverlayError>>),
317 Show {
319 descriptor: NativeOutputDescriptor,
321 spec: NativeCalibrationMarkerSpec,
323 response: mpsc::Sender<Result<(), NativeOverlayError>>,
325 },
326 Hide(Option<mpsc::Sender<Result<(), NativeOverlayError>>>),
328 Shutdown,
330}
331
332pub struct NativeOutputProbeService {
346 #[cfg(target_os = "linux")]
347 commands: mpsc::Sender<Command>,
349 #[cfg(target_os = "linux")]
350 worker: Option<JoinHandle<()>>,
352}
353
354impl std::fmt::Debug for NativeOutputProbeService {
356 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358 formatter
359 .debug_struct("NativeOutputProbeService")
360 .finish_non_exhaustive()
361 }
362}
363
364impl NativeOutputProbeService {
366 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 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 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 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 pub fn shutdown(mut self) {
523 self.shutdown_inner();
524 }
525
526 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
538impl Drop for NativeOutputProbeService {
540 fn drop(&mut self) {
542 self.shutdown_inner();
543 }
544}
545
546pub struct NativeCalibrationMarkerGuard {
559 #[cfg(target_os = "linux")]
560 commands: mpsc::Sender<Command>,
562 visible: bool,
564}
565
566impl std::fmt::Debug for NativeCalibrationMarkerGuard {
568 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
577impl NativeCalibrationMarkerGuard {
579 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
614impl Drop for NativeCalibrationMarkerGuard {
616 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")]
628mod 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 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 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 struct ActiveMarker {
718 layer: LayerSurface,
720 _input_region: Region,
722 descriptor: NativeOutputDescriptor,
724 spec: NativeCalibrationMarkerSpec,
726 configured: bool,
728 presented: bool,
730 failure: Option<String>,
732 }
733
734 struct Runtime {
736 registry_state: RegistryState,
738 output_state: OutputState,
740 compositor: CompositorState,
742 layer_shell: LayerShell,
744 shm: Shm,
746 pool: SlotPool,
748 generation: u64,
750 catalog_signature: Vec<String>,
752 catalog_dirty: bool,
754 active: Option<ActiveMarker>,
756 }
757
758 impl Runtime {
760 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 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 fn descriptors(&self) -> Vec<NativeOutputDescriptor> {
834 self.output_state
835 .outputs()
836 .filter_map(|output| self.descriptor_for(&output))
837 .collect()
838 }
839
840 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 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 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 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 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 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 impl CompositorHandler for Runtime {
1095 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 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 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 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 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 impl OutputHandler for Runtime {
1153 fn output_state(&mut self) -> &mut OutputState {
1155 &mut self.output_state
1156 }
1157
1158 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 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 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 impl LayerShellHandler for Runtime {
1191 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 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 impl ShmHandler for Runtime {
1244 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 impl ProvidesRegistryState for Runtime {
1258 fn registry(&mut self) -> &mut RegistryState {
1260 &mut self.registry_state
1261 }
1262
1263 registry_handlers![OutputState];
1264 }
1265
1266 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)]
1283mod 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}