Skip to main content

freya_winit/
renderer.rs

1use std::{
2    borrow::Cow,
3    fmt,
4    pin::Pin,
5    task::Waker,
6};
7
8use accesskit_winit::WindowEvent as AccessibilityWindowEvent;
9use freya_core::integration::*;
10use freya_engine::prelude::{
11    FontCollection,
12    FontMgr,
13};
14use futures_lite::future::FutureExt as _;
15use futures_util::{
16    FutureExt as _,
17    StreamExt,
18    select,
19};
20use ragnarok::{
21    EventsExecutorRunner,
22    EventsMeasurerRunner,
23};
24use rustc_hash::FxHashMap;
25use torin::prelude::{
26    CursorPoint,
27    Size2D,
28};
29#[cfg(all(feature = "tray", not(target_os = "linux")))]
30use tray_icon::TrayIcon;
31use winit::{
32    application::ApplicationHandler,
33    dpi::{
34        LogicalPosition,
35        LogicalSize,
36    },
37    event::{
38        ElementState,
39        Ime,
40        MouseScrollDelta,
41        Touch,
42        TouchPhase,
43        WindowEvent,
44    },
45    event_loop::{
46        ActiveEventLoop,
47        EventLoopProxy,
48    },
49    window::{
50        Theme,
51        WindowId,
52    },
53};
54
55use crate::{
56    accessibility::AccessibilityTask,
57    config::{
58        CloseDecision,
59        WindowConfig,
60    },
61    drivers::GraphicsDriver,
62    integration::is_ime_role,
63    plugins::{
64        PluginEvent,
65        PluginHandle,
66        PluginsManager,
67    },
68    window::AppWindow,
69    winit_mappings::{
70        self,
71        map_winit_mouse_button,
72        map_winit_touch_force,
73        map_winit_touch_phase,
74    },
75};
76
77pub struct WinitRenderer {
78    pub windows_configs: Vec<WindowConfig>,
79    #[cfg(feature = "tray")]
80    pub(crate) tray: (
81        Option<crate::config::TrayIconGetter>,
82        Option<crate::config::TrayHandler>,
83    ),
84    #[cfg(all(feature = "tray", not(target_os = "linux")))]
85    pub(crate) tray_icon: Option<TrayIcon>,
86    pub resumed: bool,
87    pub windows: FxHashMap<WindowId, AppWindow>,
88    pub proxy: EventLoopProxy<NativeEvent>,
89    pub plugins: PluginsManager,
90    pub fallback_fonts: Vec<Cow<'static, str>>,
91    pub screen_reader: ScreenReader,
92    pub font_manager: FontMgr,
93    pub font_collection: FontCollection,
94    pub futures: Vec<Pin<Box<dyn std::future::Future<Output = ()>>>>,
95    pub waker: Waker,
96    pub exit_on_close: bool,
97    pub gpu_resource_cache_limit: usize,
98}
99
100pub struct RendererContext<'a> {
101    pub windows: &'a mut FxHashMap<WindowId, AppWindow>,
102    pub proxy: &'a mut EventLoopProxy<NativeEvent>,
103    pub plugins: &'a mut PluginsManager,
104    pub fallback_fonts: &'a mut Vec<Cow<'static, str>>,
105    pub screen_reader: &'a mut ScreenReader,
106    pub font_manager: &'a mut FontMgr,
107    pub font_collection: &'a mut FontCollection,
108    pub active_event_loop: &'a ActiveEventLoop,
109    pub gpu_resource_cache_limit: usize,
110}
111
112impl RendererContext<'_> {
113    pub fn launch_window(&mut self, window_config: WindowConfig) -> WindowId {
114        let app_window = AppWindow::new(
115            window_config,
116            self.active_event_loop,
117            self.proxy,
118            self.plugins,
119            self.font_collection,
120            self.font_manager,
121            self.fallback_fonts,
122            self.screen_reader.clone(),
123            self.gpu_resource_cache_limit,
124        );
125
126        let window_id = app_window.window.id();
127
128        self.proxy
129            .send_event(NativeEvent::Window(NativeWindowEvent {
130                window_id,
131                action: NativeWindowEventAction::PollRunner,
132            }))
133            .ok();
134
135        self.windows.insert(window_id, app_window);
136
137        window_id
138    }
139
140    pub fn windows(&self) -> &FxHashMap<WindowId, AppWindow> {
141        self.windows
142    }
143
144    pub fn windows_mut(&mut self) -> &mut FxHashMap<WindowId, AppWindow> {
145        self.windows
146    }
147
148    pub fn exit(&mut self) {
149        self.active_event_loop.exit();
150    }
151}
152
153#[derive(Debug)]
154pub enum NativeWindowEventAction {
155    PollRunner,
156
157    Accessibility(AccessibilityWindowEvent),
158
159    PlatformEvent(PlatformEvent),
160
161    User(UserEvent),
162}
163
164/// Proxy wrapper provided to launch tasks so they can post callbacks executed inside the renderer.
165#[derive(Clone)]
166pub struct LaunchProxy(pub EventLoopProxy<NativeEvent>);
167
168impl LaunchProxy {
169    /// Queue a callback to be run on the renderer thread with access to a [`RendererContext`].
170    ///
171    /// The call dispatches an event to the winit event loop and returns right away; the
172    /// callback runs later, when the event loop picks it up. Its return value is delivered
173    /// through the returned oneshot [`Receiver`](futures_channel::oneshot::Receiver), which
174    /// can be `.await`ed or dropped.
175    ///
176    /// The callback runs outside any component scope, so you can't call `Platform::get` or
177    /// consume context from inside it; use the [`RendererContext`] argument instead.
178    pub fn post_callback<F, T: 'static>(&self, f: F) -> futures_channel::oneshot::Receiver<T>
179    where
180        F: FnOnce(&mut RendererContext) -> T + 'static,
181    {
182        let (tx, rx) = futures_channel::oneshot::channel::<T>();
183        let cb = Box::new(move |ctx: &mut RendererContext| {
184            let res = (f)(ctx);
185            let _ = tx.send(res);
186        });
187        let _ = self
188            .0
189            .send_event(NativeEvent::Generic(NativeGenericEvent::RendererCallback(
190                cb,
191            )));
192        rx
193    }
194}
195
196pub type RendererCallback = Box<dyn FnOnce(WindowId, &mut RendererContext) + 'static>;
197
198pub enum NativeWindowErasedEventAction {
199    LaunchWindow {
200        window_config: WindowConfig,
201        ack: futures_channel::oneshot::Sender<WindowId>,
202    },
203    CloseWindow(WindowId),
204    RendererCallback(RendererCallback),
205}
206
207#[derive(Debug)]
208pub struct NativeWindowEvent {
209    pub window_id: WindowId,
210    pub action: NativeWindowEventAction,
211}
212
213#[cfg(feature = "tray")]
214#[derive(Debug)]
215pub enum NativeTrayEventAction {
216    TrayEvent(tray_icon::TrayIconEvent),
217    MenuEvent(tray_icon::menu::MenuEvent),
218    LaunchWindow(SingleThreadErasedEvent),
219}
220
221#[cfg(feature = "tray")]
222#[derive(Debug)]
223pub struct NativeTrayEvent {
224    pub action: NativeTrayEventAction,
225}
226
227pub enum NativeGenericEvent {
228    PollFutures,
229    RendererCallback(Box<dyn FnOnce(&mut RendererContext) + 'static>),
230}
231
232impl fmt::Debug for NativeGenericEvent {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        match self {
235            NativeGenericEvent::PollFutures => f.write_str("PollFutures"),
236            NativeGenericEvent::RendererCallback(_) => f.write_str("RendererCallback"),
237        }
238    }
239}
240
241/// # Safety
242/// The values are never sent, received or accessed by other threads other than the main thread.
243/// This is needed to send `Rc<T>` and other non-Send and non-Sync values.
244unsafe impl Send for NativeGenericEvent {}
245unsafe impl Sync for NativeGenericEvent {}
246
247#[derive(Debug)]
248pub enum NativeEvent {
249    Window(NativeWindowEvent),
250    #[cfg(feature = "tray")]
251    Tray(NativeTrayEvent),
252    Generic(NativeGenericEvent),
253    Preferences(mundy::Preferences),
254}
255
256impl From<accesskit_winit::Event> for NativeEvent {
257    fn from(event: accesskit_winit::Event) -> Self {
258        NativeEvent::Window(NativeWindowEvent {
259            window_id: event.window_id,
260            action: NativeWindowEventAction::Accessibility(event.window_event),
261        })
262    }
263}
264
265impl ApplicationHandler<NativeEvent> for WinitRenderer {
266    fn resumed(&mut self, active_event_loop: &winit::event_loop::ActiveEventLoop) {
267        if !self.resumed {
268            #[cfg(feature = "tray")]
269            {
270                #[cfg(not(target_os = "linux"))]
271                if let Some(tray_icon) = self.tray.0.take() {
272                    self.tray_icon = Some((tray_icon)());
273                }
274
275                #[cfg(target_os = "macos")]
276                {
277                    use objc2_core_foundation::CFRunLoop;
278
279                    let rl = CFRunLoop::main().expect("Failed to run CFRunLoop");
280                    CFRunLoop::wake_up(&rl);
281                }
282            }
283
284            for window_config in self.windows_configs.drain(..) {
285                let app_window = AppWindow::new(
286                    window_config,
287                    active_event_loop,
288                    &self.proxy,
289                    &mut self.plugins,
290                    &mut self.font_collection,
291                    &self.font_manager,
292                    &self.fallback_fonts,
293                    self.screen_reader.clone(),
294                    self.gpu_resource_cache_limit,
295                );
296
297                self.proxy
298                    .send_event(NativeEvent::Window(NativeWindowEvent {
299                        window_id: app_window.window.id(),
300                        action: NativeWindowEventAction::PollRunner,
301                    }))
302                    .ok();
303
304                self.windows.insert(app_window.window.id(), app_window);
305            }
306            self.resumed = true;
307
308            subscribe_preferences(self.proxy.clone());
309
310            let _ = self
311                .proxy
312                .send_event(NativeEvent::Generic(NativeGenericEvent::PollFutures));
313        } else {
314            // [Android] Recreate the GraphicsDriver when the app gets brought into the foreground after being suspended,
315            // so we don't end up with a completely black surface with broken rendering.
316            let old_windows: Vec<_> = self.windows.drain().collect();
317            for (_, mut app_window) in old_windows {
318                let (new_driver, new_window) = GraphicsDriver::new(
319                    active_event_loop,
320                    app_window.window_attributes.clone(),
321                    self.gpu_resource_cache_limit,
322                );
323
324                let new_id = new_window.id();
325                app_window.driver = new_driver;
326                app_window.window = new_window;
327                app_window.process_layout_on_next_render = true;
328                app_window.tree.layout.reset();
329
330                self.windows.insert(new_id, app_window);
331
332                self.proxy
333                    .send_event(NativeEvent::Window(NativeWindowEvent {
334                        window_id: new_id,
335                        action: NativeWindowEventAction::PollRunner,
336                    }))
337                    .ok();
338            }
339        }
340    }
341
342    fn user_event(
343        &mut self,
344        active_event_loop: &winit::event_loop::ActiveEventLoop,
345        event: NativeEvent,
346    ) {
347        match event {
348            NativeEvent::Generic(NativeGenericEvent::RendererCallback(cb)) => {
349                let mut renderer_context = RendererContext {
350                    fallback_fonts: &mut self.fallback_fonts,
351                    active_event_loop,
352                    windows: &mut self.windows,
353                    proxy: &mut self.proxy,
354                    plugins: &mut self.plugins,
355                    screen_reader: &mut self.screen_reader,
356                    font_manager: &mut self.font_manager,
357                    font_collection: &mut self.font_collection,
358                    gpu_resource_cache_limit: self.gpu_resource_cache_limit,
359                };
360                (cb)(&mut renderer_context);
361            }
362            NativeEvent::Generic(NativeGenericEvent::PollFutures) => {
363                let mut cx = std::task::Context::from_waker(&self.waker);
364                self.futures
365                    .retain_mut(|fut| fut.poll(&mut cx).is_pending());
366            }
367            NativeEvent::Preferences(prefs) => {
368                for app in self.windows.values_mut() {
369                    app.platform
370                        .accent_color
371                        .set_if_modified(prefs.accent_color);
372                }
373            }
374            #[cfg(feature = "tray")]
375            NativeEvent::Tray(NativeTrayEvent { action }) => {
376                let renderer_context = RendererContext {
377                    fallback_fonts: &mut self.fallback_fonts,
378                    active_event_loop,
379                    windows: &mut self.windows,
380                    proxy: &mut self.proxy,
381                    plugins: &mut self.plugins,
382                    screen_reader: &mut self.screen_reader,
383                    font_manager: &mut self.font_manager,
384                    font_collection: &mut self.font_collection,
385                    gpu_resource_cache_limit: self.gpu_resource_cache_limit,
386                };
387                match action {
388                    NativeTrayEventAction::TrayEvent(icon_event) => {
389                        use crate::tray::TrayEvent;
390                        if let Some(tray_handler) = &mut self.tray.1 {
391                            (tray_handler)(TrayEvent::Icon(icon_event), renderer_context)
392                        }
393                    }
394                    NativeTrayEventAction::MenuEvent(menu_event) => {
395                        use crate::tray::TrayEvent;
396                        if let Some(tray_handler) = &mut self.tray.1 {
397                            (tray_handler)(TrayEvent::Menu(menu_event), renderer_context)
398                        }
399                    }
400                    NativeTrayEventAction::LaunchWindow(data) => {
401                        let window_config = data
402                            .0
403                            .downcast::<WindowConfig>()
404                            .expect("Expected WindowConfig");
405                        let app_window = AppWindow::new(
406                            *window_config,
407                            active_event_loop,
408                            &self.proxy,
409                            &mut self.plugins,
410                            &mut self.font_collection,
411                            &self.font_manager,
412                            &self.fallback_fonts,
413                            self.screen_reader.clone(),
414                            self.gpu_resource_cache_limit,
415                        );
416
417                        self.proxy
418                            .send_event(NativeEvent::Window(NativeWindowEvent {
419                                window_id: app_window.window.id(),
420                                action: NativeWindowEventAction::PollRunner,
421                            }))
422                            .ok();
423
424                        self.windows.insert(app_window.window.id(), app_window);
425                    }
426                }
427            }
428            NativeEvent::Window(NativeWindowEvent { action, window_id }) => {
429                if let Some(app) = &mut self.windows.get_mut(&window_id) {
430                    match action {
431                        NativeWindowEventAction::PollRunner => {
432                            let mut cx = std::task::Context::from_waker(&app.waker);
433
434                            #[cfg(feature = "hotreload")]
435                            let hotreload_triggered = app
436                                .hot_reload_pending
437                                .swap(false, std::sync::atomic::Ordering::AcqRel);
438
439                            #[cfg(feature = "hotreload")]
440                            if hotreload_triggered {
441                                app.runner.reload();
442                            }
443
444                            {
445                                let fut = std::pin::pin!(async {
446                                    select! {
447                                        events_chunk = app.events_receiver.next() => {
448                                            match events_chunk {
449                                                Some(EventsChunk::Processed(processed_events)) => {
450                                                    let events_executor_adapter = EventsExecutorAdapter {
451                                                        runner: &mut app.runner,
452                                                    };
453                                                    events_executor_adapter.run(&mut app.nodes_state, processed_events);
454                                                }
455                                                Some(EventsChunk::Batch(events)) => {
456                                                    for event in events {
457                                                        app.runner.handle_event(event.node_id, event.name, event.data, event.bubbles);
458                                                    }
459                                                }
460                                                _ => {}
461                                            }
462                                        },
463                                        _ = app.runner.handle_events().fuse() => {},
464                                    }
465                                });
466
467                                match fut.poll(&mut cx) {
468                                    std::task::Poll::Ready(_) => {
469                                        self.proxy
470                                            .send_event(NativeEvent::Window(NativeWindowEvent {
471                                                window_id: app.window.id(),
472                                                action: NativeWindowEventAction::PollRunner,
473                                            }))
474                                            .ok();
475                                    }
476                                    std::task::Poll::Pending => {}
477                                }
478                            }
479
480                            self.plugins.send(
481                                PluginEvent::StartedUpdatingTree {
482                                    window: &app.window,
483                                    tree: &app.tree,
484                                },
485                                PluginHandle::new(&self.proxy),
486                            );
487                            let mutations = app.runner.sync_and_update();
488                            let result = app.runner.run_in(|| app.tree.apply_mutations(mutations));
489                            if result.needs_render {
490                                app.process_layout_on_next_render = true;
491                                app.window.request_redraw();
492                            }
493                            #[cfg(feature = "hotreload")]
494                            if hotreload_triggered {
495                                // Hot-patches can change closure bodies and custom `ElementExt` impls
496                                // that `PartialEq` can't observe, so force a layout + redraw.
497                                app.process_layout_on_next_render = true;
498                                app.window.request_redraw();
499                            }
500                            if result.needs_accessibility {
501                                app.accessibility_tasks_for_next_render |=
502                                    AccessibilityTask::ProcessUpdate { mode: None };
503                                app.window.request_redraw();
504                            }
505                            self.plugins.send(
506                                PluginEvent::FinishedUpdatingTree {
507                                    window: &app.window,
508                                    tree: &app.tree,
509                                },
510                                PluginHandle::new(&self.proxy),
511                            );
512                            #[cfg(debug_assertions)]
513                            {
514                                tracing::info!("Updated app tree.");
515                                tracing::info!("{:#?}", app.tree);
516                                tracing::info!("{:#?}", app.runner);
517                            }
518                        }
519                        NativeWindowEventAction::Accessibility(
520                            accesskit_winit::WindowEvent::AccessibilityDeactivated,
521                        ) => {
522                            self.screen_reader.set(false);
523                        }
524                        NativeWindowEventAction::Accessibility(
525                            accesskit_winit::WindowEvent::ActionRequested(_),
526                        ) => {}
527                        NativeWindowEventAction::Accessibility(
528                            accesskit_winit::WindowEvent::InitialTreeRequested,
529                        ) => {
530                            app.accessibility_tasks_for_next_render = AccessibilityTask::Init;
531                            app.window.request_redraw();
532                            self.screen_reader.set(true);
533                        }
534                        NativeWindowEventAction::User(user_event) => match user_event {
535                            UserEvent::RequestRedraw => {
536                                app.window.request_redraw();
537                            }
538                            UserEvent::FocusAccessibilityNode(strategy) => {
539                                let task = match strategy {
540                                    AccessibilityFocusStrategy::Backward(_)
541                                    | AccessibilityFocusStrategy::Forward(_) => {
542                                        AccessibilityTask::ProcessUpdate {
543                                            mode: Some(NavigationMode::Keyboard),
544                                        }
545                                    }
546                                    _ => AccessibilityTask::ProcessUpdate { mode: None },
547                                };
548                                app.tree.accessibility_diff.request_focus(strategy);
549                                app.accessibility_tasks_for_next_render = task;
550                                app.window.request_redraw();
551                            }
552                            UserEvent::SetCursorIcon(cursor_icon) => {
553                                app.window.set_cursor(cursor_icon);
554                            }
555                            UserEvent::Erased(data) => {
556                                let action = data
557                                    .0
558                                    .downcast::<NativeWindowErasedEventAction>()
559                                    .expect("Expected NativeWindowErasedEventAction");
560                                match *action {
561                                    NativeWindowErasedEventAction::LaunchWindow {
562                                        window_config,
563                                        ack,
564                                    } => {
565                                        let app_window = AppWindow::new(
566                                            window_config,
567                                            active_event_loop,
568                                            &self.proxy,
569                                            &mut self.plugins,
570                                            &mut self.font_collection,
571                                            &self.font_manager,
572                                            &self.fallback_fonts,
573                                            self.screen_reader.clone(),
574                                            self.gpu_resource_cache_limit,
575                                        );
576
577                                        let window_id = app_window.window.id();
578
579                                        let _ = self.proxy.send_event(NativeEvent::Window(
580                                            NativeWindowEvent {
581                                                window_id,
582                                                action: NativeWindowEventAction::PollRunner,
583                                            },
584                                        ));
585
586                                        self.windows.insert(window_id, app_window);
587                                        let _ = ack.send(window_id);
588                                    }
589                                    NativeWindowErasedEventAction::CloseWindow(window_id) => {
590                                        // Its fine to ignore if the window doesnt exist anymore
591                                        let _ = self.windows.remove(&window_id);
592                                        let has_windows = !self.windows.is_empty();
593
594                                        let has_tray = {
595                                            #[cfg(feature = "tray")]
596                                            {
597                                                self.tray.1.is_some()
598                                            }
599                                            #[cfg(not(feature = "tray"))]
600                                            {
601                                                false
602                                            }
603                                        };
604
605                                        // Only exit when there is no window and no tray
606                                        if !has_windows && !has_tray && self.exit_on_close {
607                                            active_event_loop.exit();
608                                        }
609                                    }
610                                    NativeWindowErasedEventAction::RendererCallback(cb) => {
611                                        let window_id = app.window.id();
612                                        let mut renderer_context = RendererContext {
613                                            fallback_fonts: &mut self.fallback_fonts,
614                                            active_event_loop,
615                                            windows: &mut self.windows,
616                                            proxy: &mut self.proxy,
617                                            plugins: &mut self.plugins,
618                                            screen_reader: &mut self.screen_reader,
619                                            font_manager: &mut self.font_manager,
620                                            font_collection: &mut self.font_collection,
621                                            gpu_resource_cache_limit: self.gpu_resource_cache_limit,
622                                        };
623                                        (cb)(window_id, &mut renderer_context);
624                                    }
625                                }
626                            }
627                        },
628                        NativeWindowEventAction::PlatformEvent(platform_event) => {
629                            let mut events_measurer_adapter = EventsMeasurerAdapter {
630                                scale_factor: app.effective_scale_factor(),
631                                tree: &mut app.tree,
632                            };
633                            let processed_events = events_measurer_adapter.run(
634                                &mut vec![platform_event],
635                                &mut app.nodes_state,
636                                app.accessibility.focused_node_id(),
637                            );
638                            app.events_sender
639                                .unbounded_send(EventsChunk::Processed(processed_events))
640                                .unwrap();
641                        }
642                    }
643                }
644            }
645        }
646    }
647
648    fn window_event(
649        &mut self,
650        event_loop: &winit::event_loop::ActiveEventLoop,
651        window_id: winit::window::WindowId,
652        event: winit::event::WindowEvent,
653    ) {
654        if let Some(app) = &mut self.windows.get_mut(&window_id) {
655            app.accessibility_adapter.process_event(&app.window, &event);
656            match event {
657                WindowEvent::ThemeChanged(theme) => {
658                    app.platform.preferred_theme.set(match theme {
659                        Theme::Light => PreferredTheme::Light,
660                        Theme::Dark => PreferredTheme::Dark,
661                    });
662                }
663                WindowEvent::ScaleFactorChanged { .. } => {
664                    app.window.request_redraw();
665                    app.process_layout_on_next_render = true;
666                    app.tree.layout.reset();
667                    app.tree.text_cache.reset();
668                }
669                WindowEvent::CloseRequested => {
670                    let mut on_close_hook = self
671                        .windows
672                        .get_mut(&window_id)
673                        .and_then(|app| app.on_close.take());
674
675                    let decision = if let Some(ref mut on_close) = on_close_hook {
676                        let renderer_context = RendererContext {
677                            fallback_fonts: &mut self.fallback_fonts,
678                            active_event_loop: event_loop,
679                            windows: &mut self.windows,
680                            proxy: &mut self.proxy,
681                            plugins: &mut self.plugins,
682                            screen_reader: &mut self.screen_reader,
683                            font_manager: &mut self.font_manager,
684                            font_collection: &mut self.font_collection,
685                            gpu_resource_cache_limit: self.gpu_resource_cache_limit,
686                        };
687                        on_close(renderer_context, window_id)
688                    } else {
689                        CloseDecision::Close
690                    };
691
692                    if matches!(decision, CloseDecision::KeepOpen)
693                        && let Some(app) = self.windows.get_mut(&window_id)
694                    {
695                        app.on_close = on_close_hook;
696                    }
697
698                    if matches!(decision, CloseDecision::Close) {
699                        self.windows.remove(&window_id);
700                        let has_windows = !self.windows.is_empty();
701
702                        let has_tray = {
703                            #[cfg(feature = "tray")]
704                            {
705                                self.tray.1.is_some()
706                            }
707                            #[cfg(not(feature = "tray"))]
708                            {
709                                false
710                            }
711                        };
712
713                        // Only exit when there is no windows and no tray
714                        if !has_windows && !has_tray && self.exit_on_close {
715                            event_loop.exit();
716                        }
717                    }
718                }
719                WindowEvent::ModifiersChanged(modifiers) => {
720                    app.modifiers_state = modifiers.state();
721                }
722                WindowEvent::Focused(is_focused) => {
723                    app.platform.is_app_focused.set_if_modified(is_focused);
724                }
725                WindowEvent::RedrawRequested => {
726                    let scale_factor = app.effective_scale_factor();
727                    hotpath::measure_block!("RedrawRequested", {
728                        if app.process_layout_on_next_render {
729                            self.plugins.send(
730                                PluginEvent::StartedMeasuringLayout {
731                                    window: &app.window,
732                                    tree: &app.tree,
733                                },
734                                PluginHandle::new(&self.proxy),
735                            );
736                            let size: Size2D = (
737                                app.window.inner_size().width as f32,
738                                app.window.inner_size().height as f32,
739                            )
740                                .into();
741
742                            app.tree.measure_layout(
743                                size,
744                                &mut self.font_collection,
745                                &self.font_manager,
746                                &app.events_sender,
747                                scale_factor,
748                                &self.fallback_fonts,
749                            );
750                            app.platform.root_size.set_if_modified(size);
751                            app.process_layout_on_next_render = false;
752                            self.plugins.send(
753                                PluginEvent::FinishedMeasuringLayout {
754                                    window: &app.window,
755                                    tree: &app.tree,
756                                },
757                                PluginHandle::new(&self.proxy),
758                            );
759                        }
760
761                        app.driver.present(
762                            app.window.inner_size().cast(),
763                            &app.window,
764                            |surface| {
765                                self.plugins.send(
766                                    PluginEvent::BeforeRender {
767                                        window: &app.window,
768                                        canvas: surface.canvas(),
769                                        font_collection: &self.font_collection,
770                                        tree: &app.tree,
771                                    },
772                                    PluginHandle::new(&self.proxy),
773                                );
774
775                                let render_pipeline = RenderPipeline {
776                                    font_collection: &mut self.font_collection,
777                                    font_manager: &self.font_manager,
778                                    tree: &app.tree,
779                                    canvas: surface.canvas(),
780                                    scale_factor,
781                                    background: app.background,
782                                };
783
784                                render_pipeline.render();
785
786                                self.plugins.send(
787                                    PluginEvent::AfterRender {
788                                        window: &app.window,
789                                        canvas: surface.canvas(),
790                                        font_collection: &self.font_collection,
791                                        tree: &app.tree,
792                                        animation_clock: &app.animation_clock,
793                                    },
794                                    PluginHandle::new(&self.proxy),
795                                );
796                                self.plugins.send(
797                                    PluginEvent::BeforePresenting {
798                                        window: &app.window,
799                                        font_collection: &self.font_collection,
800                                        tree: &app.tree,
801                                    },
802                                    PluginHandle::new(&self.proxy),
803                                );
804                            },
805                        );
806                        self.plugins.send(
807                            PluginEvent::AfterPresenting {
808                                window: &app.window,
809                                font_collection: &self.font_collection,
810                                tree: &app.tree,
811                            },
812                            PluginHandle::new(&self.proxy),
813                        );
814
815                        self.plugins.send(
816                            PluginEvent::BeforeAccessibility {
817                                window: &app.window,
818                                font_collection: &self.font_collection,
819                                tree: &app.tree,
820                            },
821                            PluginHandle::new(&self.proxy),
822                        );
823
824                        match app.accessibility_tasks_for_next_render.take() {
825                            AccessibilityTask::ProcessUpdate { mode } => {
826                                let update = app
827                                    .accessibility
828                                    .process_updates(&mut app.tree, &app.events_sender);
829                                app.platform
830                                    .focused_accessibility_id
831                                    .set_if_modified(update.focus);
832                                let node_id = app.accessibility.focused_node_id().unwrap();
833                                let layout_node = app.tree.layout.get(&node_id).unwrap();
834                                let focused_node =
835                                    AccessibilityTree::create_node(node_id, layout_node, &app.tree);
836                                app.window.set_ime_allowed(is_ime_role(focused_node.role()));
837                                app.platform
838                                    .focused_accessibility_node
839                                    .set_if_modified(focused_node);
840                                if let Some(mode) = mode {
841                                    app.platform.navigation_mode.set(mode);
842                                }
843
844                                let area = layout_node.visible_area();
845                                app.window.set_ime_cursor_area(
846                                    LogicalPosition::new(area.min_x(), area.min_y()),
847                                    LogicalSize::new(area.width(), area.height()),
848                                );
849
850                                app.accessibility_adapter.update_if_active(|| update);
851                            }
852                            AccessibilityTask::Init => {
853                                let update = app.accessibility.init(&mut app.tree);
854                                app.platform
855                                    .focused_accessibility_id
856                                    .set_if_modified(update.focus);
857                                let node_id = app.accessibility.focused_node_id().unwrap();
858                                let layout_node = app.tree.layout.get(&node_id).unwrap();
859                                let focused_node =
860                                    AccessibilityTree::create_node(node_id, layout_node, &app.tree);
861                                app.window.set_ime_allowed(is_ime_role(focused_node.role()));
862                                app.platform
863                                    .focused_accessibility_node
864                                    .set_if_modified(focused_node);
865
866                                let area = layout_node.visible_area();
867                                app.window.set_ime_cursor_area(
868                                    LogicalPosition::new(area.min_x(), area.min_y()),
869                                    LogicalSize::new(area.width(), area.height()),
870                                );
871
872                                app.accessibility_adapter.update_if_active(|| update);
873                            }
874                            AccessibilityTask::None => {}
875                        }
876
877                        self.plugins.send(
878                            PluginEvent::AfterAccessibility {
879                                window: &app.window,
880                                font_collection: &self.font_collection,
881                                tree: &app.tree,
882                            },
883                            PluginHandle::new(&self.proxy),
884                        );
885
886                        if app.ticker_sender.receiver_count() > 0 {
887                            app.ticker_sender.broadcast_blocking(()).unwrap();
888                        }
889
890                        self.plugins.send(
891                            PluginEvent::AfterRedraw {
892                                window: &app.window,
893                                font_collection: &self.font_collection,
894                                tree: &app.tree,
895                            },
896                            PluginHandle::new(&self.proxy),
897                        );
898                    });
899                }
900                WindowEvent::Resized(size) => {
901                    app.driver.resize(size);
902
903                    app.window.request_redraw();
904
905                    app.process_layout_on_next_render = true;
906                    app.tree.layout.clear_dirty();
907                    app.tree.layout.invalidate(NodeId::ROOT);
908                }
909
910                WindowEvent::MouseInput { state, button, .. } => {
911                    app.mouse_state = state;
912                    app.platform
913                        .navigation_mode
914                        .set(NavigationMode::NotKeyboard);
915
916                    let name = if state == ElementState::Pressed {
917                        MouseEventName::MouseDown
918                    } else {
919                        MouseEventName::MouseUp
920                    };
921                    let platform_event = PlatformEvent::Mouse {
922                        name,
923                        cursor: (app.position.x, app.position.y).into(),
924                        button: Some(map_winit_mouse_button(button)),
925                    };
926                    let mut events_measurer_adapter = EventsMeasurerAdapter {
927                        scale_factor: app.effective_scale_factor(),
928                        tree: &mut app.tree,
929                    };
930                    let processed_events = events_measurer_adapter.run(
931                        &mut vec![platform_event],
932                        &mut app.nodes_state,
933                        app.accessibility.focused_node_id(),
934                    );
935                    app.events_sender
936                        .unbounded_send(EventsChunk::Processed(processed_events))
937                        .unwrap();
938                }
939
940                WindowEvent::KeyboardInput {
941                    event,
942                    is_synthetic,
943                    ..
944                } => {
945                    // Ignore synthetic presses (e.g. Tab on alt-tab) but keep synthetic releases so keys don't get stuck.
946                    if is_synthetic && event.state == ElementState::Pressed {
947                        return;
948                    }
949
950                    let name = match event.state {
951                        ElementState::Pressed => KeyboardEventName::KeyDown,
952                        ElementState::Released => KeyboardEventName::KeyUp,
953                    };
954                    let key = winit_mappings::map_winit_key(&event.logical_key);
955                    let code = winit_mappings::map_winit_physical_key(&event.physical_key);
956                    let modifiers = winit_mappings::map_winit_modifiers(app.modifiers_state);
957
958                    #[cfg(feature = "zoom-shortcuts")]
959                    if app.try_handle_zoom_shortcut(&key, modifiers, event.state.is_pressed()) {
960                        return;
961                    }
962
963                    self.plugins.send(
964                        PluginEvent::KeyboardInput {
965                            window: &app.window,
966                            key: key.clone(),
967                            code,
968                            modifiers,
969                            is_pressed: event.state.is_pressed(),
970                        },
971                        PluginHandle::new(&self.proxy),
972                    );
973
974                    let platform_event = PlatformEvent::Keyboard {
975                        name,
976                        key,
977                        code,
978                        modifiers,
979                    };
980                    let mut events_measurer_adapter = EventsMeasurerAdapter {
981                        scale_factor: app.effective_scale_factor(),
982                        tree: &mut app.tree,
983                    };
984                    let processed_events = events_measurer_adapter.run(
985                        &mut vec![platform_event],
986                        &mut app.nodes_state,
987                        app.accessibility.focused_node_id(),
988                    );
989                    app.events_sender
990                        .unbounded_send(EventsChunk::Processed(processed_events))
991                        .unwrap();
992                }
993
994                WindowEvent::MouseWheel { delta, phase, .. } => {
995                    const WHEEL_SPEED_MODIFIER: f64 = 53.0;
996                    const TOUCHPAD_SPEED_MODIFIER: f64 = 2.0;
997
998                    if TouchPhase::Moved == phase {
999                        let scroll_data = {
1000                            match delta {
1001                                MouseScrollDelta::LineDelta(x, y) => (
1002                                    (x as f64 * WHEEL_SPEED_MODIFIER),
1003                                    (y as f64 * WHEEL_SPEED_MODIFIER),
1004                                ),
1005                                MouseScrollDelta::PixelDelta(pos) => (
1006                                    (pos.x * TOUCHPAD_SPEED_MODIFIER),
1007                                    (pos.y * TOUCHPAD_SPEED_MODIFIER),
1008                                ),
1009                            }
1010                        };
1011
1012                        let platform_event = PlatformEvent::Wheel {
1013                            name: WheelEventName::Wheel,
1014                            scroll: scroll_data.into(),
1015                            cursor: app.position,
1016                            source: WheelSource::Device,
1017                        };
1018                        let mut events_measurer_adapter = EventsMeasurerAdapter {
1019                            scale_factor: app.effective_scale_factor(),
1020                            tree: &mut app.tree,
1021                        };
1022                        let processed_events = events_measurer_adapter.run(
1023                            &mut vec![platform_event],
1024                            &mut app.nodes_state,
1025                            app.accessibility.focused_node_id(),
1026                        );
1027                        app.events_sender
1028                            .unbounded_send(EventsChunk::Processed(processed_events))
1029                            .unwrap();
1030                    }
1031                }
1032
1033                WindowEvent::CursorLeft { .. } => {
1034                    if app.mouse_state == ElementState::Released {
1035                        app.position = CursorPoint::from((-1., -1.));
1036                        let platform_event = PlatformEvent::Mouse {
1037                            name: MouseEventName::MouseMove,
1038                            cursor: app.position,
1039                            button: None,
1040                        };
1041                        let mut events_measurer_adapter = EventsMeasurerAdapter {
1042                            scale_factor: app.effective_scale_factor(),
1043                            tree: &mut app.tree,
1044                        };
1045                        let processed_events = events_measurer_adapter.run(
1046                            &mut vec![platform_event],
1047                            &mut app.nodes_state,
1048                            app.accessibility.focused_node_id(),
1049                        );
1050                        app.events_sender
1051                            .unbounded_send(EventsChunk::Processed(processed_events))
1052                            .unwrap();
1053                    }
1054                }
1055                WindowEvent::CursorMoved { position, .. } => {
1056                    app.position = CursorPoint::from((position.x, position.y));
1057
1058                    let mut platform_event = vec![PlatformEvent::Mouse {
1059                        name: MouseEventName::MouseMove,
1060                        cursor: app.position,
1061                        button: None,
1062                    }];
1063
1064                    for dropped_file_path in app.dropped_file_paths.drain(..) {
1065                        platform_event.push(PlatformEvent::File {
1066                            name: FileEventName::FileDrop,
1067                            file_path: Some(dropped_file_path),
1068                            cursor: app.position,
1069                        });
1070                    }
1071
1072                    let mut events_measurer_adapter = EventsMeasurerAdapter {
1073                        scale_factor: app.effective_scale_factor(),
1074                        tree: &mut app.tree,
1075                    };
1076                    let processed_events = events_measurer_adapter.run(
1077                        &mut platform_event,
1078                        &mut app.nodes_state,
1079                        app.accessibility.focused_node_id(),
1080                    );
1081                    app.events_sender
1082                        .unbounded_send(EventsChunk::Processed(processed_events))
1083                        .unwrap();
1084                }
1085
1086                WindowEvent::Touch(Touch {
1087                    location,
1088                    phase,
1089                    id,
1090                    force,
1091                    ..
1092                }) => {
1093                    app.position = CursorPoint::from((location.x, location.y));
1094
1095                    let name = match phase {
1096                        TouchPhase::Cancelled => TouchEventName::TouchCancel,
1097                        TouchPhase::Ended => TouchEventName::TouchEnd,
1098                        TouchPhase::Moved => TouchEventName::TouchMove,
1099                        TouchPhase::Started => TouchEventName::TouchStart,
1100                    };
1101
1102                    let platform_event = PlatformEvent::Touch {
1103                        name,
1104                        location: app.position,
1105                        finger_id: id,
1106                        phase: map_winit_touch_phase(phase),
1107                        force: force.map(map_winit_touch_force),
1108                    };
1109                    let mut events_measurer_adapter = EventsMeasurerAdapter {
1110                        scale_factor: app.effective_scale_factor(),
1111                        tree: &mut app.tree,
1112                    };
1113                    let processed_events = events_measurer_adapter.run(
1114                        &mut vec![platform_event],
1115                        &mut app.nodes_state,
1116                        app.accessibility.focused_node_id(),
1117                    );
1118                    app.events_sender
1119                        .unbounded_send(EventsChunk::Processed(processed_events))
1120                        .unwrap();
1121                    app.position = CursorPoint::from((location.x, location.y));
1122                }
1123                WindowEvent::Ime(Ime::Commit(text)) => {
1124                    let platform_event = PlatformEvent::Keyboard {
1125                        name: KeyboardEventName::KeyDown,
1126                        key: keyboard_types::Key::Character(text),
1127                        code: keyboard_types::Code::Unidentified,
1128                        modifiers: winit_mappings::map_winit_modifiers(app.modifiers_state),
1129                    };
1130                    let mut events_measurer_adapter = EventsMeasurerAdapter {
1131                        scale_factor: app.effective_scale_factor(),
1132                        tree: &mut app.tree,
1133                    };
1134                    let processed_events = events_measurer_adapter.run(
1135                        &mut vec![platform_event],
1136                        &mut app.nodes_state,
1137                        app.accessibility.focused_node_id(),
1138                    );
1139                    app.events_sender
1140                        .unbounded_send(EventsChunk::Processed(processed_events))
1141                        .unwrap();
1142                }
1143                WindowEvent::Ime(Ime::Preedit(text, pos)) => {
1144                    let platform_event = PlatformEvent::ImePreedit {
1145                        name: ImeEventName::Preedit,
1146                        text,
1147                        cursor: pos,
1148                    };
1149                    let mut events_measurer_adapter = EventsMeasurerAdapter {
1150                        scale_factor: app.effective_scale_factor(),
1151                        tree: &mut app.tree,
1152                    };
1153                    let processed_events = events_measurer_adapter.run(
1154                        &mut vec![platform_event],
1155                        &mut app.nodes_state,
1156                        app.accessibility.focused_node_id(),
1157                    );
1158                    app.events_sender
1159                        .unbounded_send(EventsChunk::Processed(processed_events))
1160                        .unwrap();
1161                }
1162                WindowEvent::DroppedFile(file_path) => {
1163                    app.dropped_file_paths.push(file_path);
1164                }
1165                WindowEvent::HoveredFile(file_path) => {
1166                    let platform_event = PlatformEvent::File {
1167                        name: FileEventName::FileHover,
1168                        file_path: Some(file_path),
1169                        cursor: app.position,
1170                    };
1171                    let mut events_measurer_adapter = EventsMeasurerAdapter {
1172                        scale_factor: app.effective_scale_factor(),
1173                        tree: &mut app.tree,
1174                    };
1175                    let processed_events = events_measurer_adapter.run(
1176                        &mut vec![platform_event],
1177                        &mut app.nodes_state,
1178                        app.accessibility.focused_node_id(),
1179                    );
1180                    app.events_sender
1181                        .unbounded_send(EventsChunk::Processed(processed_events))
1182                        .unwrap();
1183                }
1184                WindowEvent::HoveredFileCancelled => {
1185                    let platform_event = PlatformEvent::File {
1186                        name: FileEventName::FileHoverCancelled,
1187                        file_path: None,
1188                        cursor: app.position,
1189                    };
1190                    let mut events_measurer_adapter = EventsMeasurerAdapter {
1191                        scale_factor: app.effective_scale_factor(),
1192                        tree: &mut app.tree,
1193                    };
1194                    let processed_events = events_measurer_adapter.run(
1195                        &mut vec![platform_event],
1196                        &mut app.nodes_state,
1197                        app.accessibility.focused_node_id(),
1198                    );
1199                    app.events_sender
1200                        .unbounded_send(EventsChunk::Processed(processed_events))
1201                        .unwrap();
1202                }
1203                _ => {}
1204            }
1205        }
1206    }
1207}
1208
1209fn subscribe_preferences(proxy: EventLoopProxy<NativeEvent>) {
1210    let subscription = mundy::Preferences::subscribe(mundy::Interest::AccentColor, move |prefs| {
1211        let _ = proxy.send_event(NativeEvent::Preferences(prefs));
1212    });
1213    std::mem::forget(subscription);
1214}