Skip to main content

freya_winit/
window.rs

1use std::{
2    borrow::Cow,
3    path::PathBuf,
4    rc::Rc,
5    sync::Arc,
6    task::Waker,
7};
8
9use accesskit_winit::Adapter;
10use freya_clipboard::copypasta::{
11    ClipboardContext,
12    ClipboardProvider,
13};
14use freya_components::{
15    cache::AssetCacher,
16    integration::integration,
17};
18use freya_core::{
19    integration::*,
20    prelude::Color,
21};
22use freya_engine::prelude::{
23    FontCollection,
24    FontMgr,
25};
26use futures_util::task::{
27    ArcWake,
28    waker,
29};
30use ragnarok::NodesState;
31use raw_window_handle::HasDisplayHandle;
32#[cfg(target_os = "linux")]
33use raw_window_handle::RawDisplayHandle;
34use torin::prelude::{
35    CursorPoint,
36    Size2D,
37};
38use winit::{
39    dpi::LogicalSize,
40    event::ElementState,
41    event_loop::{
42        ActiveEventLoop,
43        EventLoopProxy,
44    },
45    keyboard::ModifiersState,
46    window::{
47        Theme,
48        Window,
49        WindowAttributes,
50        WindowId,
51    },
52};
53
54use crate::{
55    accessibility::AccessibilityTask,
56    config::{
57        OnCloseHook,
58        WindowConfig,
59    },
60    drivers::GraphicsDriver,
61    plugins::{
62        PluginEvent,
63        PluginHandle,
64        PluginsManager,
65    },
66    renderer::{
67        NativeEvent,
68        NativeWindowEvent,
69        NativeWindowEventAction,
70    },
71};
72
73pub struct AppWindow {
74    pub(crate) runner: Runner,
75    pub(crate) tree: Tree,
76    pub(crate) driver: GraphicsDriver,
77    pub(crate) window: Window,
78    pub(crate) nodes_state: NodesState<NodeId>,
79
80    pub(crate) position: CursorPoint,
81    pub(crate) mouse_state: ElementState,
82    pub(crate) modifiers_state: ModifiersState,
83
84    pub(crate) events_receiver: futures_channel::mpsc::UnboundedReceiver<EventsChunk>,
85    pub(crate) events_sender: futures_channel::mpsc::UnboundedSender<EventsChunk>,
86
87    pub(crate) accessibility: AccessibilityTree,
88    pub(crate) accessibility_adapter: accesskit_winit::Adapter,
89    pub(crate) accessibility_tasks_for_next_render: AccessibilityTask,
90
91    pub(crate) process_layout_on_next_render: bool,
92
93    pub(crate) waker: Waker,
94
95    pub(crate) ticker_sender: RenderingTickerSender,
96
97    pub(crate) platform: Platform,
98
99    pub(crate) animation_clock: AnimationClock,
100
101    pub(crate) background: Color,
102
103    pub(crate) dropped_file_paths: Vec<PathBuf>,
104
105    pub(crate) on_close: Option<OnCloseHook>,
106
107    pub(crate) window_attributes: WindowAttributes,
108
109    pub(crate) user_zoom: f32,
110    #[cfg(feature = "hotreload")]
111    pub(crate) hot_reload_pending: Arc<std::sync::atomic::AtomicBool>,
112}
113
114pub(crate) const MIN_USER_ZOOM: f32 = 0.25;
115pub(crate) const MAX_USER_ZOOM: f32 = 5.0;
116
117#[cfg(feature = "zoom-shortcuts")]
118pub(crate) const ZOOM_STEP: f32 = 0.10;
119
120impl AppWindow {
121    #[allow(clippy::too_many_arguments)]
122    pub fn new(
123        mut window_config: WindowConfig,
124        active_event_loop: &ActiveEventLoop,
125        event_loop_proxy: &EventLoopProxy<NativeEvent>,
126        plugins: &mut PluginsManager,
127        font_collection: &mut FontCollection,
128        font_manager: &FontMgr,
129        fallback_fonts: &[Cow<'static, str>],
130        screen_reader: ScreenReader,
131        gpu_resource_cache_limit: usize,
132    ) -> Self {
133        #[cfg(feature = "hotreload")]
134        let hot_reload_pending = Arc::new(std::sync::atomic::AtomicBool::new(false));
135        let mut window_attributes = Window::default_attributes()
136            .with_resizable(window_config.resizable)
137            .with_window_icon(window_config.icon.take())
138            .with_visible(false)
139            .with_title(window_config.title)
140            .with_decorations(window_config.decorations)
141            .with_transparent(window_config.transparent)
142            .with_inner_size(LogicalSize::<f64>::from(window_config.size));
143
144        if let Some(min_size) = window_config.min_size {
145            window_attributes =
146                window_attributes.with_min_inner_size(LogicalSize::<f64>::from(min_size));
147        }
148        if let Some(max_size) = window_config.max_size {
149            window_attributes =
150                window_attributes.with_max_inner_size(LogicalSize::<f64>::from(max_size));
151        }
152        #[cfg(target_os = "linux")]
153        if let Some(app_id) = window_config.app_id.take() {
154            use winit::platform::wayland::WindowAttributesExtWayland;
155            window_attributes = window_attributes.with_name(&app_id, &app_id);
156        }
157        if let Some(window_attributes_hook) = window_config.window_attributes_hook.take() {
158            window_attributes = window_attributes_hook(window_attributes, active_event_loop);
159        }
160        let (driver, mut window) = GraphicsDriver::new(
161            active_event_loop,
162            window_attributes.clone(),
163            gpu_resource_cache_limit,
164        );
165
166        if let Some(window_handle_hook) = window_config.window_handle_hook.take() {
167            window_handle_hook(&mut window);
168        }
169
170        let on_close = window_config.on_close.take();
171
172        let (events_sender, events_receiver) = futures_channel::mpsc::unbounded();
173
174        let app = window_config.app.clone();
175        let mut runner = Runner::new({
176            let plugins = plugins.clone();
177            move || {
178                let el = integration(app.clone()).into_element();
179                plugins.wrap_root(el)
180            }
181        });
182
183        runner.provide_root_context(|| screen_reader);
184
185        let (mut ticker_sender, ticker) = RenderingTicker::new();
186        ticker_sender.set_overflow(true);
187        runner.provide_root_context(|| ticker);
188
189        let animation_clock = AnimationClock::new();
190        runner.provide_root_context(|| animation_clock.clone());
191
192        runner.provide_root_context(AssetCacher::create);
193        let mut tree = Tree::default();
194
195        let window_size = window.inner_size();
196        let accent_color_preference = accent_color_preference();
197        let platform = runner.provide_root_context({
198            let event_loop_proxy = event_loop_proxy.clone();
199            let window_id = window.id();
200            let theme = match window.theme() {
201                Some(Theme::Dark) => PreferredTheme::Dark,
202                _ => PreferredTheme::Light,
203            };
204            let is_app_focused = window.has_focus();
205            move || Platform {
206                focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
207                focused_accessibility_node: State::create(accesskit::Node::new(
208                    accesskit::Role::Window,
209                )),
210                root_size: State::create(Size2D::new(
211                    window_size.width as f32,
212                    window_size.height as f32,
213                )),
214                navigation_mode: State::create(NavigationMode::NotKeyboard),
215                preferred_theme: State::create(theme),
216                is_app_focused: State::create(is_app_focused),
217                accent_color: State::create(accent_color_preference.accent_color),
218                sender: Rc::new(move |user_event| {
219                    event_loop_proxy
220                        .send_event(NativeEvent::Window(NativeWindowEvent {
221                            window_id,
222                            action: NativeWindowEventAction::User(user_event),
223                        }))
224                        .unwrap();
225                }),
226            }
227        });
228
229        let clipboard = {
230            if let Ok(handle) = window.display_handle() {
231                #[allow(clippy::match_single_binding)]
232                match handle.as_raw() {
233                    #[cfg(target_os = "linux")]
234                    RawDisplayHandle::Wayland(handle) => {
235                        let (_primary, clipboard) = unsafe {
236                            use freya_clipboard::copypasta::wayland_clipboard;
237
238                            wayland_clipboard::create_clipboards_from_external(
239                                handle.display.as_ptr(),
240                            )
241                        };
242                        let clipboard: Box<dyn ClipboardProvider> = Box::new(clipboard);
243                        Some(clipboard)
244                    }
245                    _ => ClipboardContext::new().ok().map(|c| {
246                        let clipboard: Box<dyn ClipboardProvider> = Box::new(c);
247                        clipboard
248                    }),
249                }
250            } else {
251                None
252            }
253        };
254
255        runner.provide_root_context(|| State::create(clipboard));
256
257        runner.provide_root_context(|| tree.accessibility_generator.clone());
258
259        runner.provide_root_context(|| tree.accessibility_generator.clone());
260
261        runner.provide_root_context(|| font_collection.clone());
262
263        plugins.send(
264            PluginEvent::RunnerCreated {
265                runner: &mut runner,
266            },
267            PluginHandle::new(event_loop_proxy),
268        );
269
270        let mutations = runner.sync_and_update();
271        tree.apply_mutations(mutations);
272        tree.measure_layout(
273            (
274                window.inner_size().width as f32,
275                window.inner_size().height as f32,
276            )
277                .into(),
278            font_collection,
279            font_manager,
280            &events_sender,
281            window.scale_factor(),
282            fallback_fonts,
283        );
284
285        let nodes_state = NodesState::default();
286
287        let accessibility_adapter =
288            Adapter::with_event_loop_proxy(active_event_loop, &window, event_loop_proxy.clone());
289
290        window.set_visible(true);
291
292        struct TreeHandle(EventLoopProxy<NativeEvent>, WindowId);
293
294        impl ArcWake for TreeHandle {
295            fn wake_by_ref(arc_self: &Arc<Self>) {
296                _ = arc_self
297                    .0
298                    .send_event(NativeEvent::Window(NativeWindowEvent {
299                        window_id: arc_self.1,
300                        action: NativeWindowEventAction::PollRunner,
301                    }));
302            }
303        }
304
305        let waker = waker(Arc::new(TreeHandle(event_loop_proxy.clone(), window.id())));
306
307        #[cfg(feature = "hotreload")]
308        {
309            let event_loop_proxy = event_loop_proxy.clone();
310            let window_id = window.id();
311            let hot_reload_pending_handler = hot_reload_pending.clone();
312            freya_core::hotreload::subsecond::register_handler(Arc::new(move || {
313                hot_reload_pending_handler.store(true, std::sync::atomic::Ordering::Release);
314                let _ = event_loop_proxy.send_event(NativeEvent::Window(NativeWindowEvent {
315                    window_id,
316                    action: NativeWindowEventAction::PollRunner,
317                }));
318            }));
319        }
320
321        plugins.send(
322            PluginEvent::WindowCreated {
323                window: &window,
324                font_collection,
325                tree: &tree,
326                animation_clock: &animation_clock,
327                runner: &mut runner,
328                graphics_driver: driver.name(),
329            },
330            PluginHandle::new(event_loop_proxy),
331        );
332
333        AppWindow {
334            runner,
335            tree,
336            driver,
337            window,
338            nodes_state,
339
340            mouse_state: ElementState::Released,
341            position: CursorPoint::default(),
342            modifiers_state: ModifiersState::default(),
343
344            events_receiver,
345            events_sender,
346
347            accessibility: AccessibilityTree::default(),
348            accessibility_adapter,
349            accessibility_tasks_for_next_render: AccessibilityTask::ProcessUpdate { mode: None },
350
351            process_layout_on_next_render: true,
352
353            waker,
354
355            ticker_sender,
356
357            platform,
358
359            animation_clock,
360
361            background: window_config.background,
362
363            dropped_file_paths: Vec::new(),
364
365            on_close,
366
367            window_attributes,
368
369            user_zoom: 1.0,
370
371            #[cfg(feature = "hotreload")]
372            hot_reload_pending,
373        }
374    }
375
376    pub fn window(&self) -> &Window {
377        &self.window
378    }
379
380    pub fn window_mut(&mut self) -> &mut Window {
381        &mut self.window
382    }
383
384    pub fn effective_scale_factor(&self) -> f64 {
385        self.window.scale_factor() * self.user_zoom as f64
386    }
387
388    /// Sets `user_zoom`, clamped to `[MIN_USER_ZOOM, MAX_USER_ZOOM]`. On change,
389    /// resets layout/text caches and requests a redraw, mirroring `ScaleFactorChanged`.
390    pub fn set_user_zoom(&mut self, zoom: f32) {
391        let clamped = zoom.clamp(MIN_USER_ZOOM, MAX_USER_ZOOM);
392        if (clamped - self.user_zoom).abs() < f32::EPSILON {
393            return;
394        }
395        self.user_zoom = clamped;
396        self.process_layout_on_next_render = true;
397        self.tree.layout.reset();
398        self.tree.text_cache.reset();
399        self.window.request_redraw();
400    }
401
402    /// Returns `true` when the combo matched. Releases are also consumed so
403    /// press/release pairs stay symmetrical for upstream listeners.
404    #[cfg(feature = "zoom-shortcuts")]
405    pub fn try_handle_zoom_shortcut(
406        &mut self,
407        key: &keyboard_types::Key,
408        modifiers: keyboard_types::Modifiers,
409        is_pressed: bool,
410    ) -> bool {
411        use keyboard_types::Key;
412        if !modifiers.ctrl_or_meta() {
413            return false;
414        }
415        let new_zoom = match key {
416            Key::Character(c) if c == "+" || c == "=" => self.user_zoom + ZOOM_STEP,
417            Key::Character(c) if c == "-" => self.user_zoom - ZOOM_STEP,
418            Key::Character(c) if c == "0" => 1.0,
419            _ => return false,
420        };
421        if is_pressed {
422            self.set_user_zoom(new_zoom);
423        }
424        true
425    }
426}
427
428fn accent_color_preference() -> mundy::Preferences {
429    use std::sync::OnceLock;
430    static PREFERENCE: OnceLock<mundy::Preferences> = OnceLock::new();
431    *PREFERENCE.get_or_init(|| {
432        mundy::Preferences::once_blocking(
433            mundy::Interest::AccentColor,
434            std::time::Duration::from_millis(200),
435        )
436        .unwrap_or_default()
437    })
438}