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 + Send + Sync>;
35pub type WindowHandleHook = Box<dyn FnOnce(&mut Window) + Send + Sync>;
36
37/// Decision returned by the `on_close` hook to determine whether a window should close.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum CloseDecision {
40    /// Close the window.
41    #[default]
42    Close,
43    /// Keep the window open.
44    KeepOpen,
45}
46
47/// Hook called when a window close is requested.
48/// Returns a [`CloseDecision`] to determine whether the window should actually close.
49pub type OnCloseHook =
50    Box<dyn FnMut(crate::renderer::RendererContext, WindowId) -> CloseDecision + Send>;
51
52/// Configuration for a Window.
53pub struct WindowConfig {
54    /// Root component for the window app.
55    pub(crate) app: AppComponent,
56    /// Size of the Window.
57    pub(crate) size: (f64, f64),
58    /// Minimum size of the Window.
59    pub(crate) min_size: Option<(f64, f64)>,
60    /// Maximum size of the Window.
61    pub(crate) max_size: Option<(f64, f64)>,
62    /// Enable Window decorations.
63    pub(crate) decorations: bool,
64    /// Title for the Window.
65    pub(crate) title: &'static str,
66    /// Make the Window transparent or not.
67    pub(crate) transparent: bool,
68    /// Background color of the Window.
69    pub(crate) background: Color,
70    /// Enable Window resizable behaviour.
71    pub(crate) resizable: bool,
72    /// Icon for the Window.
73    pub(crate) icon: Option<Icon>,
74    /// Hook function called with the Window Attributes.
75    pub(crate) window_attributes_hook: Option<WindowBuilderHook>,
76    /// Hook function called with the Window.
77    pub(crate) window_handle_hook: Option<WindowHandleHook>,
78    /// Hook function called when the window is requested to close.
79    pub(crate) on_close: Option<OnCloseHook>,
80}
81
82impl Debug for WindowConfig {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("WindowConfig")
85            .field("size", &self.size)
86            .field("min_size", &self.min_size)
87            .field("max_size", &self.max_size)
88            .field("decorations", &self.decorations)
89            .field("title", &self.title)
90            .field("transparent", &self.transparent)
91            .field("background", &self.background)
92            .field("resizable", &self.resizable)
93            .field("icon", &self.icon)
94            .finish()
95    }
96}
97
98impl WindowConfig {
99    /// Create a window with the given app.
100    pub fn new(app: impl Into<AppComponent>) -> Self {
101        Self::new_with_defaults(app.into())
102    }
103
104    fn new_with_defaults(app: impl Into<AppComponent>) -> Self {
105        Self {
106            app: app.into(),
107            size: (700.0, 500.0),
108            min_size: None,
109            max_size: None,
110            decorations: true,
111            title: "Freya",
112            transparent: false,
113            background: Color::WHITE,
114            resizable: true,
115            icon: None,
116            window_attributes_hook: None,
117            window_handle_hook: None,
118            on_close: None,
119        }
120    }
121
122    /// Specify a Window size.
123    pub fn with_size(mut self, width: f64, height: f64) -> Self {
124        self.size = (width, height);
125        self
126    }
127
128    /// Specify a minimum Window size.
129    pub fn with_min_size(mut self, min_width: f64, min_height: f64) -> Self {
130        self.min_size = Some((min_width, min_height));
131        self
132    }
133
134    /// Specify a maximum Window size.
135    pub fn with_max_size(mut self, max_width: f64, max_height: f64) -> Self {
136        self.max_size = Some((max_width, max_height));
137        self
138    }
139
140    /// Whether the Window will have decorations or not.
141    pub fn with_decorations(mut self, decorations: bool) -> Self {
142        self.decorations = decorations;
143        self
144    }
145
146    /// Specify the Window title.
147    pub fn with_title(mut self, title: &'static str) -> Self {
148        self.title = title;
149        self
150    }
151
152    /// Make the Window transparent or not.
153    pub fn with_transparency(mut self, transparency: bool) -> Self {
154        self.transparent = transparency;
155        self
156    }
157
158    /// Specify the Window's background color.
159    pub fn with_background(mut self, background: impl Into<Color>) -> Self {
160        self.background = background.into();
161        self
162    }
163
164    /// Is Window resizable.
165    pub fn with_resizable(mut self, resizable: bool) -> Self {
166        self.resizable = resizable;
167        self
168    }
169
170    /// Specify Window icon.
171    pub fn with_icon(mut self, icon: Icon) -> Self {
172        self.icon = Some(icon);
173        self
174    }
175
176    /// Register a Window Attributes hook.
177    pub fn with_window_attributes(
178        mut self,
179        window_attributes_hook: impl FnOnce(WindowAttributes, &ActiveEventLoop) -> WindowAttributes
180        + 'static
181        + Send
182        + Sync,
183    ) -> Self {
184        self.window_attributes_hook = Some(Box::new(window_attributes_hook));
185        self
186    }
187
188    /// Register a Window handle hook.
189    pub fn with_window_handle(
190        mut self,
191        window_handle_hook: impl FnOnce(&mut Window) + 'static + Send + Sync,
192    ) -> Self {
193        self.window_handle_hook = Some(Box::new(window_handle_hook));
194        self
195    }
196
197    /// Register an on-close hook that is called when the window is requested to close by the user.
198    pub fn with_on_close(
199        mut self,
200        on_close: impl FnMut(crate::renderer::RendererContext, WindowId) -> CloseDecision
201        + 'static
202        + Send,
203    ) -> Self {
204        self.on_close = Some(Box::new(on_close));
205        self
206    }
207}
208
209pub type EmbeddedFonts = Vec<(Cow<'static, str>, Bytes)>;
210#[cfg(feature = "tray")]
211pub type TrayIconGetter = Box<dyn FnOnce() -> tray_icon::TrayIcon + Send>;
212#[cfg(feature = "tray")]
213pub type TrayHandler =
214    Box<dyn FnMut(crate::tray_icon::TrayEvent, crate::renderer::RendererContext)>;
215
216pub type TaskHandler =
217    Box<dyn FnOnce(crate::renderer::LaunchProxy) -> Pin<Box<dyn Future<Output = ()>>> + 'static>;
218
219/// Launch configuration.
220pub struct LaunchConfig {
221    pub(crate) windows_configs: Vec<WindowConfig>,
222    #[cfg(feature = "tray")]
223    pub(crate) tray: (Option<TrayIconGetter>, Option<TrayHandler>),
224    pub(crate) plugins: PluginsManager,
225    pub(crate) embedded_fonts: EmbeddedFonts,
226    pub(crate) fallback_fonts: Vec<Cow<'static, str>>,
227    pub(crate) tasks: Vec<TaskHandler>,
228}
229
230impl Default for LaunchConfig {
231    fn default() -> Self {
232        LaunchConfig {
233            windows_configs: Vec::default(),
234            #[cfg(feature = "tray")]
235            tray: (None, None),
236            plugins: PluginsManager::default(),
237            embedded_fonts: Default::default(),
238            fallback_fonts: default_fonts(),
239            tasks: Vec::new(),
240        }
241    }
242}
243
244impl LaunchConfig {
245    pub fn new() -> LaunchConfig {
246        LaunchConfig::default()
247    }
248
249    pub fn window_icon(icon: &[u8]) -> Icon {
250        let reader = ImageReader::new(Cursor::new(icon))
251            .with_guessed_format()
252            .expect("Cursor io never fails");
253        let image = reader
254            .decode()
255            .expect("Failed to open icon path")
256            .into_rgba8();
257        let (width, height) = image.dimensions();
258        let rgba = image.into_raw();
259        Icon::from_rgba(rgba, width, height).expect("Failed to open icon")
260    }
261
262    #[cfg(feature = "tray")]
263    pub fn tray_icon(icon: &[u8]) -> tray_icon::Icon {
264        let reader = ImageReader::new(Cursor::new(icon))
265            .with_guessed_format()
266            .expect("Cursor io never fails");
267        let image = reader
268            .decode()
269            .expect("Failed to open icon path")
270            .into_rgba8();
271        let (width, height) = image.dimensions();
272        let rgba = image.into_raw();
273        tray_icon::Icon::from_rgba(rgba, width, height).expect("Failed to open icon")
274    }
275}
276
277impl LaunchConfig {
278    /// Register a window configuration. You can call this multiple times.
279    pub fn with_window(mut self, window_config: WindowConfig) -> Self {
280        self.windows_configs.push(window_config);
281        self
282    }
283
284    /// Register a tray icon and its handler.
285    #[cfg(feature = "tray")]
286    pub fn with_tray(
287        mut self,
288        tray_icon: impl FnOnce() -> tray_icon::TrayIcon + 'static + Send,
289        tray_handler: impl FnMut(crate::tray_icon::TrayEvent, crate::renderer::RendererContext)
290        + 'static,
291    ) -> Self {
292        self.tray = (Some(Box::new(tray_icon)), Some(Box::new(tray_handler)));
293        self
294    }
295
296    /// Register a plugin.
297    pub fn with_plugin(mut self, plugin: impl FreyaPlugin + 'static) -> Self {
298        self.plugins.add_plugin(plugin);
299        self
300    }
301
302    /// Embed a font.
303    pub fn with_font(
304        mut self,
305        font_name: impl Into<Cow<'static, str>>,
306        font: impl Into<Bytes>,
307    ) -> Self {
308        self.embedded_fonts.push((font_name.into(), font.into()));
309        self
310    }
311
312    /// Register a fallback font. Will be used if the default fonts are not available.
313    pub fn with_fallback_font(mut self, font_family: impl Into<Cow<'static, str>>) -> Self {
314        self.fallback_fonts.push(font_family.into());
315        self
316    }
317
318    /// Register a default font. Will be used if found.
319    pub fn with_default_font(mut self, font_name: impl Into<Cow<'static, str>>) -> Self {
320        self.fallback_fonts.insert(0, font_name.into());
321        self
322    }
323
324    /// Register a single-thread launch task.
325    /// The task receives a [LaunchProxy] that can be used to get access to [RendererContext](crate::renderer::RendererContext).
326    /// The provided callback should return a `'static` future which will be scheduled on the renderer
327    /// thread and polled until completion.
328    pub fn with_future<F, Fut>(mut self, task: F) -> Self
329    where
330        F: FnOnce(LaunchProxy) -> Fut + 'static,
331        Fut: Future<Output = ()> + 'static,
332    {
333        self.tasks
334            .push(Box::new(move |proxy| Box::pin(task(proxy))));
335        self
336    }
337}