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            move || Platform {
205                focused_accessibility_id: State::create(ACCESSIBILITY_ROOT_ID),
206                focused_accessibility_node: State::create(accesskit::Node::new(
207                    accesskit::Role::Window,
208                )),
209                root_size: State::create(Size2D::new(
210                    window_size.width as f32,
211                    window_size.height as f32,
212                )),
213                navigation_mode: State::create(NavigationMode::NotKeyboard),
214                preferred_theme: State::create(theme),
215                accent_color: State::create(accent_color_preference.accent_color),
216                sender: Rc::new(move |user_event| {
217                    event_loop_proxy
218                        .send_event(NativeEvent::Window(NativeWindowEvent {
219                            window_id,
220                            action: NativeWindowEventAction::User(user_event),
221                        }))
222                        .unwrap();
223                }),
224            }
225        });
226
227        let clipboard = {
228            if let Ok(handle) = window.display_handle() {
229                #[allow(clippy::match_single_binding)]
230                match handle.as_raw() {
231                    #[cfg(target_os = "linux")]
232                    RawDisplayHandle::Wayland(handle) => {
233                        let (_primary, clipboard) = unsafe {
234                            use freya_clipboard::copypasta::wayland_clipboard;
235
236                            wayland_clipboard::create_clipboards_from_external(
237                                handle.display.as_ptr(),
238                            )
239                        };
240                        let clipboard: Box<dyn ClipboardProvider> = Box::new(clipboard);
241                        Some(clipboard)
242                    }
243                    _ => ClipboardContext::new().ok().map(|c| {
244                        let clipboard: Box<dyn ClipboardProvider> = Box::new(c);
245                        clipboard
246                    }),
247                }
248            } else {
249                None
250            }
251        };
252
253        runner.provide_root_context(|| State::create(clipboard));
254
255        runner.provide_root_context(|| tree.accessibility_generator.clone());
256
257        runner.provide_root_context(|| tree.accessibility_generator.clone());
258
259        runner.provide_root_context(|| font_collection.clone());
260
261        plugins.send(
262            PluginEvent::RunnerCreated {
263                runner: &mut runner,
264            },
265            PluginHandle::new(event_loop_proxy),
266        );
267
268        let mutations = runner.sync_and_update();
269        tree.apply_mutations(mutations);
270        tree.measure_layout(
271            (
272                window.inner_size().width as f32,
273                window.inner_size().height as f32,
274            )
275                .into(),
276            font_collection,
277            font_manager,
278            &events_sender,
279            window.scale_factor(),
280            fallback_fonts,
281        );
282
283        let nodes_state = NodesState::default();
284
285        let accessibility_adapter =
286            Adapter::with_event_loop_proxy(active_event_loop, &window, event_loop_proxy.clone());
287
288        window.set_visible(true);
289
290        struct TreeHandle(EventLoopProxy<NativeEvent>, WindowId);
291
292        impl ArcWake for TreeHandle {
293            fn wake_by_ref(arc_self: &Arc<Self>) {
294                _ = arc_self
295                    .0
296                    .send_event(NativeEvent::Window(NativeWindowEvent {
297                        window_id: arc_self.1,
298                        action: NativeWindowEventAction::PollRunner,
299                    }));
300            }
301        }
302
303        let waker = waker(Arc::new(TreeHandle(event_loop_proxy.clone(), window.id())));
304
305        #[cfg(feature = "hotreload")]
306        {
307            let event_loop_proxy = event_loop_proxy.clone();
308            let window_id = window.id();
309            let hot_reload_pending_handler = hot_reload_pending.clone();
310            freya_core::hotreload::subsecond::register_handler(Arc::new(move || {
311                hot_reload_pending_handler.store(true, std::sync::atomic::Ordering::Release);
312                let _ = event_loop_proxy.send_event(NativeEvent::Window(NativeWindowEvent {
313                    window_id,
314                    action: NativeWindowEventAction::PollRunner,
315                }));
316            }));
317        }
318
319        plugins.send(
320            PluginEvent::WindowCreated {
321                window: &window,
322                font_collection,
323                tree: &tree,
324                animation_clock: &animation_clock,
325                runner: &mut runner,
326                graphics_driver: driver.name(),
327            },
328            PluginHandle::new(event_loop_proxy),
329        );
330
331        AppWindow {
332            runner,
333            tree,
334            driver,
335            window,
336            nodes_state,
337
338            mouse_state: ElementState::Released,
339            position: CursorPoint::default(),
340            modifiers_state: ModifiersState::default(),
341
342            events_receiver,
343            events_sender,
344
345            accessibility: AccessibilityTree::default(),
346            accessibility_adapter,
347            accessibility_tasks_for_next_render: AccessibilityTask::ProcessUpdate { mode: None },
348
349            process_layout_on_next_render: true,
350
351            waker,
352
353            ticker_sender,
354
355            platform,
356
357            animation_clock,
358
359            background: window_config.background,
360
361            dropped_file_paths: Vec::new(),
362
363            on_close,
364
365            window_attributes,
366
367            user_zoom: 1.0,
368
369            #[cfg(feature = "hotreload")]
370            hot_reload_pending,
371        }
372    }
373
374    pub fn window(&self) -> &Window {
375        &self.window
376    }
377
378    pub fn window_mut(&mut self) -> &mut Window {
379        &mut self.window
380    }
381
382    pub fn effective_scale_factor(&self) -> f64 {
383        self.window.scale_factor() * self.user_zoom as f64
384    }
385
386    /// Sets `user_zoom`, clamped to `[MIN_USER_ZOOM, MAX_USER_ZOOM]`. On change,
387    /// resets layout/text caches and requests a redraw, mirroring `ScaleFactorChanged`.
388    pub fn set_user_zoom(&mut self, zoom: f32) {
389        let clamped = zoom.clamp(MIN_USER_ZOOM, MAX_USER_ZOOM);
390        if (clamped - self.user_zoom).abs() < f32::EPSILON {
391            return;
392        }
393        self.user_zoom = clamped;
394        self.process_layout_on_next_render = true;
395        self.tree.layout.reset();
396        self.tree.text_cache.reset();
397        self.window.request_redraw();
398    }
399
400    /// Returns `true` when the combo matched. Releases are also consumed so
401    /// press/release pairs stay symmetrical for upstream listeners.
402    #[cfg(feature = "zoom-shortcuts")]
403    pub fn try_handle_zoom_shortcut(
404        &mut self,
405        key: &keyboard_types::Key,
406        modifiers: keyboard_types::Modifiers,
407        is_pressed: bool,
408    ) -> bool {
409        use keyboard_types::{
410            Key,
411            Modifiers,
412        };
413        let zoom_modifier = if cfg!(target_os = "macos") {
414            Modifiers::META
415        } else {
416            Modifiers::CONTROL
417        };
418        if !modifiers.contains(zoom_modifier) {
419            return false;
420        }
421        let new_zoom = match key {
422            Key::Character(c) if c == "+" || c == "=" => self.user_zoom + ZOOM_STEP,
423            Key::Character(c) if c == "-" => self.user_zoom - ZOOM_STEP,
424            Key::Character(c) if c == "0" => 1.0,
425            _ => return false,
426        };
427        if is_pressed {
428            self.set_user_zoom(new_zoom);
429        }
430        true
431    }
432}
433
434fn accent_color_preference() -> mundy::Preferences {
435    use std::sync::OnceLock;
436    static PREFERENCE: OnceLock<mundy::Preferences> = OnceLock::new();
437    *PREFERENCE.get_or_init(|| {
438        mundy::Preferences::once_blocking(
439            mundy::Interest::AccentColor,
440            std::time::Duration::from_millis(200),
441        )
442        .unwrap_or_default()
443    })
444}