i-slint-backend-selector 1.14.0

Helper crate to pick the default rendering backend for Slint
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

#![warn(missing_docs)]

/*!
This module contains types that are public and re-exported in the slint-rs as well as the slint-interpreter crate as public API,
in particular the `BackendSelector` type.
*/

use alloc::boxed::Box;
use alloc::{format, string::String};

use i_slint_core::api::PlatformError;
use i_slint_core::graphics::{RequestedGraphicsAPI, RequestedOpenGLVersion};

#[i_slint_core_macros::slint_doc]
/// Use the BackendSelector to configure one of Slint's built-in [backends with a renderer](slint:backends_and_renderers)
/// to accommodate specific needs of your application. This is a programmatic substitute for
/// the `SLINT_BACKEND` environment variable.
///
/// For example, to configure Slint to use a renderer that supports OpenGL ES 3.0, configure
/// the `BackendSelector` as follows:
/// ```rust,no_run
/// # use i_slint_backend_selector::api::BackendSelector;
/// let selector = BackendSelector::new().require_opengl_es_with_version(3, 0);
/// if let Err(err) = selector.select() {
///     eprintln!("Error selecting backend with OpenGL ES support: {err}");
/// }
/// ```
#[derive(Default)]
pub struct BackendSelector {
    requested_graphics_api: Option<RequestedGraphicsAPI>,
    backend: Option<String>,
    renderer: Option<String>,
    selected: bool,
    #[cfg(feature = "unstable-winit-030")]
    winit_window_attributes_hook: Option<
        Box<
            dyn Fn(
                i_slint_backend_winit::winit::window::WindowAttributes,
            ) -> i_slint_backend_winit::winit::window::WindowAttributes,
        >,
    >,
    #[cfg(feature = "unstable-winit-030")]
    winit_event_loop_builder: Option<i_slint_backend_winit::EventLoopBuilder>,
    #[cfg(feature = "unstable-winit-030")]
    winit_custom_application_handler:
        Option<Box<dyn i_slint_backend_winit::CustomApplicationHandler>>,
    #[cfg(all(target_os = "linux", feature = "unstable-libinput-09"))]
    libinput_event_hook: Option<Box<dyn Fn(&input::Event) -> bool>>,
}

impl BackendSelector {
    /// Creates a new BackendSelector.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds the requirement to the selector that the backend must render with OpenGL ES
    /// and the specified major and minor version.
    #[must_use]
    pub fn require_opengl_es_with_version(mut self, major: u8, minor: u8) -> Self {
        self.requested_graphics_api =
            Some(RequestedOpenGLVersion::OpenGLES(Some((major, minor))).into());
        self
    }

    /// Adds the requirement to the selector that the backend must render with OpenGL ES.
    #[must_use]
    pub fn require_opengl_es(mut self) -> Self {
        self.requested_graphics_api = Some(RequestedOpenGLVersion::OpenGLES(None).into());
        self
    }

    /// Adds the requirement to the selector that the backend must render with OpenGL.
    #[must_use]
    pub fn require_opengl(mut self) -> Self {
        self.requested_graphics_api = Some(RequestedOpenGLVersion::OpenGL(None).into());
        self
    }

    /// Adds the requirement to the selector that the backend must render with OpenGL
    /// and the specified major and minor version.
    #[must_use]
    pub fn require_opengl_with_version(mut self, major: u8, minor: u8) -> Self {
        self.requested_graphics_api =
            Some(RequestedOpenGLVersion::OpenGL(Some((major, minor))).into());
        self
    }

    /// Adds the requirement to the selector that the backend must render with Apple's Metal framework.
    #[must_use]
    pub fn require_metal(mut self) -> Self {
        self.requested_graphics_api = Some(RequestedGraphicsAPI::Metal);
        self
    }

