Skip to main content

egui_pop_viewport/
image_surface.rs

1//! The image's own surface (feature `wayland`): on a Wayland compositor
2//! with colour management, the viewport draws its image into a surface
3//! of its own, below the window, that the compositor is told the
4//! encoding of; egui's interface stays sRGB on the window's surface
5//! (`docs/wayland-colour.md`).
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! - [`install`] (once, with eframe's creation context) joins the
11//!   compositor through the main window's handles and records what it
12//!   offers ([`Offer`]): its colour manager's announcements, the formats
13//!   and colour spaces a subsurface can be presented in.
14//! - Every other window gets an image surface of its own, under its own
15//!   surface and negotiated for what that window wants: set up with its
16//!   handles ([`install_window`]), or the first frame it draws the image
17//!   once [`set_window_source`] says where windows' handles are read;
18//!   freed when the window closes ([`close_window`], or at the next frame
19//!   once egui no longer knows the window). egui's interface keeps
20//!   egui-wgpu's one surface format in every window.
21//! - Each frame, a window's viewports [`negotiate`] what the application
22//!   wants for that window ([`display::want`]) against its offer
23//!   ([`negotiate_window`]):
24//!   - [`Route::Tagged`]: a subsurface egui-pop tags itself through
25//!     `wp_color_management_v1` (BT.2020 with a 2.2 power, for one;
26//!     KWin, sway, Weston);
27//!   - [`Route::Wsi`]: a subsurface presented in a colour space the
28//!     driver's window system integration declares (Display P3 where the
29//!     compositor announces the sRGB transfer: GNOME, Hyprland);
30//!   - [`Route::Window`]: the window's surface, sRGB, and why
31//!     ([`display::Resolution::reason`]).
32//! - With an image surface, the viewport renders its tiles there,
33//!   presents it just before egui presents the window (both apply in the
34//!   same compositor frame), and punches a transparent hole in the
35//!   interface where the image is: overlays, menus and tooltips drawn
36//!   after stay above it. The window must be transparent
37//!   (`ViewportBuilder::with_transparent(true)`), or the hole would show
38//!   black.
39//!
40//! The `EGUI_POP_IMAGE_SURFACE` variable turns it `off`, or keeps the
41//! driver's colour spaces only (`no-tag`). The debug bridge's `viewport`
42//! collector reports it ([`report`]), with the compositor's preferred
43//! image description for each window; the window registry
44//! (`windows.list`) shows each window's (`egui_pop_core::window_surface`).
45
46use std::collections::HashMap;
47use std::sync::atomic::{AtomicBool, Ordering};
48use std::sync::{Arc, Mutex, MutexGuard};
49
50use egui::{Color32, Context, ViewportId};
51use egui_pop_core::state::Slot;
52use egui_pop_wayland::{Capabilities, Feature, NamedPrimaries, NamedTransfer};
53use egui_wgpu::wgpu;
54use serde_json::{Value as Json, json};
55
56use crate::display::{
57    self, ColorSpace, DisplayTarget, HDR_REFERENCE_WHITE, Primaries, Stage, SurfaceFormat,
58    TargetSource, Transfer,
59};
60use crate::gpu::{Resources, TilePaint};
61
62/// The raw window handles [`install`] takes (eframe's creation context
63/// implements both traits).
64pub use egui_pop_wayland::raw_window_handle;
65
66/// The environment variable: `off` (no image surface), `no-tag` (the
67/// driver's colour spaces only), anything else or unset (both).
68pub const VARIABLE: &str = "EGUI_POP_IMAGE_SURFACE";
69
70/// What the platform offers an image surface.
71#[derive(Clone, Debug, Default, PartialEq)]
72pub struct Offer {
73    /// Why there is no image surface at all (not Wayland, an opaque
74    /// window, no subsurfaces, turned off), if there is none.
75    pub unavailable: Option<String>,
76    /// The colour manager's announcements (to a version 1 client),
77    /// `None` without one.
78    pub colour: Option<Capabilities>,
79    /// The formats and colour spaces an image surface can be presented
80    /// in, as its driver offers them.
81    pub wsi: Vec<(SurfaceFormat, ColorSpace)>,
82    /// Whether egui-pop may tag the image surface itself.
83    pub may_tag: bool,
84}
85
86impl Offer {
87    /// No image surface, and why.
88    pub fn unavailable(why: impl Into<String>) -> Offer {
89        Offer {
90            unavailable: Some(why.into()),
91            ..Offer::default()
92        }
93    }
94}
95
96/// Where the image is drawn.
97#[derive(Clone, Copy, Debug, PartialEq)]
98pub enum Route {
99    /// On the window's surface.
100    Window,
101    /// On an image surface egui-pop tagged through the protocol.
102    Tagged(DisplayTarget),
103    /// On an image surface in a colour space the driver declares.
104    Wsi(DisplayTarget),
105}
106
107impl Route {
108    /// What the image surface expects, when there is one.
109    pub fn target(&self) -> Option<DisplayTarget> {
110        match self {
111            Route::Window => None,
112            Route::Tagged(t) | Route::Wsi(t) => Some(*t),
113        }
114    }
115
116    pub fn name(&self) -> &'static str {
117        match self {
118            Route::Window => "window",
119            Route::Tagged(_) => "tagged",
120            Route::Wsi(_) => "wsi",
121        }
122    }
123}
124
125/// Where the image goes for a wanted target, and why not better.
126#[derive(Clone, Debug, PartialEq)]
127pub struct Negotiation {
128    pub route: Route,
129    /// Why the image stays on the window's surface, or gets less than
130    /// wanted.
131    pub why: Option<String>,
132}
133
134/// The protocol's name for primaries (custom ones have none).
135pub fn named_primaries(primaries: Primaries) -> Option<NamedPrimaries> {
136    match primaries {
137        Primaries::Srgb => Some(NamedPrimaries::Srgb),
138        Primaries::DisplayP3 => Some(NamedPrimaries::DisplayP3),
139        Primaries::Bt2020 => Some(NamedPrimaries::Bt2020),
140        Primaries::Custom { .. } => None,
141    }
142}
143
144/// The protocol's name for a transfer (extended sRGB has none).
145pub fn named_transfer(transfer: Transfer) -> Option<NamedTransfer> {
146    match transfer {
147        Transfer::SrgbPiecewise => Some(NamedTransfer::Srgb),
148        Transfer::Gamma22 => Some(NamedTransfer::Gamma22),
149        Transfer::ExtLinear => Some(NamedTransfer::ExtLinear),
150        Transfer::Pq => Some(NamedTransfer::St2084Pq),
151        Transfer::Hlg => Some(NamedTransfer::Hlg),
152        Transfer::ExtSrgb => None,
153    }
154}
155
156/// Whether a target carries anything sRGB does not.
157fn wider_than_srgb(t: &DisplayTarget) -> bool {
158    t.primaries.rank() > 0 || t.transfer.is_hdr()
159}
160
161/// The format to tag for a transfer, among those offered with the sRGB
162/// colour space (the driver then leaves the surface's colour alone).
163fn tag_format(transfer: Transfer, formats: &[SurfaceFormat]) -> Option<SurfaceFormat> {
164    use SurfaceFormat as F;
165    let order: &[SurfaceFormat] = match transfer {
166        Transfer::ExtLinear | Transfer::ExtSrgb => &[F::Rgba16Float],
167        Transfer::Pq | Transfer::Hlg => &[F::Rgb10a2Unorm, F::Rgba16Float],
168        Transfer::SrgbPiecewise | Transfer::Gamma22 => {
169            &[F::Rgb10a2Unorm, F::Rgba8Unorm, F::Rgba16Float]
170        }
171    };
172    order.iter().copied().find(|f| formats.contains(f))
173}
174
175/// The encoding to tag the image surface with: the wanted primaries (or
176/// BT.2020, which holds them) with the wanted transfer (or a 2.2 power,
177/// or the sRGB curve), the first the compositor takes on an offered
178/// format.
179fn tag(
180    wanted: &DisplayTarget,
181    caps: &Capabilities,
182    offer: &Offer,
183) -> Result<DisplayTarget, String> {
184    if !offer.may_tag {
185        return Err(format!("tagging is turned off ({VARIABLE}=no-tag)"));
186    }
187    // upstream: Mesa holds the colour object of sRGB swapchains and wgpu
188    // has no pass-through colour space (docs/upstream.md, Wayland).
189    if caps.wsi_claims_srgb_surfaces() {
190        return Err(
191            "the compositor announces sRGB with the sRGB transfer, so the driver's \
192                    window system integration may hold the image surface's colour itself \
193                    (Mesa does): egui-pop does not tag it"
194                .into(),
195        );
196    }
197    if !caps.has_feature(Feature::Parametric) {
198        return Err("the compositor takes no parametric image description".into());
199    }
200    let formats: Vec<SurfaceFormat> = offer
201        .wsi
202        .iter()
203        .filter(|(_, space)| *space == ColorSpace::Srgb)
204        .map(|(format, _)| *format)
205        .collect();
206    let mut primaries = vec![wanted.primaries];
207    if wanted.primaries != Primaries::Bt2020 {
208        primaries.push(Primaries::Bt2020);
209    }
210    let mut transfers = vec![wanted.transfer];
211    for t in [Transfer::Gamma22, Transfer::SrgbPiecewise] {
212        if !transfers.contains(&t) {
213            transfers.push(t);
214        }
215    }
216    for &transfer in &transfers {
217        for &p in &primaries {
218            let (Some(np), Some(nt)) = (named_primaries(p), named_transfer(transfer)) else {
219                continue;
220            };
221            if !caps.can_tag(np, nt) {
222                continue;
223            }
224            let Some(format) = tag_format(transfer, &formats) else {
225                continue;
226            };
227            let white = match transfer {
228                Transfer::Pq | Transfer::Hlg => HDR_REFERENCE_WHITE,
229                _ => 80.0,
230            };
231            let target = DisplayTarget {
232                primaries: p,
233                transfer,
234                sdr_white_nits: white,
235                headroom: if transfer.is_hdr() {
236                    wanted.headroom.clamp(1.0, transfer.max_headroom(white))
237                } else {
238                    1.0
239                },
240                surface_format: format,
241                source: TargetSource::Tagged,
242            };
243            if wider_than_srgb(&target) && target.is_supported() {
244                return Ok(target);
245            }
246        }
247    }
248    if formats.is_empty() {
249        return Err("the image surface's driver offers no format to tag".into());
250    }
251    let [_, prims, tfs, _] = caps.names();
252    Err(format!(
253        "the compositor takes no encoding wider than sRGB for {} (it announces the primaries {} and the transfers {})",
254        wanted.describe(),
255        prims.join(", "),
256        tfs.join(", ")
257    ))
258}
259
260/// The driver's colour space for the image surface: an SDR one for an
261/// SDR wish, then one carrying the wish, then the widest gamut, then the
262/// fewest bits.
263fn wsi(wanted: &DisplayTarget, pairs: &[(SurfaceFormat, ColorSpace)]) -> Option<DisplayTarget> {
264    let mut best: Option<(u32, DisplayTarget)> = None;
265    for &(format, space) in pairs {
266        if space == ColorSpace::Srgb
267            || matches!(format, SurfaceFormat::Rgba8UnormSrgb | SurfaceFormat::Other)
268        {
269            continue;
270        }
271        let target = DisplayTarget::for_color_space(
272            space,
273            format,
274            wanted.headroom.max(1.0),
275            TargetSource::Wsi,
276        );
277        if !target.is_supported() || !wider_than_srgb(&target) {
278            continue;
279        }
280        let same_kind =
281            wanted.transfer.is_hdr() || !matches!(target.transfer, Transfer::Pq | Transfer::Hlg);
282        let carries = target.missing(wanted).is_none();
283        let gamut = if target.transfer.is_extended() {
284            3
285        } else {
286            u32::from(target.primaries.rank())
287        };
288        let score = u32::from(same_kind) * 2000
289            + u32::from(carries) * 1000
290            + gamut * 50
291            + (32 - u32::from(format.bits().min(32)) / 2);
292        if best.is_none_or(|(s, _)| score > s) {
293            best = Some((score, target));
294        }
295    }
296    best.map(|(_, t)| t)
297}
298
299/// Where the image goes for `wanted`, given what the platform offers:
300/// the window's surface for sRGB or without an image surface; else a
301/// surface tagged by egui-pop when it may and the compositor takes the
302/// encoding; else one in a colour space the driver declares; else the
303/// window's, with why each step failed.
304pub fn negotiate(wanted: &DisplayTarget, offer: &Offer) -> Negotiation {
305    let window = |why: Option<String>| Negotiation {
306        route: Route::Window,
307        why,
308    };
309    if !wider_than_srgb(wanted) {
310        return window(None);
311    }
312    if let Some(why) = &offer.unavailable {
313        return window(Some(why.clone()));
314    }
315    let mut why = Vec::new();
316    match &offer.colour {
317        None => why.push("the compositor has no colour management (wp_color_manager_v1)".into()),
318        Some(caps) => match tag(wanted, caps, offer) {
319            Ok(target) => {
320                return Negotiation {
321                    route: Route::Tagged(target),
322                    why: None,
323                };
324            }
325            Err(e) => why.push(e),
326        },
327    }
328    match wsi(wanted, &offer.wsi) {
329        Some(target) => Negotiation {
330            route: Route::Wsi(target),
331            why: target.missing(wanted).map(|_| why.join("; ")),
332        },
333        None => {
334            why.push("the image surface's driver offers no colour space wider than sRGB".into());
335            window(Some(why.join("; ")))
336        }
337    }
338}
339
340/// Where an image surface sits for an image rectangle.
341#[derive(Clone, Copy, Debug, PartialEq)]
342pub struct Layout {
343    /// `[x, y, width, height]` in logical pixels of the window's surface:
344    /// whole pixels covering the rectangle (the overflow hides under the
345    /// interface).
346    pub logical: [i32; 4],
347    /// The buffer's size in physical pixels.
348    pub buffer: [u32; 2],
349    /// The buffer's top left in window pixels.
350    pub origin: [f32; 2],
351}
352
353/// The image surface's place for a rectangle `[x0, y0, x1, y1]` in
354/// window pixels, at `scale` physical pixels per logical one; `None` for
355/// an empty one.
356pub fn layout(rect_px: [f32; 4], scale: f32) -> Option<Layout> {
357    let scale = if scale > 0.0 { scale } else { 1.0 };
358    let x0 = (rect_px[0] / scale).floor() as i32;
359    let y0 = (rect_px[1] / scale).floor() as i32;
360    let x1 = (rect_px[2] / scale).ceil() as i32;
361    let y1 = (rect_px[3] / scale).ceil() as i32;
362    let (w, h) = (x1 - x0, y1 - y0);
363    if w <= 0 || h <= 0 {
364        return None;
365    }
366    Some(Layout {
367        logical: [x0, y0, w, h],
368        buffer: [
369            ((w as f32 * scale).round() as u32).max(1),
370            ((h as f32 * scale).round() as u32).max(1),
371        ],
372        origin: [x0 as f32 * scale, y0 as f32 * scale],
373    })
374}
375
376/// An sRGB colour encoded for a target (the image surface's background).
377pub fn clear_colour(colour: Color32, target: &DisplayTarget) -> [f64; 4] {
378    let linear = egui::Rgba::from(colour);
379    let e = Stage::convert(Primaries::Srgb, target).encode([linear.r(), linear.g(), linear.b()]);
380    [f64::from(e[0]), f64::from(e[1]), f64::from(e[2]), 1.0]
381}
382
383/// How [`install`] sets up image surfaces.
384#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
385pub struct Options {
386    /// The window was built transparent
387    /// (`ViewportBuilder::with_transparent(true)`): required, the image
388    /// surface shows through a hole in it.
389    pub transparent_window: bool,
390}
391
392/// A window's raw handles, as [`set_window_source`] gives them.
393pub trait WindowHandles:
394    raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle
395{
396}
397
398impl<T: raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle + ?Sized>
399    WindowHandles for T
400{
401}
402
403/// Where the handles of a window opened after [`install`] are read.
404type Source = Arc<dyn Fn(ViewportId) -> Option<Box<dyn WindowHandles>> + Send + Sync>;
405
406/// One window's image surface: what its platform offers, what was
407/// negotiated there, and the surfaces made under it.
408#[derive(Default)]
409struct WindowSurface {
410    offer: Offer,
411    negotiated: Option<(DisplayTarget, Negotiation)>,
412    /// Why the image surface failed (it then stays on the window until
413    /// the wish changes).
414    failure: Option<String>,
415    #[cfg(target_os = "linux")]
416    manager: Option<wl::Manager>,
417}
418
419impl WindowSurface {
420    fn new(offer: Offer) -> WindowSurface {
421        WindowSurface {
422            offer,
423            ..WindowSurface::default()
424        }
425    }
426}
427
428#[derive(Default)]
429struct Shared {
430    /// The render state [`install`] was given, for the windows after.
431    render: Option<egui_wgpu::RenderState>,
432    /// The image surface of each window, the main window's from
433    /// [`install`], another's once it draws the image.
434    windows: HashMap<ViewportId, WindowSurface>,
435    /// Where another window's handles are read, and how it was built.
436    source: Option<(Source, Options)>,
437}
438
439/// The image surfaces of a context, shared with the paint callbacks.
440#[derive(Clone)]
441pub(crate) struct ImageSurfaces(Arc<Mutex<Shared>>);
442
443impl std::fmt::Debug for ImageSurfaces {
444    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445        f.debug_struct("ImageSurfaces").finish_non_exhaustive()
446    }
447}
448
449impl ImageSurfaces {
450    fn lock(&self) -> MutexGuard<'_, Shared> {
451        self.0
452            .lock()
453            .unwrap_or_else(std::sync::PoisonError::into_inner)
454    }
455}
456
457const SURFACES: Slot<ImageSurfaces> = Slot::opaque("viewport.image_surface");
458
459/// What the platform offers a window's image surface: joins the
460/// compositor through the window's own handles, with a manager of its
461/// own (one parent surface per window).
462fn offer_for(
463    rs: &egui_wgpu::RenderState,
464    window: &(impl raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle),
465    options: Options,
466) -> WindowSurface {
467    let mode = std::env::var(VARIABLE).unwrap_or_default();
468    if mode == "off" {
469        return WindowSurface::new(Offer::unavailable(format!("turned off ({VARIABLE}=off)")));
470    }
471    if !options.transparent_window {
472        return WindowSurface::new(Offer::unavailable(
473            "the window is opaque: the image surface sits below it and needs a transparent \
474             window (ViewportBuilder::with_transparent)",
475        ));
476    }
477    #[cfg(target_os = "linux")]
478    match wl::Manager::new(rs, window) {
479        Ok((manager, mut offer)) => {
480            offer.may_tag = mode != "no-tag";
481            WindowSurface {
482                manager: Some(manager),
483                ..WindowSurface::new(offer)
484            }
485        }
486        Err(e) => WindowSurface::new(Offer::unavailable(e)),
487    }
488    #[cfg(not(target_os = "linux"))]
489    {
490        let _ = (rs, window);
491        WindowSurface::new(Offer::unavailable(
492            "not a Wayland window (X11 or another system)",
493        ))
494    }
495}
496
497/// The image surfaces of `ctx`, made empty the first time.
498fn surfaces(ctx: &Context) -> ImageSurfaces {
499    SURFACES.get_or_insert_with(ctx, || {
500        ImageSurfaces(Arc::new(Mutex::new(Shared::default())))
501    })
502}
503
504/// Sets up image surfaces for the main window: `rs` is the render state
505/// the GPU path was installed on ([`crate::gpu::install`]), `window` the
506/// main window's handles (eframe's creation context). Returns what the
507/// platform offers; viewports in the main window use it from the next
508/// frame. Other windows get theirs with [`install_window`], or as they
509/// draw the image once [`set_window_source`] says where their handles
510/// are.
511// upstream: winit binds no colour management and egui-wgpu takes no
512// colour space, hence a surface of the image's own (docs/upstream.md).
513pub fn install(
514    ctx: &Context,
515    rs: &egui_wgpu::RenderState,
516    window: &(impl raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle),
517    options: Options,
518) -> Offer {
519    let surfaces = surfaces(ctx);
520    let window = offer_for(rs, window, options);
521    let offer = window.offer.clone();
522    {
523        let mut s = surfaces.lock();
524        s.render = Some(rs.clone());
525        s.windows.insert(ViewportId::ROOT, window);
526    }
527    ctx.request_repaint();
528    offer
529}
530
531/// Sets up the image surface of another window (`viewport`), with its
532/// own handles, after [`install`] (whose render state it shares): its
533/// own parent surface, negotiated for what that window wants. Returns
534/// what the platform offers it; it is freed when the window closes
535/// ([`close_window`]). Without [`install`] first, none and why.
536pub fn install_window(
537    ctx: &Context,
538    viewport: ViewportId,
539    window: &(impl raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle),
540    options: Options,
541) -> Offer {
542    let surfaces = surfaces(ctx);
543    let mut s = surfaces.lock();
544    let w = match s.render.clone() {
545        Some(rs) => offer_for(&rs, window, options),
546        None => WindowSurface::new(Offer::unavailable(
547            "the image surfaces are not installed (image_surface::install, with the main window)",
548        )),
549    };
550    let offer = w.offer.clone();
551    s.windows.insert(viewport, w);
552    drop(s);
553    ctx.request_repaint_of(viewport);
554    offer
555}
556
557/// Says where the handles of a window opened after [`install`] are read
558/// (`egui_pop::api::runner::window` on egui-pop's runner), and how such
559/// windows are built (`options`): a window drawing the image gets its own
560/// image surface the first frame its handles are known, freed when it
561/// closes. A window whose builder said how it was built
562/// (`egui_pop_core::window_surface::set_transparency`) is taken as said:
563/// transparent, it gets a surface whatever `options` say; opaque, none,
564/// with the builder's reason.
565pub fn set_window_source<W>(
566    ctx: &Context,
567    options: Options,
568    source: impl Fn(ViewportId) -> Option<W> + Send + Sync + 'static,
569) where
570    W: raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle + 'static,
571{
572    let source: Source =
573        Arc::new(move |v| source(v).map(|w| Box::new(w) as Box<dyn WindowHandles>));
574    surfaces(ctx).lock().source = Some((source, options));
575}
576
577/// Records what a window's platform offers without joining it: no
578/// surface is made, only the negotiation and its state (a test's fake
579/// compositor, or a host presenting the image surface itself). The
580/// viewport's widget then sends the image to that surface: use it where
581/// something presents it.
582pub fn install_offer(ctx: &Context, viewport: ViewportId, offer: Offer) {
583    surfaces(ctx)
584        .lock()
585        .windows
586        .insert(viewport, WindowSurface::new(offer));
587    ctx.request_repaint_of(viewport);
588}
589
590/// Frees a window's image surface (the window closed): its subsurfaces
591/// and connection go, its state is forgotten. Windows egui no longer
592/// knows are freed this way at the next frame.
593pub fn close_window(ctx: &Context, viewport: ViewportId) {
594    if let Some(surfaces) = SURFACES.get(ctx) {
595        let gone = surfaces.lock().windows.remove(&viewport);
596        drop(gone);
597    }
598    display::set_image_surface(ctx, viewport, display::ImageSurface::default());
599    egui_pop_core::window_surface::set(ctx, viewport, None);
600}
601
602/// What [`install`] found for the main window, if it ran.
603pub fn offer(ctx: &Context) -> Option<Offer> {
604    offer_of(ctx, ViewportId::ROOT)
605}
606
607/// What the platform offers a window's image surface, once set up.
608pub fn offer_of(ctx: &Context, viewport: ViewportId) -> Option<Offer> {
609    let surfaces = SURFACES.get(ctx)?;
610    let s = surfaces.lock();
611    s.windows.get(&viewport).map(|w| w.offer.clone())
612}
613
614/// The windows with an image surface set up, the main window first.
615pub fn windows(ctx: &Context) -> Vec<ViewportId> {
616    let Some(surfaces) = SURFACES.get(ctx) else {
617        return Vec::new();
618    };
619    let s = surfaces.lock();
620    let mut out: Vec<ViewportId> = s.windows.keys().copied().collect();
621    out.sort_by_key(|v| (*v != ViewportId::ROOT, format!("{v:?}")));
622    out
623}
624
625/// A window's image surface as `windows.list` shows it.
626fn state(wanted: &DisplayTarget, n: &Negotiation) -> Json {
627    let target = n.route.target();
628    json!({
629        "kind": "image",
630        "route": n.route.name(),
631        "wanted": wanted.describe(),
632        "format": target.map(|t| format!("{:?}", t.surface_format)),
633        "colour_space": target.map(|t| t.describe()),
634        "why": n.why,
635    })
636}
637
638/// Where the image of `viewport` goes for what it wants
639/// ([`display::want`]): negotiates against that window's offer when the
640/// wish changes, records the image surface's target and why
641/// ([`display::set_image_surface`], and the window's entry in
642/// `windows.list`). The viewport calls it each frame it draws the image
643/// on the GPU path; call it yourself only with an offer from
644/// [`install_offer`] (tests).
645pub fn negotiate_window(ctx: &Context, viewport: ViewportId) -> Negotiation {
646    let window = |why: Option<String>| Negotiation {
647        route: Route::Window,
648        why,
649    };
650    let Some(surfaces) = SURFACES.get(ctx) else {
651        return window(None);
652    };
653    let wanted = display::wanted_of(ctx, viewport);
654    // Windows egui no longer knows closed: their surfaces go.
655    let open: Vec<ViewportId> = ctx.input(|i| i.raw.viewports.keys().copied().collect());
656    let closed: Vec<ViewportId> = if open.contains(&ViewportId::ROOT) {
657        let s = surfaces.lock();
658        s.windows
659            .keys()
660            .filter(|v| **v != ViewportId::ROOT && !open.contains(v))
661            .copied()
662            .collect()
663    } else {
664        Vec::new()
665    };
666    for v in closed {
667        close_window(ctx, v);
668    }
669    // How the window was built, when its builder said it: an opaque
670    // window gets no surface, whatever the source's options say.
671    let built = egui_pop_core::window_surface::transparency(ctx, viewport);
672    let opaque = built
673        .as_ref()
674        .and_then(|t| t.why_opaque())
675        .map(|why| format!("the window is opaque ({why}): the image surface sits below it"));
676    let negotiation = {
677        let mut s = surfaces.lock();
678        let mut no_render = false;
679        if !s.windows.contains_key(&viewport) && wider_than_srgb(&wanted) && opaque.is_none() {
680            let handles = s.source.as_ref().map(|(source, o)| (source(viewport), *o));
681            if let Some((Some(handles), mut options)) = handles {
682                if built.as_ref().is_some_and(|t| t.is_transparent()) {
683                    options.transparent_window = true;
684                }
685                match s.render.clone() {
686                    Some(rs) => {
687                        let w = offer_for(&rs, &handles, options);
688                        s.windows.insert(viewport, w);
689                    }
690                    None => no_render = true,
691                }
692            }
693        }
694        match s.windows.get_mut(&viewport) {
695            None => window(wider_than_srgb(&wanted).then(|| {
696                if let Some(why) = &opaque {
697                    why.clone()
698                } else if no_render {
699                    "the image surfaces are not installed (image_surface::install, with the \
700                     main window)"
701                        .to_string()
702                } else if s.source.is_some() {
703                    "the window's handles are not known yet".to_string()
704                } else {
705                    "no image surface for this window (image_surface::install_window, or \
706                     set_window_source)"
707                        .to_string()
708                }
709            })),
710            Some(w) => {
711                #[cfg(target_os = "linux")]
712                if let Some(Err(e)) = w.manager.as_mut().map(wl::Manager::poll) {
713                    w.failure = Some(format!("the compositor's events: {e}"));
714                }
715                if w.negotiated.as_ref().is_none_or(|(old, _)| *old != wanted) {
716                    w.failure = None;
717                    let n = negotiate(&wanted, &w.offer);
718                    w.negotiated = Some((wanted, n));
719                }
720                let mut n = w
721                    .negotiated
722                    .as_ref()
723                    .map(|(_, n)| n.clone())
724                    .unwrap_or(window(None));
725                if let Some(f) = &w.failure
726                    && n.route != Route::Window
727                {
728                    n = window(Some(format!("the image surface failed: {f}")));
729                }
730                #[cfg(target_os = "linux")]
731                if let Some(m) = w.manager.as_mut() {
732                    if n.route == Route::Window {
733                        m.clear();
734                    } else {
735                        m.collect(ctx.cumulative_pass_nr());
736                    }
737                }
738                n
739            }
740        }
741    };
742    display::set_image_surface(
743        ctx,
744        viewport,
745        display::ImageSurface {
746            target: negotiation.route.target(),
747            why: negotiation.why.clone(),
748        },
749    );
750    egui_pop_core::window_surface::set(ctx, viewport, Some(state(&wanted, &negotiation)));
751    negotiation
752}
753
754/// Where the image of the window `viewport` goes, on the GPU path
755/// ([`negotiate_window`]); the image surfaces when it has one.
756pub(crate) fn frame(ctx: &Context, viewport: ViewportId) -> Option<(ImageSurfaces, Route)> {
757    let surfaces = SURFACES.get(ctx)?;
758    let n = negotiate_window(ctx, viewport);
759    (n.route != Route::Window).then_some((surfaces, n.route))
760}
761
762/// One viewport's image for its image surface, and the hole for it in
763/// the window.
764#[cfg_attr(
765    not(target_os = "linux"),
766    allow(dead_code, reason = "only Linux's image surface (Wayland) reads it")
767)]
768pub(crate) struct ImagePaint {
769    pub ctx: Context,
770    pub surfaces: ImageSurfaces,
771    /// The window it is drawn in (whose image surface takes it).
772    pub viewport: ViewportId,
773    pub route: Route,
774    /// The viewport's key (its tile slot).
775    pub key: u64,
776    pub pass: u64,
777    /// The visible image rectangle, in window pixels.
778    pub rect_px: [f32; 4],
779    /// Physical pixels per logical pixel of the window's surface.
780    pub scale: f32,
781    pub background: [f64; 4],
782    /// Each side's tiles and its clip, in window pixels.
783    pub sides: Vec<(TilePaint, [f32; 4])>,
784    /// The image surface shows this frame's image (else no hole).
785    pub shown: AtomicBool,
786}
787
788impl egui_wgpu::CallbackTrait for ImagePaint {
789    fn prepare(
790        &self,
791        device: &wgpu::Device,
792        queue: &wgpu::Queue,
793        _screen: &egui_wgpu::ScreenDescriptor,
794        _encoder: &mut wgpu::CommandEncoder,
795        resources: &mut egui_wgpu::CallbackResources,
796    ) -> Vec<wgpu::CommandBuffer> {
797        let Some(r) = resources.get_mut::<Resources>() else {
798            return Vec::new();
799        };
800        for (side, _) in &self.sides {
801            side.sync_textures(device, queue, r);
802        }
803        #[cfg(target_os = "linux")]
804        {
805            let mut s = self.surfaces.lock();
806            let Some(w) = s.windows.get_mut(&self.viewport) else {
807                return Vec::new();
808            };
809            let result = match w.manager.as_mut() {
810                Some(m) => m.render(self, device, queue, r),
811                None => Ok(false),
812            };
813            match result {
814                Ok(shown) => self.shown.store(shown, Ordering::Relaxed),
815                Err(e) => {
816                    w.failure = Some(e);
817                    self.ctx.request_repaint_of(self.viewport);
818                }
819            }
820        }
821        Vec::new()
822    }
823
824    fn paint(
825        &self,
826        info: egui::PaintCallbackInfo,
827        pass: &mut wgpu::RenderPass<'static>,
828        resources: &egui_wgpu::CallbackResources,
829    ) {
830        if !self.shown.load(Ordering::Relaxed) {
831            return;
832        }
833        if let Some(r) = resources.get::<Resources>() {
834            r.draw_hole(pass, info.screen_size_px);
835        }
836    }
837}
838
839/// One window's image surface, for the debug bridge.
840fn report_window(viewport: ViewportId, w: &WindowSurface) -> Json {
841    let colour = w.offer.colour.as_ref().map(|c| {
842        let [features, primaries, transfers, intents] = c.names();
843        json!({
844            "version": c.version,
845            "features": features,
846            "primaries": primaries,
847            "transfers": transfers,
848            "intents": intents,
849            "wsi_claims_srgb_surfaces": c.wsi_claims_srgb_surfaces(),
850        })
851    });
852    let negotiated = w.negotiated.as_ref().map(|(wanted, n)| {
853        json!({
854            "wanted": wanted.describe(),
855            "route": n.route.name(),
856            "target": n.route.target().map(|t| format!("{} ({:?})", t.describe(), t.surface_format)),
857            "why": n.why,
858        })
859    });
860    #[cfg(target_os = "linux")]
861    let manager = w.manager.as_ref().map(wl::Manager::report);
862    #[cfg(not(target_os = "linux"))]
863    let manager: Option<Json> = None;
864    json!({
865        "window": format!("{viewport:?}"),
866        "unavailable": w.offer.unavailable,
867        "colour_management": colour,
868        "wsi": w.offer.wsi.iter().map(|(f, c)| format!("{f:?} {c:?}")).collect::<Vec<_>>(),
869        "may_tag": w.offer.may_tag,
870        "negotiated": negotiated,
871        "failure": w.failure,
872        "surfaces": manager,
873    })
874}
875
876/// What the image surfaces of `ctx` are doing, for the debug bridge: the
877/// main window's at the top level (as before), every window's in
878/// `windows`.
879pub fn report(ctx: &Context) -> Json {
880    let Some(surfaces) = SURFACES.get(ctx) else {
881        return json!({ "installed": false });
882    };
883    let order = windows(ctx);
884    let s = surfaces.lock();
885    let mut out = s
886        .windows
887        .get(&ViewportId::ROOT)
888        .map(|w| report_window(ViewportId::ROOT, w))
889        .unwrap_or_else(|| json!({}));
890    out["installed"] = json!(s.windows.contains_key(&ViewportId::ROOT));
891    out["windows"] = Json::Array(
892        order
893            .iter()
894            .filter_map(|v| s.windows.get(v).map(|w| report_window(*v, w)))
895            .collect(),
896    );
897    out["window_source"] = json!(s.source.is_some());
898    out
899}
900
901#[cfg(target_os = "linux")]
902mod wl {
903    //! The Wayland image surfaces of one window: one subsurface and wgpu
904    //! surface per viewport drawn in it, under that window's surface.
905
906    use std::collections::HashMap;
907
908    use egui_pop_wayland::{Description, Display, Subsurface};
909    use egui_wgpu::wgpu;
910    use serde_json::{Value as Json, json};
911
912    use super::{ImagePaint, Route, layout, named_primaries, named_transfer, raw_window_handle};
913    use crate::display::{ColorSpace, SurfaceFormat};
914    use crate::gpu::{self, Resources};
915
916    struct Image {
917        // Dropped first: the swapchain goes before its surface.
918        surface: wgpu::Surface<'static>,
919        sub: Subsurface,
920        config: Option<wgpu::SurfaceConfiguration>,
921        route: Route,
922        used: u64,
923        presented: bool,
924    }
925
926    pub(super) struct Manager {
927        // Dropped first: the image surfaces go before the connection.
928        images: HashMap<u64, Image>,
929        display: Display,
930        instance: wgpu::Instance,
931        formats: Vec<(wgpu::TextureFormat, SurfaceFormat, ColorSpace)>,
932        present_mode: wgpu::PresentMode,
933        alpha_mode: wgpu::CompositeAlphaMode,
934        max_side: u32,
935    }
936
937    impl Manager {
938        /// Joins the compositor and probes a subsurface's capabilities.
939        pub(super) fn new(
940            rs: &egui_wgpu::RenderState,
941            window: &(impl raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle),
942        ) -> Result<(Manager, super::Offer), String> {
943            let mut display = Display::attach(window).map_err(|e| e.to_string())?;
944            if !display.has_subcompositor() {
945                return Err("the compositor offers no subsurfaces".into());
946            }
947            if !display.has_viewporter() {
948                return Err("the compositor has no wp_viewporter to size a subsurface".into());
949            }
950            let sub = display.subsurface()?;
951            let surface = rs
952                .instance
953                .create_surface(sub.handle())
954                .map_err(|e| format!("no wgpu surface on a subsurface: {e}"))?;
955            if !rs.adapter.is_surface_supported(&surface) {
956                return Err("the GPU cannot present to a subsurface".into());
957            }
958            let caps = surface.get_capabilities(&rs.adapter);
959            drop(surface);
960            drop(sub);
961            let mut formats = Vec::new();
962            for &format in &caps.formats {
963                let sf = gpu::surface_format(format);
964                if matches!(sf, SurfaceFormat::Other | SurfaceFormat::Rgba8UnormSrgb) {
965                    continue;
966                }
967                let spaces = caps.color_spaces(format);
968                for space in ColorSpace::ALL {
969                    if spaces.contains(gpu::color_space_flag(space))
970                        && !formats.iter().any(|(_, f, c)| *f == sf && *c == space)
971                    {
972                        formats.push((format, sf, space));
973                    }
974                }
975            }
976            let present_mode = [wgpu::PresentMode::Mailbox, wgpu::PresentMode::Immediate]
977                .into_iter()
978                .find(|m| caps.present_modes.contains(m))
979                .unwrap_or(wgpu::PresentMode::Fifo);
980            let alpha_mode = if caps.alpha_modes.contains(&wgpu::CompositeAlphaMode::Opaque) {
981                wgpu::CompositeAlphaMode::Opaque
982            } else {
983                wgpu::CompositeAlphaMode::Auto
984            };
985            let offer = super::Offer {
986                unavailable: None,
987                colour: display.capabilities().cloned(),
988                wsi: formats.iter().map(|(_, f, c)| (*f, *c)).collect(),
989                may_tag: true,
990            };
991            Ok((
992                Manager {
993                    images: HashMap::new(),
994                    display,
995                    instance: rs.instance.clone(),
996                    formats,
997                    present_mode,
998                    alpha_mode,
999                    max_side: rs.device.limits().max_texture_dimension_2d,
1000                },
1001                offer,
1002            ))
1003        }
1004
1005        pub(super) fn poll(&mut self) -> Result<(), String> {
1006            self.display.poll()
1007        }
1008
1009        /// Drops every image surface (the image went back to the window).
1010        pub(super) fn clear(&mut self) {
1011            self.images.clear();
1012        }
1013
1014        /// Drops the image surfaces of viewports no longer drawn.
1015        pub(super) fn collect(&mut self, pass: u64) {
1016            self.images.retain(|_, i| i.used + 2 >= pass);
1017        }
1018
1019        /// Renders a viewport's image into its surface and presents it;
1020        /// whether the surface shows an image.
1021        pub(super) fn render(
1022            &mut self,
1023            p: &ImagePaint,
1024            device: &wgpu::Device,
1025            queue: &wgpu::Queue,
1026            r: &mut Resources,
1027        ) -> Result<bool, String> {
1028            let Some(target) = p.route.target() else {
1029                return Ok(false);
1030            };
1031            let Some(place) = layout(p.rect_px, p.scale) else {
1032                return Ok(false);
1033            };
1034            if place.buffer.iter().any(|s| *s > self.max_side) {
1035                return Err(format!(
1036                    "the image ({}x{} pixels) is larger than the GPU's surfaces",
1037                    place.buffer[0], place.buffer[1]
1038                ));
1039            }
1040            let space = match p.route {
1041                Route::Wsi(t) => t.color_space().ok_or("no colour space for the target")?,
1042                _ => ColorSpace::Srgb,
1043            };
1044            let format = self
1045                .formats
1046                .iter()
1047                .find(|(_, f, c)| *f == target.surface_format && *c == space)
1048                .map(|(w, _, _)| *w)
1049                .ok_or("the image surface's format is not offered")?;
1050            if self.images.get(&p.key).is_some_and(|i| i.route != p.route) {
1051                self.images.remove(&p.key);
1052            }
1053            if !self.images.contains_key(&p.key) {
1054                let mut sub = self.display.subsurface()?;
1055                if let Route::Tagged(t) = p.route {
1056                    let (Some(np), Some(nt)) =
1057                        (named_primaries(t.primaries), named_transfer(t.transfer))
1058                    else {
1059                        return Err("the target has no protocol name".into());
1060                    };
1061                    sub.tag(&mut self.display, np, nt)?;
1062                }
1063                let surface = self
1064                    .instance
1065                    .create_surface(sub.handle())
1066                    .map_err(|e| format!("no wgpu surface on the subsurface: {e}"))?;
1067                self.images.insert(
1068                    p.key,
1069                    Image {
1070                        surface,
1071                        sub,
1072                        config: None,
1073                        route: p.route,
1074                        used: p.pass,
1075                        presented: false,
1076                    },
1077                );
1078            }
1079            let Some(image) = self.images.get_mut(&p.key) else {
1080                return Ok(false);
1081            };
1082            image.used = p.pass;
1083            image.sub.place(place.logical);
1084            let config = wgpu::SurfaceConfiguration {
1085                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1086                format,
1087                color_space: gpu::to_wgpu(space),
1088                width: place.buffer[0],
1089                height: place.buffer[1],
1090                present_mode: self.present_mode,
1091                desired_maximum_frame_latency: 2,
1092                alpha_mode: self.alpha_mode,
1093                view_formats: Vec::new(),
1094            };
1095            if image.config.as_ref() != Some(&config) {
1096                image.surface.configure(device, &config);
1097                image.config = Some(config);
1098            }
1099            let frame = match image.surface.get_current_texture() {
1100                wgpu::CurrentSurfaceTexture::Success(t)
1101                | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,
1102                // The last image stays.
1103                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
1104                    return Ok(image.presented);
1105                }
1106                wgpu::CurrentSurfaceTexture::Outdated
1107                | wgpu::CurrentSurfaceTexture::Lost
1108                | wgpu::CurrentSurfaceTexture::Validation => {
1109                    image.config = None;
1110                    return Ok(false);
1111                }
1112            };
1113            let [bw, bh] = place.buffer;
1114            let size = [bw as f32, bh as f32];
1115            r.ensure_image_pipelines(device, format);
1116            let mut drawn = Vec::new();
1117            for (side, clip) in &p.sides {
1118                if side.write_uniforms(device, queue, r, size, place.origin, false) {
1119                    drawn.push((side, *clip));
1120                }
1121            }
1122            let view = frame
1123                .texture
1124                .create_view(&wgpu::TextureViewDescriptor::default());
1125            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1126                label: Some("egui-pop-viewport.image"),
1127            });
1128            {
1129                let [cr, cg, cb, ca] = p.background;
1130                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1131                    label: Some("egui-pop-viewport.image"),
1132                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1133                        view: &view,
1134                        resolve_target: None,
1135                        ops: wgpu::Operations {
1136                            load: wgpu::LoadOp::Clear(wgpu::Color {
1137                                r: cr,
1138                                g: cg,
1139                                b: cb,
1140                                a: ca,
1141                            }),
1142                            store: wgpu::StoreOp::Store,
1143                        },
1144                        depth_slice: None,
1145                    })],
1146                    ..Default::default()
1147                });
1148                pass.set_viewport(0.0, 0.0, size[0], size[1], 0.0, 1.0);
1149                for (side, clip) in drawn {
1150                    let x0 = (clip[0] - place.origin[0]).floor().clamp(0.0, size[0]) as u32;
1151                    let y0 = (clip[1] - place.origin[1]).floor().clamp(0.0, size[1]) as u32;
1152                    let x1 = (clip[2] - place.origin[0]).ceil().clamp(0.0, size[0]) as u32;
1153                    let y1 = (clip[3] - place.origin[1]).ceil().clamp(0.0, size[1]) as u32;
1154                    if x1 <= x0 || y1 <= y0 {
1155                        continue;
1156                    }
1157                    pass.set_scissor_rect(x0, y0, x1 - x0, y1 - y0);
1158                    side.draw(&mut pass, r, &r.image_pipelines[&format]);
1159                }
1160            }
1161            queue.submit([encoder.finish()]);
1162            // The position, size and tag go with the present's commit.
1163            self.display.flush()?;
1164            queue.present(frame);
1165            image.presented = true;
1166            Ok(true)
1167        }
1168
1169        pub(super) fn report(&self) -> Json {
1170            json!({
1171                "present_mode": format!("{:?}", self.present_mode),
1172                "images": self.images.values().map(|i| json!({
1173                    "route": i.route.name(),
1174                    "placed": i.sub.placed(),
1175                    "tagged": i.sub.tagged().map(|(p, t)| format!("{} {}", p.name(), t.name())),
1176                    "config": i.config.as_ref().map(|c| format!("{:?} {:?} {}x{}", c.format, c.color_space, c.width, c.height)),
1177                })).collect::<Vec<_>>(),
1178                "preferred": self.display.preferred().map(description),
1179                "preferred_error": self.display.preferred_error(),
1180            })
1181        }
1182    }
1183
1184    /// A description as JSON.
1185    fn description(d: &Description) -> Json {
1186        json!({
1187            "primaries_named": d.primaries_named.map(|p| p.name()),
1188            "primaries": d.primaries,
1189            "transfer": d.transfer.map(|t| t.name()),
1190            "tf_power": d.tf_power,
1191            "luminances": d.luminances.map(|l| json!({ "min": l.min, "max": l.max, "reference": l.reference })),
1192            "target_primaries": d.target_primaries,
1193            "target_luminance": d.target_luminance,
1194            "target_max_cll": d.target_max_cll,
1195            "target_max_fall": d.target_max_fall,
1196            "headroom": d.headroom(),
1197            "icc": d.icc,
1198        })
1199    }
1200}
1201
1202#[cfg(test)]
1203mod tests {
1204    use super::*;
1205    use egui_pop_wayland::{Feature, NamedPrimaries as P, NamedTransfer as T};
1206
1207    fn caps(primaries: &[P], transfers: &[T], features: &[Feature]) -> Capabilities {
1208        Capabilities {
1209            version: 1,
1210            features: features.to_vec(),
1211            primaries: primaries.to_vec(),
1212            transfers: transfers.to_vec(),
1213            intents: vec![0],
1214        }
1215    }
1216
1217    /// A Mesa driver's offer for a subsurface on a compositor announcing
1218    /// these names (its colour spaces, on 8 and 10 bits and half floats).
1219    fn offer(c: Capabilities, wsi: &[ColorSpace]) -> Offer {
1220        let mut pairs = Vec::new();
1221        for f in [
1222            SurfaceFormat::Rgba8Unorm,
1223            SurfaceFormat::Rgb10a2Unorm,
1224            SurfaceFormat::Rgba16Float,
1225        ] {
1226            pairs.push((f, ColorSpace::Srgb));
1227            for &s in wsi {
1228                pairs.push((f, s));
1229            }
1230        }
1231        Offer {
1232            unavailable: None,
1233            colour: Some(c),
1234            wsi: pairs,
1235            may_tag: true,
1236        }
1237    }
1238
1239    fn kwin() -> Offer {
1240        offer(
1241            caps(
1242                &[P::Srgb, P::Bt2020, P::DisplayP3],
1243                &[T::Gamma22, T::St2084Pq, T::ExtLinear, T::Hlg],
1244                &[Feature::Parametric, Feature::ExtendedTargetVolume],
1245            ),
1246            &[
1247                ColorSpace::ExtendedSrgbLinear,
1248                ColorSpace::Bt2100Pq,
1249                ColorSpace::Bt2100Hlg,
1250            ],
1251        )
1252    }
1253
1254    fn gnome() -> Offer {
1255        offer(
1256            caps(
1257                &[P::Srgb, P::Bt2020, P::DisplayP3],
1258                &[T::Gamma22, T::St2084Pq, T::ExtLinear, T::Srgb],
1259                &[Feature::Parametric],
1260            ),
1261            &[ColorSpace::DisplayP3, ColorSpace::Bt2100Pq],
1262        )
1263    }
1264
1265    fn rec2020() -> DisplayTarget {
1266        DisplayTarget {
1267            primaries: Primaries::Bt2020,
1268            transfer: Transfer::Gamma22,
1269            ..DisplayTarget::srgb()
1270        }
1271    }
1272
1273    #[test]
1274    fn srgb_stays_on_the_window() {
1275        let n = negotiate(&DisplayTarget::srgb(), &kwin());
1276        assert_eq!(n.route, Route::Window);
1277        assert_eq!(n.why, None);
1278    }
1279
1280    #[test]
1281    fn rec2020_is_tagged_where_the_driver_leaves_the_surface_alone() {
1282        let n = negotiate(&rec2020(), &kwin());
1283        let Route::Tagged(t) = n.route else {
1284            panic!("{n:?}");
1285        };
1286        assert_eq!(
1287            (t.primaries, t.transfer),
1288            (Primaries::Bt2020, Transfer::Gamma22)
1289        );
1290        assert_eq!(t.surface_format, SurfaceFormat::Rgb10a2Unorm);
1291        assert_eq!(t.source, TargetSource::Tagged);
1292        assert!(t.is_supported());
1293        assert!(display::resolve(&rec2020(), &t, true).faithful());
1294        assert_eq!(n.why, None);
1295    }
1296
1297    #[test]
1298    fn display_p3_is_tagged_with_a_power_where_the_srgb_curve_is_not_announced() {
1299        let n = negotiate(&DisplayTarget::display_p3(), &kwin());
1300        let Route::Tagged(t) = n.route else {
1301            panic!("{n:?}");
1302        };
1303        assert_eq!(
1304            (t.primaries, t.transfer),
1305            (Primaries::DisplayP3, Transfer::Gamma22)
1306        );
1307    }
1308
1309    #[test]
1310    fn hdr_is_tagged_on_ten_bits() {
1311        let n = negotiate(&DisplayTarget::hdr_pq(4.0), &kwin());
1312        let Route::Tagged(t) = n.route else {
1313            panic!("{n:?}");
1314        };
1315        assert_eq!(t.transfer, Transfer::Pq);
1316        assert_eq!(t.surface_format, SurfaceFormat::Rgb10a2Unorm);
1317        assert_eq!(t.headroom, 4.0);
1318    }
1319
1320    #[test]
1321    fn the_driver_declares_where_it_holds_the_surface() {
1322        // GNOME announces sRGB with the sRGB transfer: Mesa holds the
1323        // colour of every surface it presents to; Display P3 through it.
1324        let n = negotiate(&rec2020(), &gnome());
1325        let Route::Wsi(t) = n.route else {
1326            panic!("{n:?}");
1327        };
1328        assert_eq!(t.color_space(), Some(ColorSpace::DisplayP3));
1329        assert_eq!(t.source, TargetSource::Wsi);
1330        let why = n.why.unwrap();
1331        assert!(why.contains("Mesa"), "{why}");
1332        // What is lost is said by the resolution.
1333        let r = display::resolve(&rec2020(), &t, true);
1334        assert!(r.reason().unwrap().contains("BT.2020"), "{r:?}");
1335    }
1336
1337    #[test]
1338    fn tagging_can_be_turned_off() {
1339        let mut o = kwin();
1340        o.may_tag = false;
1341        let n = negotiate(&rec2020(), &o);
1342        let Route::Wsi(t) = n.route else {
1343            panic!("{n:?}");
1344        };
1345        // scRGB carries BT.2020 (negatives) and is SDR-compatible.
1346        assert_eq!(t.color_space(), Some(ColorSpace::ExtendedSrgbLinear));
1347        assert_eq!(n.why, None);
1348    }
1349
1350    #[test]
1351    fn without_colour_management_the_image_stays_srgb_and_says_why() {
1352        let mut o = offer(Capabilities::default(), &[]);
1353        o.colour = None;
1354        let n = negotiate(&rec2020(), &o);
1355        assert_eq!(n.route, Route::Window);
1356        let why = n.why.unwrap();
1357        assert!(why.contains("no colour management"), "{why}");
1358        assert!(why.contains("no colour space wider than sRGB"), "{why}");
1359        // Not Wayland, an opaque window: the reason as given.
1360        let n = negotiate(&rec2020(), &Offer::unavailable("not a Wayland window"));
1361        assert_eq!(n.route, Route::Window);
1362        assert_eq!(n.why.as_deref(), Some("not a Wayland window"));
1363    }
1364
1365    #[test]
1366    fn a_compositor_without_the_encoding_falls_to_the_driver_then_the_window() {
1367        // Parametric, but only sRGB primaries.
1368        let narrow = offer(caps(&[P::Srgb], &[T::Gamma22], &[Feature::Parametric]), &[]);
1369        let n = negotiate(&rec2020(), &narrow);
1370        assert_eq!(n.route, Route::Window);
1371        let why = n.why.unwrap();
1372        assert!(why.contains("announces the primaries srgb"), "{why}");
1373        // No parametric feature (ICC only).
1374        let icc = offer(caps(&[P::Bt2020], &[T::Gamma22], &[]), &[]);
1375        let why = negotiate(&rec2020(), &icc).why.unwrap();
1376        assert!(why.contains("parametric"), "{why}");
1377    }
1378
1379    #[test]
1380    fn custom_primaries_are_tagged_bt2020() {
1381        let custom = DisplayTarget {
1382            primaries: Primaries::Custom {
1383                r: [0.69, 0.30],
1384                g: [0.20, 0.72],
1385                b: [0.15, 0.05],
1386                w: display::D65,
1387            },
1388            ..rec2020()
1389        };
1390        let Route::Tagged(t) = negotiate(&custom, &kwin()).route else {
1391            panic!()
1392        };
1393        assert_eq!(t.primaries, Primaries::Bt2020);
1394    }
1395
1396    #[test]
1397    fn the_layout_covers_the_rectangle_in_whole_logical_pixels() {
1398        // Scale 1.25: 400 by 300 window pixels are 320 by 240 logical.
1399        let l = layout([10.0, 20.0, 410.0, 320.0], 1.25).unwrap();
1400        assert_eq!(l.logical, [8, 16, 320, 240]);
1401        assert_eq!(l.buffer, [400, 300]);
1402        assert_eq!(l.origin, [10.0, 20.0]);
1403        // Off the grid: the surface covers it, and starts before.
1404        let l = layout([11.0, 21.0, 100.5, 50.0], 2.0).unwrap();
1405        assert_eq!(l.logical, [5, 10, 46, 15]);
1406        assert_eq!(l.buffer, [92, 30]);
1407        assert_eq!(l.origin, [10.0, 20.0]);
1408        assert_eq!(layout([5.0, 5.0, 5.0, 9.0], 1.0), None);
1409    }
1410
1411    #[test]
1412    fn the_background_is_encoded_for_the_target() {
1413        let grey = Color32::from_gray(128);
1414        let srgb = clear_colour(grey, &DisplayTarget::srgb());
1415        assert!((srgb[0] - 128.0 / 255.0).abs() < 2e-3, "{srgb:?}");
1416        // Grey stays grey in BT.2020; a 2.2 power is darker than the
1417        // sRGB curve's toe but close at mid grey.
1418        let t = rec2020().with_source(TargetSource::Tagged);
1419        let c = clear_colour(grey, &t);
1420        assert!(
1421            (c[0] - c[1]).abs() < 1e-4 && (c[1] - c[2]).abs() < 1e-4,
1422            "{c:?}"
1423        );
1424        assert!((c[0] - srgb[0]).abs() < 0.02, "{c:?}");
1425        assert_eq!(c[3], 1.0);
1426    }
1427
1428    /// One pass of `ctx` with `raw`, its output dropped.
1429    fn pass(ctx: &Context, raw: egui::RawInput) {
1430        ctx.run_ui(raw, |_| {}).textures_delta.clear();
1431    }
1432
1433    /// A context whose egui knows the main window and `others`.
1434    fn context_with(others: &[ViewportId]) -> Context {
1435        let ctx = Context::default();
1436        let mut raw = egui::RawInput::default();
1437        raw.viewports
1438            .insert(ViewportId::ROOT, egui::ViewportInfo::default());
1439        for v in others {
1440            raw.viewports.insert(*v, egui::ViewportInfo::default());
1441        }
1442        pass(&ctx, raw);
1443        ctx
1444    }
1445
1446    #[test]
1447    fn each_window_gets_its_own_surface_negotiated_for_what_it_wants() {
1448        let wide = ViewportId::from_hash_of("wide viewer");
1449        let plain = ViewportId::from_hash_of("plain viewer");
1450        let ctx = context_with(&[wide, plain]);
1451        // The main window on GNOME's offer, the two viewers on KWin's.
1452        install_offer(&ctx, ViewportId::ROOT, gnome());
1453        install_offer(&ctx, wide, kwin());
1454        install_offer(&ctx, plain, kwin());
1455        display::want(&ctx, wide, rec2020());
1456        display::want(&ctx, plain, DisplayTarget::srgb());
1457        display::want(&ctx, ViewportId::ROOT, rec2020());
1458
1459        let n = negotiate_window(&ctx, wide);
1460        let Route::Tagged(t) = n.route else {
1461            panic!("{n:?}")
1462        };
1463        assert_eq!(t.surface_format, SurfaceFormat::Rgb10a2Unorm);
1464        assert_eq!(negotiate_window(&ctx, plain).route, Route::Window);
1465        let Route::Wsi(main) = negotiate_window(&ctx, ViewportId::ROOT).route else {
1466            panic!()
1467        };
1468        assert_eq!(main.color_space(), Some(ColorSpace::DisplayP3));
1469
1470        // Each window's image surface, apart.
1471        let of = |v| display::image_surface_of(&ctx, v).and_then(|i| i.target);
1472        assert_eq!(of(wide), Some(t));
1473        assert_eq!(of(plain), None);
1474        assert_eq!(of(ViewportId::ROOT), Some(main));
1475        assert_eq!(display::target_of(&ctx, wide), t);
1476        // What windows.list shows of each.
1477        let state = egui_pop_core::window_surface::get(&ctx, wide).unwrap();
1478        assert_eq!(state["route"], "tagged");
1479        assert_eq!(state["format"], "Rgb10a2Unorm");
1480        assert!(
1481            state["colour_space"].as_str().unwrap().contains("2020"),
1482            "{state}"
1483        );
1484        let state = egui_pop_core::window_surface::get(&ctx, plain).unwrap();
1485        assert_eq!(state["route"], "window");
1486        assert_eq!(state["format"], Json::Null);
1487        let r = report(&ctx);
1488        assert_eq!(r["windows"].as_array().unwrap().len(), 3, "{r}");
1489        assert_eq!(r["windows"][0]["window"], format!("{:?}", ViewportId::ROOT));
1490    }
1491
1492    #[test]
1493    fn closing_a_window_frees_its_surface() {
1494        let viewer = ViewportId::from_hash_of("viewer");
1495        let ctx = context_with(&[viewer]);
1496        install_offer(&ctx, ViewportId::ROOT, kwin());
1497        install_offer(&ctx, viewer, kwin());
1498        display::want(&ctx, viewer, rec2020());
1499        display::want(&ctx, ViewportId::ROOT, rec2020());
1500        assert!(matches!(
1501            negotiate_window(&ctx, viewer).route,
1502            Route::Tagged(_)
1503        ));
1504        close_window(&ctx, viewer);
1505        assert_eq!(offer_of(&ctx, viewer), None);
1506        assert_eq!(windows(&ctx), vec![ViewportId::ROOT]);
1507        assert_eq!(egui_pop_core::window_surface::get(&ctx, viewer), None);
1508        assert_eq!(
1509            display::image_surface_of(&ctx, viewer).and_then(|i| i.target),
1510            None
1511        );
1512
1513        // A window egui no longer knows is freed at the next frame.
1514        install_offer(&ctx, viewer, kwin());
1515        let _ = negotiate_window(&ctx, viewer);
1516        let mut raw = egui::RawInput::default();
1517        raw.viewports
1518            .insert(ViewportId::ROOT, egui::ViewportInfo::default());
1519        pass(&ctx, raw);
1520        let _ = negotiate_window(&ctx, ViewportId::ROOT);
1521        assert_eq!(windows(&ctx), vec![ViewportId::ROOT]);
1522        assert_eq!(egui_pop_core::window_surface::get(&ctx, viewer), None);
1523        // The main window's stays.
1524        assert!(matches!(
1525            negotiate_window(&ctx, ViewportId::ROOT).route,
1526            Route::Tagged(_)
1527        ));
1528    }
1529
1530    #[test]
1531    fn a_window_without_a_surface_says_why() {
1532        let viewer = ViewportId::from_hash_of("viewer");
1533        let ctx = context_with(&[viewer]);
1534        install_offer(&ctx, ViewportId::ROOT, kwin());
1535        display::want(&ctx, viewer, rec2020());
1536        let n = negotiate_window(&ctx, viewer);
1537        assert_eq!(n.route, Route::Window);
1538        assert!(n.why.unwrap().contains("install_window"));
1539        // Told where handles are, but none yet for this window.
1540        set_window_source(&ctx, Options::default(), |_| None::<NoHandles>);
1541        let why = negotiate_window(&ctx, viewer).why.unwrap();
1542        assert!(why.contains("not known yet"), "{why}");
1543        // Handles refused: the window's offer says why, kept.
1544        set_window_source(&ctx, Options::default(), |_| Some(NoHandles));
1545        // No render state: install never ran with a GPU.
1546        assert_eq!(offer_of(&ctx, viewer), None);
1547    }
1548
1549    #[test]
1550    fn a_window_built_opaque_says_why_its_builder_gave() {
1551        use egui_pop_core::window_surface::{Transparency, set_transparency};
1552        let viewer = ViewportId::from_hash_of("viewer");
1553        let ctx = context_with(&[viewer]);
1554        install_offer(&ctx, ViewportId::ROOT, kwin());
1555        display::want(&ctx, viewer, rec2020());
1556        set_window_source(&ctx, Options::default(), |_| Some(NoHandles));
1557        set_transparency(
1558            &ctx,
1559            viewer,
1560            Some(Transparency::Opaque("X11: no subsurface".into())),
1561        );
1562        let n = negotiate_window(&ctx, viewer);
1563        assert_eq!(n.route, Route::Window);
1564        let why = n.why.unwrap();
1565        assert!(why.contains("opaque") && why.contains("X11"), "{why}");
1566        assert_eq!(offer_of(&ctx, viewer), None);
1567        // Transparent, handles known, but no GPU installed: said so, not
1568        // "handles not known".
1569        set_transparency(&ctx, viewer, Some(Transparency::Transparent));
1570        let why = negotiate_window(&ctx, viewer).why.unwrap();
1571        assert!(why.contains("not installed"), "{why}");
1572    }
1573
1574    struct NoHandles;
1575
1576    impl raw_window_handle::HasWindowHandle for NoHandles {
1577        fn window_handle(
1578            &self,
1579        ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
1580            Err(raw_window_handle::HandleError::Unavailable)
1581        }
1582    }
1583
1584    impl raw_window_handle::HasDisplayHandle for NoHandles {
1585        fn display_handle(
1586            &self,
1587        ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
1588            Err(raw_window_handle::HandleError::Unavailable)
1589        }
1590    }
1591}