Skip to main content

freya_winit/
config.rs

1use std::{
2    borrow::Cow,
3    fmt::Debug,
4    future::Future,
5    io::Cursor,
6    pin::Pin,
7};
8
9use bytes::Bytes;
10use freya_core::{
11    integration::*,
12    prelude::Color,
13};
14use image::ImageReader;
15use winit::{
16    event_loop::ActiveEventLoop,
17    window::{
18        Icon,
19        Window,
20        WindowAttributes,
21        WindowId,
22    },
23};
24
25use crate::{
26    plugins::{
27        FreyaPlugin,
28        PluginsManager,
29    },
30    renderer::LaunchProxy,
31};
32
33pub type WindowBuilderHook =
34    Box<dyn FnOnce(WindowAttributes, &ActiveEventLoop) -> WindowAttributes>;
35pub type WindowHandleHook = Box<dyn FnOnce(&mut Window)>;
36
37/// Preferred GPU type, with fallback to other available hardware.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
39pub enum GpuPreference {
40    /// Match Wayland's preferred GPU, otherwise prefer integrated hardware.
41    #[default]
42    Auto,
43    /// Prefer an integrated GPU.
44    Integrated,
45    /// Prefer a discrete GPU.
46    Discrete,
47}
48
49/// Graphics driver preference a window asks for.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub enum RendererPreference {
52    /// Always pick the best renderer given the hardware and the OS.
53    #[default]
54    Auto,
55    Software,
56    OpenGl,
57    Vulkan {
58        gpu_preference: GpuPreference,
59    },
60}
61
62impl RendererPreference {
63    /// Return the Vulkan GPU preference or the default for other renderers.
64    pub fn gpu_preference(self) -> GpuPreference {
65        match self {
66            Self::Vulkan { gpu_preference } => gpu_preference,
67            _ => GpuPreference::default(),
68        }
69    }
70}
71
72/// Decision returned by the `on_close` hook to determine whether a window should close.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
74pub enum CloseDecision {
75    /// Close the window.
76    #[default]
77    Close,
78    /// Keep the window open.
79    KeepOpen,
80}
81
82/// Hook called when a window close is requested.
83/// Returns a [`CloseDecision`] to determine whether the window should actually close.
84pub type OnCloseHook = Box<dyn FnMut(crate::renderer::RendererContext, WindowId) -> CloseDecision>;
85
86/// Configuration for a Window.
87pub struct WindowConfig {
88    /// Root component for the window app.
89    pub(crate) app: AppComponent,
90    pub(crate) root_contexts: Vec<Box<dyn FnOnce()>>,
91    /// Size of the Window.
92    pub(crate) size: (f64, f64),
93    /// Minimum size of the Window.
94    pub(crate) min_size: Option<(f64, f64)>,
95    /// Maximum size of the Window.
96    pub(crate) max_size: Option<(f64, f64)>,
97    /// Enable Window decorations.
98    pub(crate) decorations: bool,
99    /// Title for the Window.
100    pub(crate) title: &'static str,
101    /// Make the Window transparent or not.
102    pub(crate) transparent: bool,
103    /// Background color of the Window.
104    pub(crate) background: Color,
105    /// Enable Window resizable behaviour.
106    pub(crate) resizable: bool,
107    /// Custom scale factor for the Window.
108    pub(crate) custom_scale_factor: f64,
109    /// Icon for the Window.
110    pub(crate) icon: Option<Icon>,
111    /// Application ID for the Window.
112    pub(crate) app_id: Option<String>,
113    /// Preferred graphics backend for the Window.
114    pub(crate) renderer: RendererPreference,
115    /// Hook function called with the Window Attributes.
116    pub(crate) window_attributes_hook: Option<WindowBuilderHook>,
117    /// Hook function called with the Window.
118    pub(crate) window_handle_hook: Option<WindowHandleHook>,
119    /// Hook function called when the window is requested to close.
120    pub(crate) on_close: Option<OnCloseHook>,
121}
122
123impl Debug for WindowConfig {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        f.debug_struct("WindowConfig")
126            .field("size", &self.size)
127            .field("min_size", &self.min_size)
128            .field("max_size", &self.max_size)
129            .field("decorations", &self.decorations)
130            .field("title", &self.title)
131            .field("transparent", &self.transparent)
132            .field("background", &self.background)
133            .field("resizable", &self.resizable)
134            .field("custom_scale_factor", &self.custom_scale_factor)
135            .field("icon", &self.icon)
136            .field("app_id", &self.app_id)
137            .field("renderer", &self.renderer)
138            .finish()
139    }
140}
141
142impl WindowConfig {
143    /// Create a window with the given app.
144    pub fn new(app: impl Into<AppComponent>) -> Self {
145        Self::new_with_defaults(app.into())
146    }
147
148    /// Create a window using an `App` directly.
149    pub fn new_app(app: impl App + 'static) -> Self {
150        Self::new_with_defaults(AppComponent::new(app))
151    }
152
153    fn new_with_defaults(app: impl Into<AppComponent>) -> Self {
154        Self {
155            app: app.into(),
156            root_contexts: Vec::new(),
157            size: (700.0, 500.0),
158            min_size: None,
159            max_size: None,
160            decorations: true,
161            title: "Freya",
162            transparent: false,
163            background: Color::WHITE,
164            resizable: true,
165            custom_scale_factor: 1.0,
166            icon: None,
167            app_id: None,
168            renderer: RendererPreference::default(),
169            window_attributes_hook: None,
170            window_handle_hook: None,
171            on_close: None,
172        }
173    }
174
175    /// Provide a context to the window's root before its first render.
176    pub fn with_root_context<T: Clone + 'static>(mut self, value: T) -> Self {
177        self.root_contexts.push(Box::new(move || {
178            freya_core::prelude::provide_root_context(value);
179        }));
180        self
181    }
182
183    /// Specify a Window size.
184    pub fn with_size(mut self, width: f64, height: f64) -> Self {
185        self.size = (width, height);
186        self
187    }
188
189    /// Specify a minimum Window size.
190    pub fn with_min_size(mut self, min_width: f64, min_height: f64) -> Self {
191        self.min_size = Some((min_width, min_height));
192        self
193    }
194
195    /// Specify a maximum Window size.
196    pub fn with_max_size(mut self, max_width: f64, max_height: f64) -> Self {
197        self.max_size = Some((max_width, max_height));
198        self
199    }
200
201    /// Whether the Window will have decorations or not.
202    pub fn with_decorations(mut self, decorations: bool) -> Self {
203        self.decorations = decorations;
204        self
205    }
206
207    /// Specify the Window title.
208    pub fn with_title(mut self, title: &'static str) -> Self {
209        self.title = title;
210        self
211    }
212
213    /// Make the Window transparent or not.
214    pub fn with_transparency(mut self, transparency: bool) -> Self {
215        self.transparent = transparency;
216        self
217    }
218
219    /// Specify the Window's background color.
220    pub fn with_background(mut self, background: impl Into<Color>) -> Self {
221        self.background = background.into();
222        self
223    }
224
225    /// Is Window resizable.
226    pub fn with_resizable(mut self, resizable: bool) -> Self {
227        self.resizable = resizable;
228        self
229    }
230
231    /// Specify a custom scale factor for the Window, multiplied with the OS
232    /// scale factor. Defaults to `1.0`.
233    pub fn with_custom_scale_factor(mut self, custom_scale_factor: f64) -> Self {
234        self.custom_scale_factor = custom_scale_factor;
235        self
236    }
237
238    /// Specify the Window icon. Use [`LaunchConfig::window_icon`] to load the icon from bytes.
239    ///
240    /// # Example
241    /// ```no_run
242    /// # use freya::prelude::*;
243    /// const ICON: &[u8] = include_bytes!("../../../examples/freya_icon.png");
244    ///
245    /// WindowConfig::new(app).with_icon(LaunchConfig::window_icon(ICON));
246    /// # fn app() -> impl IntoElement { "" }
247    /// ```
248    pub fn with_icon(mut self, icon: Icon) -> Self {
249        self.icon = Some(icon);
250        self
251    }
252
253    /// Set the application ID for the Window, should match the `.desktop` file of your program.
254    pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self {
255        self.app_id = Some(app_id.into());
256        self
257    }
258
259    /// Prefer a graphics backend for this Window, overriding `FREYA_RENDERER`.
260    pub fn with_renderer(mut self, renderer: RendererPreference) -> Self {
261        self.renderer = renderer;
262        self
263    }
264
265    /// Register a Window Attributes hook.
266    pub fn with_window_attributes(
267        mut self,
268        window_attributes_hook: impl FnOnce(WindowAttributes, &ActiveEventLoop) -> WindowAttributes
269        + 'static,
270    ) -> Self {
271        self.window_attributes_hook = Some(Box::new(window_attributes_hook));
272        self
273    }
274
275    /// Register a Window handle hook.
276    pub fn with_window_handle(
277        mut self,
278        window_handle_hook: impl FnOnce(&mut Window) + 'static,
279    ) -> Self {
280        self.window_handle_hook = Some(Box::new(window_handle_hook));
281        self
282    }
283
284    /// Register an on-close hook that is called when the window is requested to close by the user.
285    pub fn with_on_close(
286        mut self,
287        on_close: impl FnMut(crate::renderer::RendererContext, WindowId) -> CloseDecision + 'static,
288    ) -> Self {
289        self.on_close = Some(Box::new(on_close));
290        self
291    }
292}
293
294/// GPU resource cache limit used by the renderer.
295#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
296pub enum GpuResourceCacheLimit {
297    /// 128 MiB for applications with low graphics resource usage.
298    Small,
299    /// 256 MiB, matching Skia's default cache limit.
300    #[default]
301    Normal,
302    /// 1 GiB for applications with large graphics resource usage.
303    Large,
304    /// A custom limit in bytes.
305    Custom(usize),
306}
307
308impl From<usize> for GpuResourceCacheLimit {
309    fn from(bytes: usize) -> Self {
310        Self::Custom(bytes)
311    }
312}
313
314impl GpuResourceCacheLimit {
315    /// Creates a custom cache limit from a number of mebibytes.
316    pub const fn from_mb(megabytes: usize) -> Self {
317        Self::Custom(megabytes * 1024 * 1024)
318    }
319
320    /// Returns the cache limit in bytes.
321    pub const fn bytes(self) -> usize {
322        match self {
323            Self::Small => 128 * 1024 * 1024,
324            Self::Normal => 256 * 1024 * 1024,
325            Self::Large => 1024 * 1024 * 1024,
326            Self::Custom(bytes) => bytes,
327        }
328    }
329}
330
331pub type EmbeddedFonts = Vec<(Cow<'static, str>, Bytes)>;
332#[cfg(feature = "tray")]
333pub type TrayIconGetter = Box<dyn FnOnce() -> tray_icon::TrayIcon>;
334#[cfg(feature = "tray")]
335pub type TrayHandler =
336    Box<dyn FnMut(crate::tray_icon::TrayEvent, crate::renderer::RendererContext)>;
337
338pub type TaskHandler =
339    Box<dyn FnOnce(crate::renderer::LaunchProxy) -> Pin<Box<dyn Future<Output = ()>>> + 'static>;
340
341pub type GlobalContextInserter = Box<dyn FnOnce(&GlobalContexts)>;
342
343/// Configuration for the initial state of the application.
344///
345/// Use this to register windows, plugins, fonts, and other settings
346/// that should be ready before the application starts.
347pub struct LaunchConfig {
348    pub(crate) windows_configs: Vec<WindowConfig>,
349    #[cfg(feature = "tray")]
350    pub(crate) tray: (Option<TrayIconGetter>, Option<TrayHandler>),
351    pub(crate) plugins: PluginsManager,
352    pub(crate) embedded_fonts: EmbeddedFonts,
353    pub(crate) fallback_fonts: Vec<Cow<'static, str>>,
354    pub(crate) tasks: Vec<TaskHandler>,
355    pub(crate) globals: Vec<GlobalContextInserter>,
356    pub(crate) exit_on_close: bool,
357    pub(crate) event_loop: Option<winit::event_loop::EventLoop<crate::renderer::NativeEvent>>,
358    pub(crate) gpu_resource_cache_limit: usize,
359}
360
361impl Default for LaunchConfig {
362    fn default() -> Self {
363        LaunchConfig {
364            windows_configs: Vec::default(),
365            #[cfg(feature = "tray")]
366            tray: (None, None),
367            plugins: PluginsManager::default(),
368            embedded_fonts: Default::default(),
369            fallback_fonts: default_fonts(),
370            tasks: Vec::new(),
371            globals: Vec::new(),
372            exit_on_close: true,
373            event_loop: None,
374            gpu_resource_cache_limit: GpuResourceCacheLimit::default().bytes(),
375        }
376    }
377}
378
379impl LaunchConfig {
380    pub fn new() -> LaunchConfig {
381        LaunchConfig::default()
382    }
383
384    /// Load a window icon from image bytes. Pass the result to [`WindowConfig::with_icon`].
385    pub fn window_icon(icon: &[u8]) -> Icon {
386        let reader = ImageReader::new(Cursor::new(icon))
387            .with_guessed_format()
388            .expect("Cursor io never fails");
389        let image = reader
390            .decode()
391            .expect("Failed to open icon path")
392            .into_rgba8();
393        let (width, height) = image.dimensions();
394        let rgba = image.into_raw();
395        Icon::from_rgba(rgba, width, height).expect("Failed to open icon")
396    }
397
398    #[cfg(feature = "tray")]
399    pub fn tray_icon(icon: &[u8]) -> tray_icon::Icon {
400        let reader = ImageReader::new(Cursor::new(icon))
401            .with_guessed_format()
402            .expect("Cursor io never fails");
403        let image = reader
404            .decode()
405            .expect("Failed to open icon path")
406            .into_rgba8();
407        let (width, height) = image.dimensions();
408        let rgba = image.into_raw();
409        tray_icon::Icon::from_rgba(rgba, width, height).expect("Failed to open icon")
410    }
411}
412
413impl LaunchConfig {
414    /// Register a window configuration. You can call this multiple times.
415    ///
416    /// To create windows dynamically after the application has started,
417    /// see [`crate::extensions::WinitPlatformExt::launch_window()`].
418    pub fn with_window(mut self, window_config: WindowConfig) -> Self {
419        self.windows_configs.push(window_config);
420        self
421    }
422
423    /// Register a tray icon and its handler.
424    #[cfg(feature = "tray")]
425    pub fn with_tray(
426        mut self,
427        tray_icon: impl FnOnce() -> tray_icon::TrayIcon + 'static,
428        tray_handler: impl FnMut(crate::tray_icon::TrayEvent, crate::renderer::RendererContext)
429        + 'static,
430    ) -> Self {
431        self.tray = (Some(Box::new(tray_icon)), Some(Box::new(tray_handler)));
432        self
433    }
434
435    /// Register a plugin. Replaces any existing plugin with the same ID.
436    pub fn with_plugin(mut self, plugin: impl FreyaPlugin + 'static) -> Self {
437        self.plugins.add_plugin(plugin);
438        self
439    }
440
441    /// Embed a font.
442    pub fn with_font(
443        mut self,
444        font_name: impl Into<Cow<'static, str>>,
445        font: impl Into<Bytes>,
446    ) -> Self {
447        self.embedded_fonts.push((font_name.into(), font.into()));
448        self
449    }
450
451    /// Register a fallback font. Will be used if the default fonts are not available.
452    pub fn with_fallback_font(mut self, font_family: impl Into<Cow<'static, str>>) -> Self {
453        self.fallback_fonts.push(font_family.into());
454        self
455    }
456
457    /// Register a default font. Will be used if found.
458    pub fn with_default_font(mut self, font_name: impl Into<Cow<'static, str>>) -> Self {
459        self.fallback_fonts.insert(0, font_name.into());
460        self
461    }
462
463    /// Register a value in the [`GlobalContexts`], shared by all the windows.
464    ///
465    /// ```rust,no_run
466    /// # use freya::prelude::*;
467    /// #[derive(Clone)]
468    /// struct AppName(String);
469    ///
470    /// fn main() {
471    ///     launch(
472    ///         LaunchConfig::new()
473    ///             .with_global_context(AppName("Freya".to_string()))
474    ///             .with_window(WindowConfig::new(app)),
475    ///     )
476    /// }
477    ///
478    /// fn app() -> impl IntoElement {
479    ///     let app_name = GlobalContexts::get().get_context::<AppName>();
480    ///
481    ///     label().text(app_name.0)
482    /// }
483    /// ```
484    pub fn with_global_context<T: Clone + 'static>(mut self, value: T) -> Self {
485        self.globals.push(Box::new(move |global_contexts| {
486            global_contexts.insert_context(value);
487        }));
488        self
489    }
490
491    /// Whether to exit the event loop when all windows are closed. Defaults to `true`.
492    /// Set to `false` to keep the event loop alive even when no windows remain.
493    pub fn with_exit_on_close(mut self, exit_on_close: bool) -> Self {
494        self.exit_on_close = exit_on_close;
495        self
496    }
497
498    /// Register an async task that starts on the app launch.
499    ///
500    /// ```rust,no_run
501    /// # use freya::prelude::*;
502    /// let config = LaunchConfig::new().with_task(|proxy| async move {
503    ///     let _ = proxy
504    ///         .post_callback(|renderer| renderer.launch_window(WindowConfig::new(|| "Hello!")))
505    ///         .await;
506    /// });
507    /// ```
508    pub fn with_task<F, Fut>(mut self, task: F) -> Self
509    where
510        F: FnOnce(LaunchProxy) -> Fut + 'static,
511        Fut: Future<Output = ()> + 'static,
512    {
513        self.tasks
514            .push(Box::new(move |proxy| Box::pin(task(proxy))));
515        self
516    }
517
518    /// Provide a custom winit [EventLoop](winit::event_loop::EventLoop) to use instead of the default one.
519    /// This allows configuring platform-specific options on the event loop builder before passing it.
520    pub fn with_event_loop(
521        mut self,
522        event_loop: winit::event_loop::EventLoop<crate::renderer::NativeEvent>,
523    ) -> Self {
524        self.event_loop = Some(event_loop);
525        self
526    }
527
528    /// Set the Skia GPU resource cache limit applied to every window. Defaults to [`GpuResourceCacheLimit::Normal`].
529    pub fn with_gpu_resource_cache_limit(
530        mut self,
531        gpu_resource_cache_limit: impl Into<GpuResourceCacheLimit>,
532    ) -> Self {
533        self.gpu_resource_cache_limit = gpu_resource_cache_limit.into().bytes();
534        self
535    }
536}