    /// Adds the requirement to the selector that the backend must render with Vulkan.
    #[must_use]
    pub fn require_vulkan(mut self) -> Self {
        self.requested_graphics_api = Some(RequestedGraphicsAPI::Vulkan);
        self
    }

    /// Adds the requirement to the selector that the backend must render with Direct 3D.
    #[must_use]
    pub fn require_d3d(mut self) -> Self {
        self.requested_graphics_api = Some(RequestedGraphicsAPI::Direct3D);
        self
    }

    #[i_slint_core_macros::slint_doc]
    /// Adds the requirement to the selector that the backend must render using [WGPU](http://wgpu.rs).
    /// Use this when you integrate other WGPU-based renderers with a Slint UI.
    ///
    /// *Note*: This function is behind the [`unstable-wgpu-26` feature flag](slint:rust:slint/docs/cargo_features/#backends)
    ///         and may be removed or changed in future minor releases, as new major WGPU releases become available.
    ///
    /// See also the [`slint::wgpu_26`](slint:rust:slint/wgpu_26) module.
    #[cfg(feature = "unstable-wgpu-26")]
    #[must_use]
    pub fn require_wgpu_26(
        mut self,
        configuration: i_slint_core::graphics::wgpu_26::api::WGPUConfiguration,
    ) -> Self {
        self.requested_graphics_api = Some(RequestedGraphicsAPI::WGPU26(configuration));
        self
    }

    #[i_slint_core_macros::slint_doc]
    /// Adds the requirement to the selector that the backend must render using [WGPU](http://wgpu.rs).
    /// Use this when you integrate other WGPU-based renderers with a Slint UI.
    ///
    /// *Note*: This function is behind the [`unstable-wgpu-27` feature flag](slint:rust:slint/docs/cargo_features/#backends)
    ///         and may be removed or changed in future minor releases, as new major WGPU releases become available.
    ///
    /// See also the [`slint::wgpu_27`](slint:rust:slint/wgpu_27) module.
    #[cfg(feature = "unstable-wgpu-27")]
    #[must_use]
    pub fn require_wgpu_27(
        mut self,
        configuration: i_slint_core::graphics::wgpu_27::api::WGPUConfiguration,
    ) -> Self {
        self.requested_graphics_api = Some(RequestedGraphicsAPI::WGPU27(configuration));
        self
    }

    #[i_slint_core_macros::slint_doc]
    /// Configures this builder to use the specified winit hook that will be called before a Window is created.
    ///
    /// It can be used to adjust settings of window that will be created.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// let mut backend = slint::BackendSelector::new()
    ///     .with_winit_window_attributes_hook(|attributes| attributes.with_content_protected(true))
    ///     .select()
    ///     .unwrap();
    /// ```
    ///
    /// *Note*: This function is behind the [`unstable-winit-030` feature flag](slint:rust:slint/docs/cargo_features/#backends)
    ///         and may be removed or changed in future minor releases, as new major Winit releases become available.
    ///
    /// See also the [`slint::winit_030`](slint:rust:slint/winit_030) module
    #[must_use]
    #[cfg(feature = "unstable-winit-030")]
    pub fn with_winit_window_attributes_hook(
        mut self,
        hook: impl Fn(
                i_slint_backend_winit::winit::window::WindowAttributes,
            ) -> i_slint_backend_winit::winit::window::WindowAttributes
            + 'static,
    ) -> Self {
        self.winit_window_attributes_hook = Some(Box::new(hook));
        self
    }

    #[i_slint_core_macros::slint_doc]
    /// Configures this builder to use the specified winit event loop builder when creating the event
    /// loop.
    ///
    /// *Note*: This function is behind the [`unstable-winit-030` feature flag](slint:rust:slint/docs/cargo_features/#backends)
    ///         and may be removed or changed in future minor releases, as new major Winit releases become available.
    ///
    /// See also the [`slint::winit_030`](slint:rust:slint/winit_030) module
    #[must_use]
    #[cfg(feature = "unstable-winit-030")]
    pub fn with_winit_event_loop_builder(
        mut self,
        event_loop_builder: i_slint_backend_winit::EventLoopBuilder,
    ) -> Self {
        self.winit_event_loop_builder = Some(event_loop_builder);
        self
    }

