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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
39pub enum GpuPreference {
40 #[default]
42 Auto,
43 Integrated,
45 Discrete,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub enum RendererPreference {
52 #[default]
54 Auto,
55 Software,
56 OpenGl,
57 Vulkan {
58 gpu_preference: GpuPreference,
59 },
60}
61
62impl RendererPreference {
63 pub fn gpu_preference(self) -> GpuPreference {
65 match self {
66 Self::Vulkan { gpu_preference } => gpu_preference,
67 _ => GpuPreference::default(),
68 }
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
74pub enum CloseDecision {
75 #[default]
77 Close,
78 KeepOpen,
80}
81
82pub type OnCloseHook = Box<dyn FnMut(crate::renderer::RendererContext, WindowId) -> CloseDecision>;
85
86pub struct WindowConfig {
88 pub(crate) app: AppComponent,
90 pub(crate) root_contexts: Vec<Box<dyn FnOnce()>>,
91 pub(crate) size: (f64, f64),
93 pub(crate) min_size: Option<(f64, f64)>,
95 pub(crate) max_size: Option<(f64, f64)>,
97 pub(crate) decorations: bool,
99 pub(crate) title: &'static str,
101 pub(crate) transparent: bool,
103 pub(crate) background: Color,
105 pub(crate) resizable: bool,
107 pub(crate) custom_scale_factor: f64,
109 pub(crate) icon: Option<Icon>,
111 pub(crate) app_id: Option<String>,
113 pub(crate) renderer: RendererPreference,
115 pub(crate) window_attributes_hook: Option<WindowBuilderHook>,
117 pub(crate) window_handle_hook: Option<WindowHandleHook>,
119 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 pub fn new(app: impl Into<AppComponent>) -> Self {
145 Self::new_with_defaults(app.into())
146 }
147
148 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 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 pub fn with_size(mut self, width: f64, height: f64) -> Self {
185 self.size = (width, height);
186 self
187 }
188
189 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 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 pub fn with_decorations(mut self, decorations: bool) -> Self {
203 self.decorations = decorations;
204 self
205 }
206
207 pub fn with_title(mut self, title: &'static str) -> Self {
209 self.title = title;
210 self
211 }
212
213 pub fn with_transparency(mut self, transparency: bool) -> Self {
215 self.transparent = transparency;
216 self
217 }
218
219 pub fn with_background(mut self, background: impl Into<Color>) -> Self {
221 self.background = background.into();
222 self
223 }
224
225 pub fn with_resizable(mut self, resizable: bool) -> Self {
227 self.resizable = resizable;
228 self
229 }
230
231 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 pub fn with_icon(mut self, icon: Icon) -> Self {
249 self.icon = Some(icon);
250 self
251 }
252
253 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 pub fn with_renderer(mut self, renderer: RendererPreference) -> Self {
261 self.renderer = renderer;
262 self
263 }
264
265 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
296pub enum GpuResourceCacheLimit {
297 Small,
299 #[default]
301 Normal,
302 Large,
304 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 pub const fn from_mb(megabytes: usize) -> Self {
317 Self::Custom(megabytes * 1024 * 1024)
318 }
319
320 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
343pub 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 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 pub fn with_window(mut self, window_config: WindowConfig) -> Self {
419 self.windows_configs.push(window_config);
420 self
421 }
422
423 #[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 pub fn with_plugin(mut self, plugin: impl FreyaPlugin + 'static) -> Self {
437 self.plugins.add_plugin(plugin);
438 self
439 }
440
441 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 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 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 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 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 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 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 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}