Skip to main content

egui_pop_wayland/
client.rs

1//! The protocol side: the globals, the colour manager's announcements,
2//! the preferred description, and the image subsurfaces.
3
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::Arc;
7
8use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle};
9use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init};
10use wayland_client::protocol::wl_compositor::WlCompositor;
11use wayland_client::protocol::wl_region::WlRegion;
12use wayland_client::protocol::wl_registry::WlRegistry;
13use wayland_client::protocol::wl_subcompositor::WlSubcompositor;
14use wayland_client::protocol::wl_subsurface::WlSubsurface;
15use wayland_client::protocol::wl_surface::WlSurface;
16use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, delegate_noop};
17use wayland_protocols::wp::color_management::v1::client::{
18    wp_color_management_surface_feedback_v1::{self, WpColorManagementSurfaceFeedbackV1},
19    wp_color_management_surface_v1::WpColorManagementSurfaceV1,
20    wp_color_manager_v1::{self, WpColorManagerV1},
21    wp_image_description_creator_params_v1::WpImageDescriptionCreatorParamsV1,
22    wp_image_description_info_v1::{self, WpImageDescriptionInfoV1},
23    wp_image_description_v1::{self, WpImageDescriptionV1},
24};
25use wayland_protocols::wp::viewporter::client::{
26    wp_viewport::WpViewport, wp_viewporter::WpViewporter,
27};
28
29use crate::sys::{self, Keep, SurfaceHandle};
30use crate::{
31    Capabilities, Description, Feature, Luminances, NamedPrimaries, NamedTransfer, Unavailable,
32    chromaticities,
33};
34
35/// Roundtrips allowed while waiting for the compositor (a description
36/// ready, the preferred one's information).
37const ROUNDTRIPS: usize = 8;
38
39/// What an image description created here is for.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41enum Purpose {
42    /// A tag for image surfaces.
43    Tag,
44    /// The compositor's preferred description for the window.
45    Preferred,
46}
47
48/// An image description's state.
49#[derive(Clone, Debug, PartialEq, Eq)]
50enum Status {
51    Ready,
52    Failed(String),
53}
54
55#[derive(Default)]
56struct State {
57    caps: Capabilities,
58    status: HashMap<ObjectKey, Status>,
59    /// The preferred description being read, and the information so far.
60    reading: Option<(WpImageDescriptionV1, Description)>,
61    preferred: Option<Description>,
62    /// Bumped each time `preferred` changes.
63    revision: u64,
64    /// The compositor said the preferred description changed.
65    changed: bool,
66    preferred_error: Option<String>,
67}
68
69type ObjectKey = wayland_client::backend::ObjectId;
70
71impl Dispatch<WlRegistry, GlobalListContents> for State {
72    fn event(
73        _: &mut Self,
74        _: &WlRegistry,
75        _: <WlRegistry as Proxy>::Event,
76        _: &GlobalListContents,
77        _: &Connection,
78        _: &QueueHandle<Self>,
79    ) {
80    }
81}
82
83delegate_noop!(State: WlCompositor);
84delegate_noop!(State: WlSubcompositor);
85delegate_noop!(State: WlSubsurface);
86delegate_noop!(State: WlRegion);
87delegate_noop!(State: ignore WlSurface);
88delegate_noop!(State: WpViewporter);
89delegate_noop!(State: WpViewport);
90delegate_noop!(State: WpColorManagementSurfaceV1);
91delegate_noop!(State: WpImageDescriptionCreatorParamsV1);
92
93impl Dispatch<WpColorManagerV1, ()> for State {
94    fn event(
95        state: &mut Self,
96        _: &WpColorManagerV1,
97        event: wp_color_manager_v1::Event,
98        (): &(),
99        _: &Connection,
100        _: &QueueHandle<Self>,
101    ) {
102        let caps = &mut state.caps;
103        match event {
104            wp_color_manager_v1::Event::SupportedIntent { render_intent } => {
105                caps.intents.push(u32::from(render_intent));
106            }
107            wp_color_manager_v1::Event::SupportedFeature { feature } => {
108                caps.features.push(Feature::from_code(u32::from(feature)));
109            }
110            wp_color_manager_v1::Event::SupportedTfNamed { tf } => {
111                caps.transfers.push(NamedTransfer::from_code(u32::from(tf)));
112            }
113            wp_color_manager_v1::Event::SupportedPrimariesNamed { primaries } => {
114                caps.primaries
115                    .push(NamedPrimaries::from_code(u32::from(primaries)));
116            }
117            _ => {}
118        }
119    }
120}
121
122impl Dispatch<WpColorManagementSurfaceFeedbackV1, ()> for State {
123    fn event(
124        state: &mut Self,
125        _: &WpColorManagementSurfaceFeedbackV1,
126        event: wp_color_management_surface_feedback_v1::Event,
127        (): &(),
128        _: &Connection,
129        _: &QueueHandle<Self>,
130    ) {
131        if let wp_color_management_surface_feedback_v1::Event::PreferredChanged { .. } = event {
132            state.changed = true;
133        }
134    }
135}
136
137impl Dispatch<WpImageDescriptionV1, Purpose> for State {
138    fn event(
139        state: &mut Self,
140        description: &WpImageDescriptionV1,
141        event: wp_image_description_v1::Event,
142        purpose: &Purpose,
143        _: &Connection,
144        qh: &QueueHandle<Self>,
145    ) {
146        let status = match event {
147            wp_image_description_v1::Event::Ready { .. } => Status::Ready,
148            wp_image_description_v1::Event::Failed { cause, msg } => {
149                Status::Failed(format!("{msg} (cause {})", u32::from(cause)))
150            }
151            _ => return,
152        };
153        if *purpose == Purpose::Preferred {
154            match &status {
155                Status::Ready => {
156                    let _info = description.get_information(qh, ());
157                }
158                Status::Failed(e) => {
159                    state.preferred_error = Some(e.clone());
160                    if let Some((d, _)) = state.reading.take() {
161                        d.destroy();
162                    }
163                }
164            }
165        }
166        state.status.insert(description.id(), status);
167    }
168}
169
170impl Dispatch<WpImageDescriptionInfoV1, ()> for State {
171    fn event(
172        state: &mut Self,
173        _: &WpImageDescriptionInfoV1,
174        event: wp_image_description_info_v1::Event,
175        (): &(),
176        _: &Connection,
177        _: &QueueHandle<Self>,
178    ) {
179        use wp_image_description_info_v1::Event as E;
180        if let E::Done = event {
181            if let Some((description, info)) = state.reading.take() {
182                description.destroy();
183                state.preferred = Some(info);
184                state.preferred_error = None;
185                state.revision += 1;
186            }
187            return;
188        }
189        let Some((_, d)) = state.reading.as_mut() else {
190            return;
191        };
192        match event {
193            E::IccFile { .. } => d.icc = true,
194            E::Primaries {
195                r_x,
196                r_y,
197                g_x,
198                g_y,
199                b_x,
200                b_y,
201                w_x,
202                w_y,
203            } => d.primaries = Some(chromaticities([r_x, r_y, g_x, g_y, b_x, b_y, w_x, w_y])),
204            E::PrimariesNamed { primaries } => {
205                d.primaries_named = Some(NamedPrimaries::from_code(u32::from(primaries)));
206            }
207            E::TfPower { eexp } => d.tf_power = Some(f64::from(eexp) / 10_000.0),
208            E::TfNamed { tf } => d.transfer = Some(NamedTransfer::from_code(u32::from(tf))),
209            E::Luminances {
210                min_lum,
211                max_lum,
212                reference_lum,
213            } => {
214                d.luminances = Some(Luminances {
215                    min: f64::from(min_lum) / 10_000.0,
216                    max: f64::from(max_lum),
217                    reference: f64::from(reference_lum),
218                });
219            }
220            E::TargetPrimaries {
221                r_x,
222                r_y,
223                g_x,
224                g_y,
225                b_x,
226                b_y,
227                w_x,
228                w_y,
229            } => {
230                d.target_primaries = Some(chromaticities([r_x, r_y, g_x, g_y, b_x, b_y, w_x, w_y]));
231            }
232            E::TargetLuminance { min_lum, max_lum } => {
233                d.target_luminance = Some([f64::from(min_lum) / 10_000.0, f64::from(max_lum)]);
234            }
235            E::TargetMaxCll { max_cll } => d.target_max_cll = Some(max_cll),
236            E::TargetMaxFall { max_fall } => d.target_max_fall = Some(max_fall),
237            _ => {}
238        }
239    }
240}
241
242/// The compositor, as seen from a window: its globals, its colour
243/// manager's announcements, the preferred description for the window.
244pub struct Display {
245    conn: Connection,
246    queue: EventQueue<State>,
247    qh: QueueHandle<State>,
248    state: State,
249    _globals: GlobalList,
250    parent: WlSurface,
251    compositor: Option<WlCompositor>,
252    subcompositor: Option<WlSubcompositor>,
253    viewporter: Option<WpViewporter>,
254    manager: Option<WpColorManagerV1>,
255    feedback: Option<WpColorManagementSurfaceFeedbackV1>,
256    descriptions: HashMap<(u32, u32), WpImageDescriptionV1>,
257}
258
259impl fmt::Debug for Display {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        f.debug_struct("Display")
262            .field("capabilities", &self.capabilities())
263            .field("subcompositor", &self.subcompositor.is_some())
264            .field("viewporter", &self.viewporter.is_some())
265            .field("preferred", &self.state.preferred)
266            .finish_non_exhaustive()
267    }
268}
269
270impl Display {
271    /// Joins the connection of a Wayland window (eframe's creation
272    /// context or frame gives its handles), binds the compositor's
273    /// globals on a queue of its own, and reads the colour manager's
274    /// announcements and the preferred description for the window.
275    pub fn attach(
276        window: &(impl HasWindowHandle + HasDisplayHandle),
277    ) -> Result<Display, Unavailable> {
278        let display = window
279            .display_handle()
280            .map_err(|e| Unavailable::Handle(e.to_string()))?
281            .as_raw();
282        let surface = window
283            .window_handle()
284            .map_err(|e| Unavailable::Handle(e.to_string()))?
285            .as_raw();
286        let (RawDisplayHandle::Wayland(display), RawWindowHandle::Wayland(surface)) =
287            (display, surface)
288        else {
289            return Err(Unavailable::NotWayland);
290        };
291        let conn = sys::connection(display.display);
292        let parent = sys::foreign_surface(&conn, surface.surface).map_err(Unavailable::Handle)?;
293        let (globals, queue) = registry_queue_init::<State>(&conn)
294            .map_err(|e| Unavailable::Connection(e.to_string()))?;
295        let qh = queue.handle();
296        let compositor = globals.bind::<WlCompositor, _, _>(&qh, 1..=4, ()).ok();
297        let subcompositor = globals.bind::<WlSubcompositor, _, _>(&qh, 1..=1, ()).ok();
298        let viewporter = globals.bind::<WpViewporter, _, _>(&qh, 1..=1, ()).ok();
299        // Version 1: what a Vulkan driver binding version 1 sees too.
300        let manager = globals.bind::<WpColorManagerV1, _, _>(&qh, 1..=1, ()).ok();
301        let version = globals.contents().with_list(|list| {
302            list.iter()
303                .find(|g| g.interface == WpColorManagerV1::interface().name)
304                .map_or(0, |g| g.version)
305        });
306        let mut display = Display {
307            conn,
308            queue,
309            qh,
310            state: State::default(),
311            _globals: globals,
312            parent,
313            compositor,
314            subcompositor,
315            viewporter,
316            manager,
317            feedback: None,
318            descriptions: HashMap::new(),
319        };
320        display.state.caps.version = version;
321        display.roundtrip()?;
322        display.feedback = display
323            .manager
324            .as_ref()
325            .map(|m| m.get_surface_feedback(&display.parent, &display.qh, ()));
326        if display.feedback.is_some() {
327            display.request_preferred();
328            // Ready, then the information.
329            for _ in 0..ROUNDTRIPS {
330                if display.state.reading.is_none() {
331                    break;
332                }
333                display.roundtrip()?;
334            }
335        }
336        Ok(display)
337    }
338
339    fn roundtrip(&mut self) -> Result<(), Unavailable> {
340        self.queue
341            .roundtrip(&mut self.state)
342            .map(|_| ())
343            .map_err(|e| Unavailable::Connection(e.to_string()))
344    }
345
346    fn request_preferred(&mut self) {
347        let Some(feedback) = &self.feedback else {
348            return;
349        };
350        if self.state.reading.is_some() {
351            return;
352        }
353        let description = feedback.get_preferred(&self.qh, Purpose::Preferred);
354        self.state.reading = Some((description, Description::default()));
355        self.state.changed = false;
356        let _ = self.conn.flush();
357    }
358
359    /// What the colour manager announces, `None` without one.
360    pub fn capabilities(&self) -> Option<&Capabilities> {
361        self.manager.as_ref().map(|_| &self.state.caps)
362    }
363
364    /// Whether subsurfaces can be made (`wl_subcompositor`).
365    pub fn has_subcompositor(&self) -> bool {
366        self.compositor.is_some() && self.subcompositor.is_some()
367    }
368
369    /// Whether subsurfaces can be scaled to any size (`wp_viewporter`).
370    pub fn has_viewporter(&self) -> bool {
371        self.viewporter.is_some()
372    }
373
374    /// The compositor's preferred description for the window, once read.
375    pub fn preferred(&self) -> Option<&Description> {
376        self.state.preferred.as_ref()
377    }
378
379    /// Why the preferred description could not be read, if it could not.
380    pub fn preferred_error(&self) -> Option<&str> {
381        self.state.preferred_error.as_deref()
382    }
383
384    /// Bumped each time the preferred description changes.
385    pub fn revision(&self) -> u64 {
386        self.state.revision
387    }
388
389    /// Handles what arrived for this queue (winit reads the socket) and
390    /// asks again for the preferred description when the compositor says
391    /// it changed (the window moved to another screen). Never blocks.
392    pub fn poll(&mut self) -> Result<(), String> {
393        self.queue
394            .dispatch_pending(&mut self.state)
395            .map_err(|e| e.to_string())?;
396        if self.state.changed {
397            self.request_preferred();
398        }
399        self.conn.flush().map_err(|e| e.to_string())
400    }
401
402    /// A ready description for named primaries and transfer (made once,
403    /// waiting for the compositor).
404    fn description(
405        &mut self,
406        primaries: NamedPrimaries,
407        transfer: NamedTransfer,
408    ) -> Result<WpImageDescriptionV1, String> {
409        let key = (primaries.code(), transfer.code());
410        if let Some(d) = self.descriptions.get(&key) {
411            return Ok(d.clone());
412        }
413        let caps = self
414            .capabilities()
415            .ok_or("the compositor has no colour manager")?;
416        if !caps.can_tag(primaries, transfer) {
417            return Err(format!(
418                "the compositor does not take {} primaries with the {} transfer",
419                primaries.name(),
420                transfer.name()
421            ));
422        }
423        let manager = self.manager.as_ref().ok_or("no colour manager")?;
424        let named_primaries = wp_color_manager_v1::Primaries::try_from(primaries.code())
425            .map_err(|_| format!("unknown primaries {}", primaries.code()))?;
426        let named_transfer = wp_color_manager_v1::TransferFunction::try_from(transfer.code())
427            .map_err(|_| format!("unknown transfer {}", transfer.code()))?;
428        let creator = manager.create_parametric_creator(&self.qh, ());
429        creator.set_primaries_named(named_primaries);
430        creator.set_tf_named(named_transfer);
431        let description = creator.create(&self.qh, Purpose::Tag);
432        for _ in 0..ROUNDTRIPS {
433            match self.state.status.get(&description.id()) {
434                Some(Status::Ready) => {
435                    self.descriptions.insert(key, description.clone());
436                    return Ok(description);
437                }
438                Some(Status::Failed(e)) => {
439                    let e = e.clone();
440                    description.destroy();
441                    return Err(format!("the compositor refused the description: {e}"));
442                }
443                None => self.roundtrip().map_err(|e| e.to_string())?,
444            }
445        }
446        description.destroy();
447        Err("the compositor did not answer for the description".into())
448    }
449
450    /// A surface for an image, below the window's: synchronised with it
451    /// (its state applies with the window's commit), taking no input,
452    /// sized through `wp_viewporter`.
453    pub fn subsurface(&mut self) -> Result<Subsurface, String> {
454        let compositor = self.compositor.as_ref().ok_or("no wl_compositor")?;
455        let subcompositor = self.subcompositor.as_ref().ok_or("no wl_subcompositor")?;
456        let viewporter = self.viewporter.as_ref().ok_or("no wp_viewporter")?;
457        let surface = compositor.create_surface(&self.qh, ());
458        let subsurface = subcompositor.get_subsurface(&surface, &self.parent, &self.qh, ());
459        subsurface.place_below(&self.parent);
460        subsurface.set_sync();
461        let region = compositor.create_region(&self.qh, ());
462        surface.set_input_region(Some(&region));
463        region.destroy();
464        let viewport = viewporter.get_viewport(&surface, &self.qh, ());
465        self.conn.flush().map_err(|e| e.to_string())?;
466        Ok(Subsurface {
467            keep: Arc::new(Keep {
468                surface,
469                conn: self.conn.clone(),
470            }),
471            subsurface,
472            viewport,
473            colour: None,
474            placed: None,
475            tag: None,
476        })
477    }
478
479    /// Sends what was asked so far (before a present, so the compositor
480    /// gets it with the commit).
481    pub fn flush(&self) -> Result<(), String> {
482        self.conn.flush().map_err(|e| e.to_string())
483    }
484}
485
486impl Drop for Display {
487    fn drop(&mut self) {
488        for (_, d) in self.descriptions.drain() {
489            d.destroy();
490        }
491        if let Some((d, _)) = self.state.reading.take() {
492            d.destroy();
493        }
494        if let Some(f) = self.feedback.take() {
495            f.destroy();
496        }
497        if let Some(m) = self.manager.take() {
498            m.destroy();
499        }
500        if let Some(v) = self.viewporter.take() {
501            v.destroy();
502        }
503        if let Some(s) = self.subcompositor.take() {
504            s.destroy();
505        }
506        let _ = self.conn.flush();
507    }
508}
509
510/// An image's surface under a window's (see [`Display::subsurface`]).
511pub struct Subsurface {
512    keep: Arc<Keep>,
513    subsurface: WlSubsurface,
514    viewport: WpViewport,
515    colour: Option<WpColorManagementSurfaceV1>,
516    placed: Option<[i32; 4]>,
517    tag: Option<(NamedPrimaries, NamedTransfer)>,
518}
519
520impl fmt::Debug for Subsurface {
521    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522        f.debug_struct("Subsurface")
523            .field("surface", &self.keep.surface.id())
524            .field("placed", &self.placed)
525            .field("tag", &self.tag)
526            .finish_non_exhaustive()
527    }
528}
529
530impl Subsurface {
531    /// The handles to create a wgpu surface on; the `wl_surface` lives
532    /// as long as they do.
533    pub fn handle(&self) -> SurfaceHandle {
534        SurfaceHandle {
535            keep: self.keep.clone(),
536        }
537    }
538
539    /// Places it at `[x, y, width, height]`, in logical pixels of the
540    /// window's surface (its buffer is scaled to that size). Applied with
541    /// the subsurface's next commit and the window's.
542    pub fn place(&mut self, rect: [i32; 4]) {
543        if self.placed == Some(rect) {
544            return;
545        }
546        let [x, y, w, h] = rect;
547        self.subsurface.set_position(x, y);
548        if self.placed.is_none_or(|p| p[2] != w || p[3] != h) {
549            self.viewport.set_destination(w.max(1), h.max(1));
550        }
551        self.placed = Some(rect);
552    }
553
554    /// Where it was placed last.
555    pub fn placed(&self) -> Option<[i32; 4]> {
556        self.placed
557    }
558
559    /// Declares its encoding to the compositor, with the perceptual
560    /// intent (the one every compositor takes); applied with its next
561    /// commit. The surface must not be presented to by a driver that
562    /// manages its colour itself
563    /// ([`Capabilities::wsi_claims_srgb_surfaces`]).
564    pub fn tag(
565        &mut self,
566        display: &mut Display,
567        primaries: NamedPrimaries,
568        transfer: NamedTransfer,
569    ) -> Result<(), String> {
570        if self.tag == Some((primaries, transfer)) {
571            return Ok(());
572        }
573        let description = display.description(primaries, transfer)?;
574        let manager = display.manager.as_ref().ok_or("no colour manager")?;
575        let colour = self
576            .colour
577            .get_or_insert_with(|| manager.get_surface(&self.keep.surface, &display.qh, ()));
578        colour.set_image_description(&description, wp_color_manager_v1::RenderIntent::Perceptual);
579        self.tag = Some((primaries, transfer));
580        display.flush()
581    }
582
583    /// The encoding it was tagged with.
584    pub fn tagged(&self) -> Option<(NamedPrimaries, NamedTransfer)> {
585        self.tag
586    }
587}
588
589impl Drop for Subsurface {
590    fn drop(&mut self) {
591        if let Some(c) = self.colour.take() {
592            c.destroy();
593        }
594        self.viewport.destroy();
595        self.subsurface.destroy();
596        let _ = self.keep.conn.flush();
597    }
598}