    #[i_slint_core_macros::slint_doc]
    /// Configures this builder to invoke the functions on the supplied application handler whenever winit wakes up the
    /// event loop.
    ///
    /// *Note*: This function is behind the [`unstable-winit-030` feature flag](slint:rust:slint/docs/cargo_features/#backends)
    ///         and may be removed or changed in future minor releases, as new major Winit releases become available.
    ///
    /// See also the [`slint::winit_030`](slint:rust:slint/winit_030) module
    #[must_use]
    #[cfg(feature = "unstable-winit-030")]
    pub fn with_winit_custom_application_handler(
        mut self,
        custom_application_handler: impl i_slint_backend_winit::CustomApplicationHandler + 'static,
    ) -> Self {
        self.winit_custom_application_handler = Some(Box::new(custom_application_handler));
        self
    }

    #[i_slint_core_macros::slint_doc]
    /// Configures this builder to use the specified libinput event filter hook when the LinuxKMS backend
    /// is selected.
    ///
    /// The provided hook is invoked for every event received. If the function returns true, the event is
    /// not dispatched further.
    ///
    /// *Note*: This function is behind the [`unstable-libinput-09` feature flag](slint:rust:slint/docs/cargo_features/#backends)
    ///         and may be removed or changed in future minor releases, as new major Winit releases become available.
    #[must_use]
    #[cfg(all(target_os = "linux", feature = "unstable-libinput-09"))]
    pub fn with_libinput_event_hook(
        mut self,
        event_hook: impl Fn(&input::Event) -> bool + 'static,
    ) -> Self {
        self.libinput_event_hook = Some(Box::new(event_hook));
        self
    }

    /// Adds the requirement that the selected renderer must match the given name. This is
    /// equivalent to setting the `SLINT_BACKEND=name` environment variable and requires
    /// that the corresponding renderer feature is enabled. For example, to select the Skia renderer,
    /// enable the `renderer-skia` feature and call this function with `skia` as argument.
    #[must_use]
    pub fn renderer_name(mut self, name: String) -> Self {
        self.renderer = Some(name);
        self
    }

    /// Adds the requirement that the selected backend must match the given name. This is
    /// equivalent to setting the `SLINT_BACKEND=name` environment variable and requires
    /// that the corresponding backend feature is enabled. For example, to select the winit backend,
    /// enable the `backend-winit` feature and call this function with `winit` as argument.
    #[must_use]
    pub fn backend_name(mut self, name: String) -> Self {
        self.backend = Some(name);
        self
    }

    /// Completes the backend selection process and tries to combine with specified requirements
    /// with the different backends and renderers enabled at compile time. On success, the selected
    /// backend is automatically set to be active. Returns an error if the requirements could not be met.
    pub fn select(mut self) -> Result<(), PlatformError> {
        self.select_internal()
    }

