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#[derive(Clone)]
166pub struct LaunchProxy(pub EventLoopProxy<NativeEvent>);
167
168impl LaunchProxy {
169 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
241unsafe 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 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 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 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 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 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::RedrawRequested => {
723 let scale_factor = app.effective_scale_factor();
724 hotpath::measure_block!("RedrawRequested", {
725 if app.process_layout_on_next_render {
726 self.plugins.send(
727 PluginEvent::StartedMeasuringLayout {
728 window: &app.window,
729 tree: &app.tree,
730 },
731 PluginHandle::new(&self.proxy),
732 );
733 let size: Size2D = (
734 app.window.inner_size().width as f32,
735 app.window.inner_size().height as f32,
736 )
737 .into();
738
739 app.tree.measure_layout(
740 size,
741 &mut self.font_collection,
742 &self.font_manager,
743 &app.events_sender,
744 scale_factor,
745 &self.fallback_fonts,
746 );
747 app.platform.root_size.set_if_modified(size);
748 app.process_layout_on_next_render = false;
749 self.plugins.send(
750 PluginEvent::FinishedMeasuringLayout {
751 window: &app.window,
752 tree: &app.tree,
753 },
754 PluginHandle::new(&self.proxy),
755 );
756 }
757
758 app.driver.present(
759 app.window.inner_size().cast(),
760 &app.window,
761 |surface| {
762 self.plugins.send(
763 PluginEvent::BeforeRender {
764 window: &app.window,
765 canvas: surface.canvas(),
766 font_collection: &self.font_collection,
767 tree: &app.tree,
768 },
769 PluginHandle::new(&self.proxy),
770 );
771
772 let render_pipeline = RenderPipeline {
773 font_collection: &mut self.font_collection,
774 font_manager: &self.font_manager,
775 tree: &app.tree,
776 canvas: surface.canvas(),
777 scale_factor,
778 background: app.background,
779 };
780
781 render_pipeline.render();
782
783 self.plugins.send(
784 PluginEvent::AfterRender {
785 window: &app.window,
786 canvas: surface.canvas(),
787 font_collection: &self.font_collection,
788 tree: &app.tree,
789 animation_clock: &app.animation_clock,
790 },
791 PluginHandle::new(&self.proxy),
792 );
793 self.plugins.send(
794 PluginEvent::BeforePresenting {
795 window: &app.window,
796 font_collection: &self.font_collection,
797 tree: &app.tree,
798 },
799 PluginHandle::new(&self.proxy),
800 );
801 },
802 );
803 self.plugins.send(
804 PluginEvent::AfterPresenting {
805 window: &app.window,
806 font_collection: &self.font_collection,
807 tree: &app.tree,
808 },
809 PluginHandle::new(&self.proxy),
810 );
811
812 self.plugins.send(
813 PluginEvent::BeforeAccessibility {
814 window: &app.window,
815 font_collection: &self.font_collection,
816 tree: &app.tree,
817 },
818 PluginHandle::new(&self.proxy),
819 );
820
821 match app.accessibility_tasks_for_next_render.take() {
822 AccessibilityTask::ProcessUpdate { mode } => {
823 let update = app
824 .accessibility
825 .process_updates(&mut app.tree, &app.events_sender);
826 app.platform
827 .focused_accessibility_id
828 .set_if_modified(update.focus);
829 let node_id = app.accessibility.focused_node_id().unwrap();
830 let layout_node = app.tree.layout.get(&node_id).unwrap();
831 let focused_node =
832 AccessibilityTree::create_node(node_id, layout_node, &app.tree);
833 app.window.set_ime_allowed(is_ime_role(focused_node.role()));
834 app.platform
835 .focused_accessibility_node
836 .set_if_modified(focused_node);
837 if let Some(mode) = mode {
838 app.platform.navigation_mode.set(mode);
839 }
840
841 let area = layout_node.visible_area();
842 app.window.set_ime_cursor_area(
843 LogicalPosition::new(area.min_x(), area.min_y()),
844 LogicalSize::new(area.width(), area.height()),
845 );
846
847 app.accessibility_adapter.update_if_active(|| update);
848 }
849 AccessibilityTask::Init => {
850 let update = app.accessibility.init(&mut app.tree);
851 app.platform
852 .focused_accessibility_id
853 .set_if_modified(update.focus);
854 let node_id = app.accessibility.focused_node_id().unwrap();
855 let layout_node = app.tree.layout.get(&node_id).unwrap();
856 let focused_node =
857 AccessibilityTree::create_node(node_id, layout_node, &app.tree);
858 app.window.set_ime_allowed(is_ime_role(focused_node.role()));
859 app.platform
860 .focused_accessibility_node
861 .set_if_modified(focused_node);
862
863 let area = layout_node.visible_area();
864 app.window.set_ime_cursor_area(
865 LogicalPosition::new(area.min_x(), area.min_y()),
866 LogicalSize::new(area.width(), area.height()),
867 );
868
869 app.accessibility_adapter.update_if_active(|| update);
870 }
871 AccessibilityTask::None => {}
872 }
873
874 self.plugins.send(
875 PluginEvent::AfterAccessibility {
876 window: &app.window,
877 font_collection: &self.font_collection,
878 tree: &app.tree,
879 },
880 PluginHandle::new(&self.proxy),
881 );
882
883 if app.ticker_sender.receiver_count() > 0 {
884 app.ticker_sender.broadcast_blocking(()).unwrap();
885 }
886
887 self.plugins.send(
888 PluginEvent::AfterRedraw {
889 window: &app.window,
890 font_collection: &self.font_collection,
891 tree: &app.tree,
892 },
893 PluginHandle::new(&self.proxy),
894 );
895 });
896 }
897 WindowEvent::Resized(size) => {
898 app.driver.resize(size);
899
900 app.window.request_redraw();
901
902 app.process_layout_on_next_render = true;
903 app.tree.layout.clear_dirty();
904 app.tree.layout.invalidate(NodeId::ROOT);
905 }
906
907 WindowEvent::MouseInput { state, button, .. } => {
908 app.mouse_state = state;
909 app.platform
910 .navigation_mode
911 .set(NavigationMode::NotKeyboard);
912
913 let name = if state == ElementState::Pressed {
914 MouseEventName::MouseDown
915 } else {
916 MouseEventName::MouseUp
917 };
918 let platform_event = PlatformEvent::Mouse {
919 name,
920 cursor: (app.position.x, app.position.y).into(),
921 button: Some(map_winit_mouse_button(button)),
922 };
923 let mut events_measurer_adapter = EventsMeasurerAdapter {
924 scale_factor: app.effective_scale_factor(),
925 tree: &mut app.tree,
926 };
927 let processed_events = events_measurer_adapter.run(
928 &mut vec![platform_event],
929 &mut app.nodes_state,
930 app.accessibility.focused_node_id(),
931 );
932 app.events_sender
933 .unbounded_send(EventsChunk::Processed(processed_events))
934 .unwrap();
935 }
936
937 WindowEvent::KeyboardInput {
938 event,
939 is_synthetic,
940 ..
941 } => {
942 if is_synthetic && event.state == ElementState::Pressed {
944 return;
945 }
946
947 let name = match event.state {
948 ElementState::Pressed => KeyboardEventName::KeyDown,
949 ElementState::Released => KeyboardEventName::KeyUp,
950 };
951 let key = winit_mappings::map_winit_key(&event.logical_key);
952 let code = winit_mappings::map_winit_physical_key(&event.physical_key);
953 let modifiers = winit_mappings::map_winit_modifiers(app.modifiers_state);
954
955 #[cfg(feature = "zoom-shortcuts")]
956 if app.try_handle_zoom_shortcut(&key, modifiers, event.state.is_pressed()) {
957 return;
958 }
959
960 self.plugins.send(
961 PluginEvent::KeyboardInput {
962 window: &app.window,
963 key: key.clone(),
964 code,
965 modifiers,
966 is_pressed: event.state.is_pressed(),
967 },
968 PluginHandle::new(&self.proxy),
969 );
970
971 let platform_event = PlatformEvent::Keyboard {
972 name,
973 key,
974 code,
975 modifiers,
976 };
977 let mut events_measurer_adapter = EventsMeasurerAdapter {
978 scale_factor: app.effective_scale_factor(),
979 tree: &mut app.tree,
980 };
981 let processed_events = events_measurer_adapter.run(
982 &mut vec![platform_event],
983 &mut app.nodes_state,
984 app.accessibility.focused_node_id(),
985 );
986 app.events_sender
987 .unbounded_send(EventsChunk::Processed(processed_events))
988 .unwrap();
989 }
990
991 WindowEvent::MouseWheel { delta, phase, .. } => {
992 const WHEEL_SPEED_MODIFIER: f64 = 53.0;
993 const TOUCHPAD_SPEED_MODIFIER: f64 = 2.0;
994
995 if TouchPhase::Moved == phase {
996 let scroll_data = {
997 match delta {
998 MouseScrollDelta::LineDelta(x, y) => (
999 (x as f64 * WHEEL_SPEED_MODIFIER),
1000 (y as f64 * WHEEL_SPEED_MODIFIER),
1001 ),
1002 MouseScrollDelta::PixelDelta(pos) => (
1003 (pos.x * TOUCHPAD_SPEED_MODIFIER),
1004 (pos.y * TOUCHPAD_SPEED_MODIFIER),
1005 ),
1006 }
1007 };
1008
1009 let platform_event = PlatformEvent::Wheel {
1010 name: WheelEventName::Wheel,
1011 scroll: scroll_data.into(),
1012 cursor: app.position,
1013 source: WheelSource::Device,
1014 };
1015 let mut events_measurer_adapter = EventsMeasurerAdapter {
1016 scale_factor: app.effective_scale_factor(),
1017 tree: &mut app.tree,
1018 };
1019 let processed_events = events_measurer_adapter.run(
1020 &mut vec![platform_event],
1021 &mut app.nodes_state,
1022 app.accessibility.focused_node_id(),
1023 );
1024 app.events_sender
1025 .unbounded_send(EventsChunk::Processed(processed_events))
1026 .unwrap();
1027 }
1028 }
1029
1030 WindowEvent::CursorLeft { .. } => {
1031 if app.mouse_state == ElementState::Released {
1032 app.position = CursorPoint::from((-1., -1.));
1033 let platform_event = PlatformEvent::Mouse {
1034 name: MouseEventName::MouseMove,
1035 cursor: app.position,
1036 button: None,
1037 };
1038 let mut events_measurer_adapter = EventsMeasurerAdapter {
1039 scale_factor: app.effective_scale_factor(),
1040 tree: &mut app.tree,
1041 };
1042 let processed_events = events_measurer_adapter.run(
1043 &mut vec![platform_event],
1044 &mut app.nodes_state,
1045 app.accessibility.focused_node_id(),
1046 );
1047 app.events_sender
1048 .unbounded_send(EventsChunk::Processed(processed_events))
1049 .unwrap();
1050 }
1051 }
1052 WindowEvent::CursorMoved { position, .. } => {
1053 app.position = CursorPoint::from((position.x, position.y));
1054
1055 let mut platform_event = vec![PlatformEvent::Mouse {
1056 name: MouseEventName::MouseMove,
1057 cursor: app.position,
1058 button: None,
1059 }];
1060
1061 for dropped_file_path in app.dropped_file_paths.drain(..) {
1062 platform_event.push(PlatformEvent::File {
1063 name: FileEventName::FileDrop,
1064 file_path: Some(dropped_file_path),
1065 cursor: app.position,
1066 });
1067 }
1068
1069 let mut events_measurer_adapter = EventsMeasurerAdapter {
1070 scale_factor: app.effective_scale_factor(),
1071 tree: &mut app.tree,
1072 };
1073 let processed_events = events_measurer_adapter.run(
1074 &mut platform_event,
1075 &mut app.nodes_state,
1076 app.accessibility.focused_node_id(),
1077 );
1078 app.events_sender
1079 .unbounded_send(EventsChunk::Processed(processed_events))
1080 .unwrap();
1081 }
1082
1083 WindowEvent::Touch(Touch {
1084 location,
1085 phase,
1086 id,
1087 force,
1088 ..
1089 }) => {
1090 app.position = CursorPoint::from((location.x, location.y));
1091
1092 let name = match phase {
1093 TouchPhase::Cancelled => TouchEventName::TouchCancel,
1094 TouchPhase::Ended => TouchEventName::TouchEnd,
1095 TouchPhase::Moved => TouchEventName::TouchMove,
1096 TouchPhase::Started => TouchEventName::TouchStart,
1097 };
1098
1099 let platform_event = PlatformEvent::Touch {
1100 name,
1101 location: app.position,
1102 finger_id: id,
1103 phase: map_winit_touch_phase(phase),
1104 force: force.map(map_winit_touch_force),
1105 };
1106 let mut events_measurer_adapter = EventsMeasurerAdapter {
1107 scale_factor: app.effective_scale_factor(),
1108 tree: &mut app.tree,
1109 };
1110 let processed_events = events_measurer_adapter.run(
1111 &mut vec![platform_event],
1112 &mut app.nodes_state,
1113 app.accessibility.focused_node_id(),
1114 );
1115 app.events_sender
1116 .unbounded_send(EventsChunk::Processed(processed_events))
1117 .unwrap();
1118 app.position = CursorPoint::from((location.x, location.y));
1119 }
1120 WindowEvent::Ime(Ime::Commit(text)) => {
1121 let platform_event = PlatformEvent::Keyboard {
1122 name: KeyboardEventName::KeyDown,
1123 key: keyboard_types::Key::Character(text),
1124 code: keyboard_types::Code::Unidentified,
1125 modifiers: winit_mappings::map_winit_modifiers(app.modifiers_state),
1126 };
1127 let mut events_measurer_adapter = EventsMeasurerAdapter {
1128 scale_factor: app.effective_scale_factor(),
1129 tree: &mut app.tree,
1130 };
1131 let processed_events = events_measurer_adapter.run(
1132 &mut vec![platform_event],
1133 &mut app.nodes_state,
1134 app.accessibility.focused_node_id(),
1135 );
1136 app.events_sender
1137 .unbounded_send(EventsChunk::Processed(processed_events))
1138 .unwrap();
1139 }
1140 WindowEvent::Ime(Ime::Preedit(text, pos)) => {
1141 let platform_event = PlatformEvent::ImePreedit {
1142 name: ImeEventName::Preedit,
1143 text,
1144 cursor: pos,
1145 };
1146 let mut events_measurer_adapter = EventsMeasurerAdapter {
1147 scale_factor: app.effective_scale_factor(),
1148 tree: &mut app.tree,
1149 };
1150 let processed_events = events_measurer_adapter.run(
1151 &mut vec![platform_event],
1152 &mut app.nodes_state,
1153 app.accessibility.focused_node_id(),
1154 );
1155 app.events_sender
1156 .unbounded_send(EventsChunk::Processed(processed_events))
1157 .unwrap();
1158 }
1159 WindowEvent::DroppedFile(file_path) => {
1160 app.dropped_file_paths.push(file_path);
1161 }
1162 WindowEvent::HoveredFile(file_path) => {
1163 let platform_event = PlatformEvent::File {
1164 name: FileEventName::FileHover,
1165 file_path: Some(file_path),
1166 cursor: app.position,
1167 };
1168 let mut events_measurer_adapter = EventsMeasurerAdapter {
1169 scale_factor: app.effective_scale_factor(),
1170 tree: &mut app.tree,
1171 };
1172 let processed_events = events_measurer_adapter.run(
1173 &mut vec![platform_event],
1174 &mut app.nodes_state,
1175 app.accessibility.focused_node_id(),
1176 );
1177 app.events_sender
1178 .unbounded_send(EventsChunk::Processed(processed_events))
1179 .unwrap();
1180 }
1181 WindowEvent::HoveredFileCancelled => {
1182 let platform_event = PlatformEvent::File {
1183 name: FileEventName::FileHoverCancelled,
1184 file_path: None,
1185 cursor: app.position,
1186 };
1187 let mut events_measurer_adapter = EventsMeasurerAdapter {
1188 scale_factor: app.effective_scale_factor(),
1189 tree: &mut app.tree,
1190 };
1191 let processed_events = events_measurer_adapter.run(
1192 &mut vec![platform_event],
1193 &mut app.nodes_state,
1194 app.accessibility.focused_node_id(),
1195 );
1196 app.events_sender
1197 .unbounded_send(EventsChunk::Processed(processed_events))
1198 .unwrap();
1199 }
1200 _ => {}
1201 }
1202 }
1203 }
1204}
1205
1206fn subscribe_preferences(proxy: EventLoopProxy<NativeEvent>) {
1207 let subscription = mundy::Preferences::subscribe(mundy::Interest::AccentColor, move |prefs| {
1208 let _ = proxy.send_event(NativeEvent::Preferences(prefs));
1209 });
1210 std::mem::forget(subscription);
1211}