iced_graphics/
compositor.rs

1//! A compositor is responsible for initializing a renderer and managing window
2//! surfaces.
3use crate::core::Color;
4use crate::futures::{MaybeSend, MaybeSync};
5use crate::{Error, Settings, Viewport};
6
7use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
8use thiserror::Error;
9
10use std::borrow::Cow;
11
12/// A graphics compositor that can draw to windows.
13pub trait Compositor: Sized {
14    /// The iced renderer of the backend.
15    type Renderer;
16
17    /// The surface of the backend.
18    type Surface;
19
20    /// Creates a new [`Compositor`].
21    fn new<W: Window + Clone>(
22        settings: Settings,
23        compatible_window: W,
24    ) -> impl Future<Output = Result<Self, Error>> {
25        Self::with_backend(settings, compatible_window, None)
26    }
27
28    /// Creates a new [`Compositor`] with a backend preference.
29    ///
30    /// If the backend does not match the preference, it will return
31    /// [`Error::GraphicsAdapterNotFound`].
32    fn with_backend<W: Window + Clone>(
33        _settings: Settings,
34        _compatible_window: W,
35        _backend: Option<&str>,
36    ) -> impl Future<Output = Result<Self, Error>>;
37
38    /// Creates a [`Self::Renderer`] for the [`Compositor`].
39    fn create_renderer(&self) -> Self::Renderer;
40
41    /// Crates a new [`Surface`] for the given window.
42    ///
43    /// [`Surface`]: Self::Surface
44    fn create_surface<W: Window + Clone>(
45        &mut self,
46        window: W,
47        width: u32,
48        height: u32,
49    ) -> Self::Surface;
50
51    /// Configures a new [`Surface`] with the given dimensions.
52    ///
53    /// [`Surface`]: Self::Surface
54    fn configure_surface(
55        &mut self,
56        surface: &mut Self::Surface,
57        width: u32,
58        height: u32,
59    );
60
61    /// Returns [`Information`] used by this [`Compositor`].
62    fn fetch_information(&self) -> Information;
63
64    /// Loads a font from its bytes.
65    fn load_font(&mut self, font: Cow<'static, [u8]>) {
66        crate::text::font_system()
67            .write()
68            .expect("Write to font system")
69            .load_font(font);
70    }
71
72    /// Presents the [`Renderer`] primitives to the next frame of the given [`Surface`].
73    ///
74    /// [`Renderer`]: Self::Renderer
75    /// [`Surface`]: Self::Surface
76    fn present(
77        &mut self,
78        renderer: &mut Self::Renderer,
79        surface: &mut Self::Surface,
80        viewport: &Viewport,
81        background_color: Color,
82        on_pre_present: impl FnOnce(),
83    ) -> Result<(), SurfaceError>;
84
85    /// Screenshots the current [`Renderer`] primitives to an offscreen texture, and returns the bytes of
86    /// the texture ordered as `RGBA` in the `sRGB` color space.
87    ///
88    /// [`Renderer`]: Self::Renderer
89    fn screenshot(
90        &mut self,
91        renderer: &mut Self::Renderer,
92        viewport: &Viewport,
93        background_color: Color,
94    ) -> Vec<u8>;
95}
96
97/// A window that can be used in a [`Compositor`].
98///
99/// This is just a convenient super trait of the `raw-window-handle`
100/// traits.
101pub trait Window:
102    HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static
103{
104}
105
106impl<T> Window for T where
107    T: HasWindowHandle + HasDisplayHandle + MaybeSend + MaybeSync + 'static
108{
109}
110
111/// Defines the default compositor of a renderer.
112pub trait Default {
113    /// The compositor of the renderer.
114    type Compositor: Compositor<Renderer = Self>;
115}
116
117/// Result of an unsuccessful call to [`Compositor::present`].
118#[derive(Clone, PartialEq, Eq, Debug, Error)]
119pub enum SurfaceError {
120    /// A timeout was encountered while trying to acquire the next frame.
121    #[error("A timeout was encountered while trying to acquire the next frame")]
122    Timeout,
123    /// The underlying surface has changed, and therefore the surface must be updated.
124    #[error(
125        "The underlying surface has changed, and therefore the surface must be updated."
126    )]
127    Outdated,
128    /// The swap chain has been lost and needs to be recreated.
129    #[error("The surface has been lost and needs to be recreated")]
130    Lost,
131    /// There is no more memory left to allocate a new frame.
132    #[error("There is no more memory left to allocate a new frame")]
133    OutOfMemory,
134    /// Acquiring a texture failed with a generic error.
135    #[error("Acquiring a texture failed with a generic error")]
136    Other,
137}
138
139/// Contains information about the graphics (e.g. graphics adapter, graphics backend).
140#[derive(Debug)]
141pub struct Information {
142    /// Contains the graphics adapter.
143    pub adapter: String,
144    /// Contains the graphics backend.
145    pub backend: String,
146}
147
148#[cfg(debug_assertions)]
149impl Compositor for () {
150    type Renderer = ();
151    type Surface = ();
152
153    async fn with_backend<W: Window + Clone>(
154        _settings: Settings,
155        _compatible_window: W,
156        _preferred_backend: Option<&str>,
157    ) -> Result<Self, Error> {
158        Ok(())
159    }
160
161    fn create_renderer(&self) -> Self::Renderer {}
162
163    fn create_surface<W: Window + Clone>(
164        &mut self,
165        _window: W,
166        _width: u32,
167        _height: u32,
168    ) -> Self::Surface {
169    }
170
171    fn configure_surface(
172        &mut self,
173        _surface: &mut Self::Surface,
174        _width: u32,
175        _height: u32,
176    ) {
177    }
178
179    fn load_font(&mut self, _font: Cow<'static, [u8]>) {}
180
181    fn fetch_information(&self) -> Information {
182        Information {
183            adapter: String::from("Null Renderer"),
184            backend: String::from("Null"),
185        }
186    }
187
188    fn present(
189        &mut self,
190        _renderer: &mut Self::Renderer,
191        _surface: &mut Self::Surface,
192        _viewport: &Viewport,
193        _background_color: Color,
194        _on_pre_present: impl FnOnce(),
195    ) -> Result<(), SurfaceError> {
196        Ok(())
197    }
198
199    fn screenshot(
200        &mut self,
201        _renderer: &mut Self::Renderer,
202        _viewport: &Viewport,
203        _background_color: Color,
204    ) -> Vec<u8> {
205        vec![]
206    }
207}
208
209#[cfg(debug_assertions)]
210impl Default for () {
211    type Compositor = ();
212}