    #[cfg(not(target_os = "android"))]
    fn select_internal(&mut self) -> Result<(), PlatformError> {
        self.selected = true;

        #[cfg(any(
            feature = "i-slint-backend-qt",
            feature = "i-slint-backend-winit",
            feature = "i-slint-backend-linuxkms"
        ))]
        if self.backend.is_none() || self.renderer.is_none() {
            let backend_config = std::env::var("SLINT_BACKEND").unwrap_or_default();
            let backend_config = backend_config.to_lowercase();
            let (backend, renderer) = super::parse_backend_env_var(backend_config.as_str());
            if !backend.is_empty() {
                self.backend.get_or_insert_with(|| backend.to_owned());
            }
            if !renderer.is_empty() {
                self.renderer.get_or_insert_with(|| renderer.to_owned());
            }
        }

        let backend_name = self.backend.as_deref().unwrap_or_else(|| {
            // Only the winit backend supports graphics API requests right now, so prefer that over
            // aborting.
            #[cfg(feature = "i-slint-backend-winit")]
            if self.requested_graphics_api.is_some() {
                return "winit";
            }
            super::DEFAULT_BACKEND_NAME
        });

        let backend: Box<dyn i_slint_core::platform::Platform> = match backend_name {
            #[cfg(all(feature = "i-slint-backend-linuxkms", target_os = "linux"))]
            "linuxkms" => {
                if self.requested_graphics_api.is_some() {
                    return Err("The linuxkms backend does not implement renderer selection by graphics API".into());
                }

                let mut builder = i_slint_backend_linuxkms::BackendBuilder::default();

                if let Some(renderer_name) = self.renderer.as_ref() {
                    builder = builder.with_renderer_name(renderer_name.into());
                }

                #[cfg(all(target_os = "linux", feature = "unstable-libinput-09"))]
                if let Some(event_hook) = self.libinput_event_hook.take() {
                    builder = builder.with_libinput_event_hook(event_hook);
                }

                Box::new(builder.build()?)
            }
            #[cfg(feature = "i-slint-backend-winit")]
            "winit" => {
                let builder = i_slint_backend_winit::Backend::builder();

                let builder = match self.requested_graphics_api.as_ref() {
                    Some(api) => builder.request_graphics_api(api.clone()),
                    None => builder,
                };

                let builder = match self.renderer.as_ref() {
                    Some(name) => builder.with_renderer_name(name),
                    None => builder,
                };

                #[cfg(feature = "unstable-winit-030")]
                let builder = match self.winit_window_attributes_hook.take() {
                    Some(hook) => builder.with_window_attributes_hook(hook),
                    None => builder,
                };

                #[cfg(feature = "unstable-winit-030")]
                let builder = match self.winit_event_loop_builder.take() {
                    Some(event_loop_builder) => builder.with_event_loop_builder(event_loop_builder),
                    None => builder,
                };

                #[cfg(feature = "unstable-winit-030")]
                let builder = match self.winit_custom_application_handler.take() {
                    Some(custom_application_handler) => {
                        builder.with_custom_application_handler(custom_application_handler)
                    }
                    None => builder,
                };

                Box::new(builder.build()?)
            }
            #[cfg(feature = "i-slint-backend-qt")]
            "qt" => {
                if self.requested_graphics_api.is_some() {
                    return Err(
                        "The qt backend does not implement renderer selection by graphics API"
                            .into(),
                    );
                }
                if self.renderer.is_some() {
                    return Err(
                        "The qt backend does not implement renderer selection by name".into()
                    );
                }
                Box::new(i_slint_backend_qt::Backend::new())
            }
            requested_backend => {
                return Err(format!(
                    "{requested_backend} backend requested but it is not available"
                )
                .into());
            }
        };

        i_slint_core::platform::set_platform(backend).map_err(PlatformError::SetPlatformError)
    }

    #[cfg(target_os = "android")]
    fn select_internal(&mut self) -> Result<(), PlatformError> {
        self.selected = true;
        if self.backend.as_ref().is_some_and(|b| !b.starts_with("android-activity-")) {
            return Err(
                format!("Only the android-activity-* backend is supported on Android").into()
            );
        }
        if self.renderer.as_ref().is_some_and(|r| r != "skia") {
            return Err(format!("Only the Skia renderer is supported on Android").into());
        }

        if cfg!(feature = "backend-android-activity") {
            i_slint_backend_android_activity::set_requested_graphics_api(
                self.requested_graphics_api.clone(),
            )
        } else {
            Err(format!(
                "The BackendSelector is only supported with the backend-android-activity backend"
            )
            .into())
        }
    }
}

impl Drop for BackendSelector {
    fn drop(&mut self) {
        if !self.selected {
            self.select_internal().unwrap();
        }
    }
}