Skip to main content

freya_winit/
lib.rs

1pub mod reexports {
2    pub use winit;
3}
4
5use std::sync::Arc;
6
7use crate::{
8    config::LaunchConfig,
9    renderer::{
10        LaunchProxy,
11        NativeEvent,
12        NativeGenericEvent,
13        WinitRenderer,
14    },
15};
16mod accessibility;
17pub mod config;
18mod drivers;
19pub mod extensions;
20pub mod integration;
21pub mod plugins;
22pub mod renderer;
23#[cfg(feature = "tray")]
24mod tray_icon;
25mod window;
26mod winit_mappings;
27
28pub use extensions::*;
29use futures_util::task::{
30    ArcWake,
31    waker,
32};
33
34use crate::winit::event_loop::EventLoopProxy;
35
36pub mod winit {
37    pub use winit::*;
38}
39
40#[cfg(feature = "tray")]
41pub mod tray {
42    pub use tray_icon::*;
43
44    pub use crate::tray_icon::*;
45}
46
47/// Launch the application.
48///
49/// If a custom event loop was provided via [`LaunchConfig::with_event_loop`], it will be used.
50/// Otherwise a default one is created.
51pub fn launch(mut launch_config: LaunchConfig) {
52    use std::collections::HashMap;
53
54    use freya_core::integration::*;
55    use freya_engine::prelude::{
56        FontCollection,
57        FontMgr,
58        TypefaceFontProvider,
59    };
60    use winit::event_loop::EventLoop;
61
62    #[cfg(all(not(debug_assertions), not(target_os = "android")))]
63    {
64        let previous_hook = std::panic::take_hook();
65        std::panic::set_hook(Box::new(move |panic_info| {
66            rfd::MessageDialog::new()
67                .set_title("Fatal Error")
68                .set_description(&panic_info.to_string())
69                .set_level(rfd::MessageLevel::Error)
70                .show();
71            previous_hook(panic_info);
72            std::process::exit(1);
73        }));
74    }
75
76    let event_loop = launch_config.event_loop.take().unwrap_or_else(|| {
77        EventLoop::<NativeEvent>::with_user_event()
78            .build()
79            .expect("Failed to create event loop.")
80    });
81
82    let proxy = event_loop.create_proxy();
83
84    let mut font_collection = FontCollection::new();
85    let def_mgr = FontMgr::default();
86    let mut provider = TypefaceFontProvider::new();
87    for (font_name, font_data) in launch_config.embedded_fonts {
88        let ft_type = def_mgr
89            .new_from_data(&font_data, None)
90            .unwrap_or_else(|| panic!("Failed to load font {font_name}."));
91        provider.register_typeface(ft_type, Some(font_name.as_ref()));
92    }
93    let font_mgr: FontMgr = provider.into();
94    font_collection.set_default_font_manager(def_mgr, None);
95    font_collection.set_dynamic_font_manager(font_mgr.clone());
96    font_collection.paragraph_cache_mut().turn_on(false);
97
98    let screen_reader = ScreenReader::new();
99
100    struct FuturesWaker(EventLoopProxy<NativeEvent>);
101
102    impl ArcWake for FuturesWaker {
103        fn wake_by_ref(arc_self: &Arc<Self>) {
104            _ = arc_self
105                .0
106                .send_event(NativeEvent::Generic(NativeGenericEvent::PollFutures));
107        }
108    }
109
110    let waker = waker(Arc::new(FuturesWaker(proxy.clone())));
111
112    let mut renderer = WinitRenderer {
113        windows: HashMap::default(),
114        #[cfg(feature = "tray")]
115        tray: launch_config.tray,
116        #[cfg(all(feature = "tray", not(target_os = "linux")))]
117        tray_icon: None,
118        resumed: false,
119        futures: launch_config
120            .tasks
121            .into_iter()
122            .map(|task| task(LaunchProxy(proxy.clone())))
123            .collect::<Vec<_>>(),
124        proxy,
125        font_manager: font_mgr,
126        font_collection,
127        windows_configs: launch_config.windows_configs,
128        plugins: launch_config.plugins,
129        fallback_fonts: launch_config.fallback_fonts,
130        screen_reader,
131        waker,
132        exit_on_close: launch_config.exit_on_close,
133    };
134
135    #[cfg(feature = "tray")]
136    {
137        use crate::{
138            renderer::{
139                NativeTrayEvent,
140                NativeTrayEventAction,
141            },
142            tray::{
143                TrayIconEvent,
144                menu::MenuEvent,
145            },
146        };
147
148        let proxy = renderer.proxy.clone();
149        MenuEvent::set_event_handler(Some(move |event| {
150            let _ = proxy.send_event(NativeEvent::Tray(NativeTrayEvent {
151                action: NativeTrayEventAction::MenuEvent(event),
152            }));
153        }));
154        let proxy = renderer.proxy.clone();
155        TrayIconEvent::set_event_handler(Some(move |event| {
156            let _ = proxy.send_event(NativeEvent::Tray(NativeTrayEvent {
157                action: NativeTrayEventAction::TrayEvent(event),
158            }));
159        }));
160
161        #[cfg(target_os = "linux")]
162        if let Some(tray_icon) = renderer.tray.0.take() {
163            std::thread::spawn(move || {
164                if !gtk::is_initialized() {
165                    if gtk::init().is_ok() {
166                        tracing::debug!("Tray: GTK initialized");
167                    } else {
168                        tracing::error!("Tray: Failed to initialize GTK");
169                    }
170                }
171
172                let _tray_icon = (tray_icon)();
173
174                gtk::main();
175            });
176        }
177    }
178
179    event_loop.run_app(&mut renderer).unwrap();
180}