Skip to main content

egui_pop_wayland/
lib.rs

1//! The Wayland layer of egui-pop's image viewport.
2//!
3//! winit binds no colour management and eframe configures every window
4//! 8-bit sRGB (see the register of upstream workarounds,
5//! `docs/upstream.md`), so an image cannot be shown in a wider gamut
6//! through the window's own surface. This crate gives the image a
7//! surface of its own instead, under the window, that the compositor
8//! is told the encoding of (`docs/wayland-colour.md`):
9//!
10//! - [`Display::attach`] joins the connection winit opened, from the
11//!   window's raw handles, on an event queue of its own (winit never sees
12//!   its events), and reads what the compositor's `wp_color_manager_v1`
13//!   announces ([`Capabilities`]) and its preferred image description for
14//!   the window ([`Description`], kept current by [`Display::poll`]);
15//! - [`Display::subsurface`] makes a [`Subsurface`]: a `wl_surface`
16//!   placed below the window's, synchronised with it, taking no input,
17//!   scaled through `wp_viewporter`; its [`SurfaceHandle`] is what wgpu
18//!   creates a surface on;
19//! - [`Subsurface::tag`] declares its encoding (named primaries and
20//!   transfer function), once the description is ready.
21//!
22//! The crate knows nothing of egui or wgpu; the viewport maps its plain
23//! types. On other systems, and for a window that is not a Wayland one,
24//! [`Display::attach`] answers [`Unavailable`].
25
26use std::fmt;
27
28/// The raw window handles [`Display::attach`] takes.
29pub use raw_window_handle;
30
31#[cfg(target_os = "linux")]
32mod client;
33#[cfg(target_os = "linux")]
34mod sys;
35
36#[cfg(target_os = "linux")]
37pub use client::{Display, Subsurface};
38#[cfg(target_os = "linux")]
39pub use sys::SurfaceHandle;
40
41/// Named primaries of the protocol (`wp_color_manager_v1.primaries`).
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub enum NamedPrimaries {
44    /// BT.709 / sRGB.
45    Srgb,
46    DisplayP3,
47    /// BT.2020 (and BT.2100).
48    Bt2020,
49    /// Any other, by its protocol code.
50    Other(u32),
51}
52
53impl NamedPrimaries {
54    pub fn from_code(code: u32) -> NamedPrimaries {
55        match code {
56            1 => NamedPrimaries::Srgb,
57            9 => NamedPrimaries::DisplayP3,
58            6 => NamedPrimaries::Bt2020,
59            other => NamedPrimaries::Other(other),
60        }
61    }
62
63    pub fn code(self) -> u32 {
64        match self {
65            NamedPrimaries::Srgb => 1,
66            NamedPrimaries::DisplayP3 => 9,
67            NamedPrimaries::Bt2020 => 6,
68            NamedPrimaries::Other(code) => code,
69        }
70    }
71
72    /// Its name in the protocol.
73    pub fn name(self) -> &'static str {
74        match self.code() {
75            1 => "srgb",
76            2 => "pal_m",
77            3 => "pal",
78            4 => "ntsc",
79            5 => "generic_film",
80            6 => "bt2020",
81            7 => "cie1931_xyz",
82            8 => "dci_p3",
83            9 => "display_p3",
84            10 => "adobe_rgb",
85            _ => "unknown",
86        }
87    }
88}
89
90/// Named transfer functions of the protocol
91/// (`wp_color_manager_v1.transfer_function`).
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
93pub enum NamedTransfer {
94    /// The sRGB piecewise curve (deprecated in version 2 of the
95    /// interface, announced to version 1 clients by some compositors).
96    Srgb,
97    /// A pure 2.2 power, the sRGB reference display's.
98    Gamma22,
99    /// Linear, extended range.
100    ExtLinear,
101    /// SMPTE ST 2084.
102    St2084Pq,
103    /// BT.2100 hybrid log-gamma.
104    Hlg,
105    /// Any other, by its protocol code.
106    Other(u32),
107}
108
109impl NamedTransfer {
110    pub fn from_code(code: u32) -> NamedTransfer {
111        match code {
112            9 => NamedTransfer::Srgb,
113            2 => NamedTransfer::Gamma22,
114            5 => NamedTransfer::ExtLinear,
115            11 => NamedTransfer::St2084Pq,
116            13 => NamedTransfer::Hlg,
117            other => NamedTransfer::Other(other),
118        }
119    }
120
121    pub fn code(self) -> u32 {
122        match self {
123            NamedTransfer::Srgb => 9,
124            NamedTransfer::Gamma22 => 2,
125            NamedTransfer::ExtLinear => 5,
126            NamedTransfer::St2084Pq => 11,
127            NamedTransfer::Hlg => 13,
128            NamedTransfer::Other(code) => code,
129        }
130    }
131
132    /// Its name in the protocol.
133    pub fn name(self) -> &'static str {
134        match self.code() {
135            1 => "bt1886",
136            2 => "gamma22",
137            3 => "gamma28",
138            4 => "st240",
139            5 => "ext_linear",
140            6 => "log_100",
141            7 => "log_316",
142            8 => "xvycc",
143            9 => "srgb",
144            10 => "ext_srgb",
145            11 => "st2084_pq",
146            12 => "st428",
147            13 => "hlg",
148            14 => "compound_power_2_4",
149            _ => "unknown",
150        }
151    }
152}
153
154/// Optional features of the protocol (`wp_color_manager_v1.feature`).
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
156pub enum Feature {
157    /// Parametric image descriptions (named primaries and transfer).
158    Parametric,
159    /// Values outside the primaries' volume (extended linear).
160    ExtendedTargetVolume,
161    /// Any other, by its protocol code.
162    Other(u32),
163}
164
165impl Feature {
166    pub fn from_code(code: u32) -> Feature {
167        match code {
168            1 => Feature::Parametric,
169            6 => Feature::ExtendedTargetVolume,
170            other => Feature::Other(other),
171        }
172    }
173
174    pub fn code(self) -> u32 {
175        match self {
176            Feature::Parametric => 1,
177            Feature::ExtendedTargetVolume => 6,
178            Feature::Other(code) => code,
179        }
180    }
181
182    /// Its name in the protocol.
183    pub fn name(self) -> &'static str {
184        match self.code() {
185            0 => "icc_v2_v4",
186            1 => "parametric",
187            2 => "set_primaries",
188            3 => "set_tf_power",
189            4 => "set_luminances",
190            5 => "set_mastering_display_primaries",
191            6 => "extended_target_volume",
192            7 => "windows_scrgb",
193            8 => "windows_bt2100",
194            _ => "unknown",
195        }
196    }
197}
198
199/// The name of a rendering intent's protocol code.
200pub fn intent_name(code: u32) -> &'static str {
201    match code {
202        0 => "perceptual",
203        1 => "relative",
204        2 => "saturation",
205        3 => "absolute",
206        4 => "relative_bpc",
207        5 => "absolute_no_adaptation",
208        _ => "unknown",
209    }
210}
211
212/// What the compositor's `wp_color_manager_v1` announces to a version 1
213/// client (what a Vulkan driver binding version 1 sees too).
214#[derive(Clone, Debug, Default, PartialEq, Eq)]
215pub struct Capabilities {
216    /// The interface's version the compositor offers.
217    pub version: u32,
218    pub features: Vec<Feature>,
219    pub primaries: Vec<NamedPrimaries>,
220    pub transfers: Vec<NamedTransfer>,
221    /// Rendering intents, by protocol code ([`intent_name`]).
222    pub intents: Vec<u32>,
223}
224
225impl Capabilities {
226    pub fn has_feature(&self, feature: Feature) -> bool {
227        self.features.contains(&feature)
228    }
229
230    pub fn has_primaries(&self, primaries: NamedPrimaries) -> bool {
231        self.primaries.contains(&primaries)
232    }
233
234    pub fn has_transfer(&self, transfer: NamedTransfer) -> bool {
235        self.transfers.contains(&transfer)
236    }
237
238    /// Whether a surface can be tagged with these primaries and this
239    /// transfer: a parametric description of announced names (extended
240    /// linear only with values outside the primaries allowed).
241    pub fn can_tag(&self, primaries: NamedPrimaries, transfer: NamedTransfer) -> bool {
242        self.has_feature(Feature::Parametric)
243            && self.has_primaries(primaries)
244            && self.has_transfer(transfer)
245            && (transfer != NamedTransfer::ExtLinear
246                || self.has_feature(Feature::ExtendedTargetVolume))
247    }
248
249    /// Whether a Vulkan driver presenting to a surface may already hold
250    /// its colour-management object, even for plain sRGB: Mesa's Wayland
251    /// window system integration (25.1 and later) makes one on every
252    /// swapchain's surface when the compositor announces the `srgb`
253    /// primaries with the `srgb` transfer function to a version 1
254    /// client. A second one on the same surface is a fatal protocol
255    /// error, so such a surface must not be tagged by the application.
256    pub fn wsi_claims_srgb_surfaces(&self) -> bool {
257        self.has_primaries(NamedPrimaries::Srgb) && self.has_transfer(NamedTransfer::Srgb)
258    }
259
260    /// The names of the features, primaries, transfers and intents.
261    pub fn names(&self) -> [Vec<&'static str>; 4] {
262        [
263            self.features.iter().map(|f| f.name()).collect(),
264            self.primaries.iter().map(|p| p.name()).collect(),
265            self.transfers.iter().map(|t| t.name()).collect(),
266            self.intents.iter().map(|i| intent_name(*i)).collect(),
267        ]
268    }
269}
270
271/// Chromaticities `[x, y]` of red, green, blue and white.
272pub type Chromaticities = [[f64; 2]; 4];
273
274/// Luminances in cd/m².
275#[derive(Clone, Copy, Debug, PartialEq)]
276pub struct Luminances {
277    pub min: f64,
278    pub max: f64,
279    /// The reference white's.
280    pub reference: f64,
281}
282
283/// An image description as the compositor gives it
284/// (`wp_image_description_info_v1`): the encoding it prefers for a
285/// surface, and the display's volume (the target).
286#[derive(Clone, Debug, Default, PartialEq)]
287pub struct Description {
288    pub primaries_named: Option<NamedPrimaries>,
289    pub primaries: Option<Chromaticities>,
290    pub transfer: Option<NamedTransfer>,
291    /// A pure power transfer, its exponent.
292    pub tf_power: Option<f64>,
293    pub luminances: Option<Luminances>,
294    /// The display's primaries.
295    pub target_primaries: Option<Chromaticities>,
296    /// The display's minimum and maximum luminance, in cd/m².
297    pub target_luminance: Option<[f64; 2]>,
298    pub target_max_cll: Option<u32>,
299    pub target_max_fall: Option<u32>,
300    /// Whether it came as an ICC profile.
301    pub icc: bool,
302}
303
304impl Description {
305    /// How much brighter than reference white the display goes, when
306    /// both are known (1.0 for SDR).
307    pub fn headroom(&self) -> Option<f64> {
308        let reference = self.luminances?.reference;
309        let max = self.target_luminance?[1];
310        (reference > 0.0).then(|| (max / reference).max(1.0))
311    }
312}
313
314/// Protocol chromaticities (`× 1 000 000`) as `[x, y]` pairs.
315pub fn chromaticities(v: [i32; 8]) -> Chromaticities {
316    let c = |i: usize| [f64::from(v[i]) / 1e6, f64::from(v[i + 1]) / 1e6];
317    [c(0), c(2), c(4), c(6)]
318}
319
320/// Why there is no image surface.
321#[derive(Clone, Debug, PartialEq, Eq)]
322pub enum Unavailable {
323    /// Not a Wayland window (X11, another system).
324    NotWayland,
325    /// The window's handles could not be read.
326    Handle(String),
327    /// The compositor could not be asked.
328    Connection(String),
329}
330
331impl fmt::Display for Unavailable {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        match self {
334            Unavailable::NotWayland => f.write_str("not a Wayland window (X11 or another system)"),
335            Unavailable::Handle(e) => write!(f, "the window's handles: {e}"),
336            Unavailable::Connection(e) => write!(f, "the compositor: {e}"),
337        }
338    }
339}
340
341impl std::error::Error for Unavailable {}
342
343/// [`Display::attach`] on a system without Wayland.
344#[cfg(not(target_os = "linux"))]
345#[derive(Debug)]
346pub struct Display(());
347
348#[cfg(not(target_os = "linux"))]
349impl Display {
350    /// Answers [`Unavailable::NotWayland`]: Wayland is Linux only here.
351    pub fn attach(
352        _window: &(impl raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle),
353    ) -> Result<Display, Unavailable> {
354        Err(Unavailable::NotWayland)
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    fn caps(primaries: &[u32], transfers: &[u32], features: &[u32]) -> Capabilities {
363        Capabilities {
364            version: 1,
365            features: features.iter().map(|c| Feature::from_code(*c)).collect(),
366            primaries: primaries
367                .iter()
368                .map(|c| NamedPrimaries::from_code(*c))
369                .collect(),
370            transfers: transfers
371                .iter()
372                .map(|c| NamedTransfer::from_code(*c))
373                .collect(),
374            intents: vec![0],
375        }
376    }
377
378    #[test]
379    fn codes_round_trip_and_are_named() {
380        for code in 0..16 {
381            assert_eq!(NamedPrimaries::from_code(code).code(), code);
382            assert_eq!(NamedTransfer::from_code(code).code(), code);
383            assert_eq!(Feature::from_code(code).code(), code);
384        }
385        assert_eq!(NamedPrimaries::Bt2020.name(), "bt2020");
386        assert_eq!(NamedPrimaries::DisplayP3.name(), "display_p3");
387        assert_eq!(NamedTransfer::Gamma22.name(), "gamma22");
388        assert_eq!(NamedTransfer::St2084Pq.name(), "st2084_pq");
389        assert_eq!(NamedTransfer::from_code(14).name(), "compound_power_2_4");
390        assert_eq!(Feature::Parametric.name(), "parametric");
391        assert_eq!(intent_name(1), "relative");
392    }
393
394    #[test]
395    fn tagging_needs_parametric_and_the_names() {
396        // KWin-like: no srgb transfer.
397        let kwin = caps(&[1, 6, 9], &[1, 2, 5, 11, 13], &[1, 6]);
398        assert!(kwin.can_tag(NamedPrimaries::Bt2020, NamedTransfer::Gamma22));
399        assert!(kwin.can_tag(NamedPrimaries::Srgb, NamedTransfer::ExtLinear));
400        assert!(!kwin.wsi_claims_srgb_surfaces());
401        // No parametric feature: nothing.
402        let icc_only = caps(&[1, 6], &[2], &[0]);
403        assert!(!icc_only.can_tag(NamedPrimaries::Bt2020, NamedTransfer::Gamma22));
404        // Extended linear without the extended volume: not tagged.
405        let narrow = caps(&[1, 6], &[2, 5], &[1]);
406        assert!(!narrow.can_tag(NamedPrimaries::Srgb, NamedTransfer::ExtLinear));
407        // GNOME-like, as a version 1 client sees it: srgb + srgb.
408        let gnome = caps(&[1, 6, 9], &[1, 2, 3, 5, 9, 11], &[1]);
409        assert!(gnome.can_tag(NamedPrimaries::Bt2020, NamedTransfer::Gamma22));
410        assert!(gnome.wsi_claims_srgb_surfaces());
411        assert_eq!(
412            gnome.names()[2],
413            [
414                "bt1886",
415                "gamma22",
416                "gamma28",
417                "ext_linear",
418                "srgb",
419                "st2084_pq"
420            ]
421        );
422    }
423
424    #[test]
425    fn descriptions_give_the_headroom() {
426        let mut d = Description {
427            luminances: Some(Luminances {
428                min: 0.2,
429                max: 80.0,
430                reference: 80.0,
431            }),
432            ..Description::default()
433        };
434        assert_eq!(d.headroom(), None);
435        d.target_luminance = Some([0.05, 400.0]);
436        assert_eq!(d.headroom(), Some(5.0));
437        d.target_luminance = Some([0.05, 60.0]);
438        assert_eq!(d.headroom(), Some(1.0));
439        let c = chromaticities([
440            708_000, 292_000, 170_000, 797_000, 131_000, 46_000, 312_700, 329_000,
441        ]);
442        assert_eq!(c[0], [0.708, 0.292]);
443        assert_eq!(c[3], [0.3127, 0.329]);
444    }
445}