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