Skip to main content

vizia_winit/
application.rs

1#[cfg(target_os = "windows")]
2use crate::window::set_cloak;
3use crate::{
4    convert::{winit_key_code_to_code, winit_key_to_key},
5    window::{WinState, Window},
6};
7#[cfg(feature = "accesskit")]
8use accesskit_winit::Adapter;
9#[cfg(all(
10    feature = "clipboard",
11    feature = "wayland",
12    any(
13        target_os = "linux",
14        target_os = "dragonfly",
15        target_os = "freebsd",
16        target_os = "netbsd",
17        target_os = "openbsd"
18    )
19))]
20use copypasta::wayland_clipboard::create_clipboards_from_external;
21use hashbrown::HashMap;
22use log::warn;
23use std::{error::Error, fmt::Display, sync::Arc};
24use vizia_input::ImeState;
25
26// #[cfg(feature = "accesskit")]
27// use accesskit::{Action, NodeBuilder, NodeId, TreeUpdate};
28// #[cfg(feature = "accesskit")]
29// use accesskit_winit;
30use vizia_core::context::EventProxy;
31use vizia_core::events::ProxyEvent;
32use vizia_core::prelude::*;
33use vizia_core::{backend::*, events::EventManager};
34use vizia_reactive::Runtime;
35use winit::{
36    application::ApplicationHandler,
37    dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize},
38    error::EventLoopError,
39    event::ElementState,
40    event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy},
41    keyboard::{NativeKeyCode, PhysicalKey},
42    window::{CursorIcon, CustomCursor, WindowAttributes, WindowId, WindowLevel},
43};
44
45#[cfg(all(
46    feature = "clipboard",
47    feature = "wayland",
48    any(
49        target_os = "linux",
50        target_os = "dragonfly",
51        target_os = "freebsd",
52        target_os = "netbsd",
53        target_os = "openbsd"
54    )
55))]
56use winit::raw_window_handle::{HasDisplayHandle, RawDisplayHandle};
57
58// #[cfg(all(
59//     feature = "clipboard",
60//     feature = "wayland",
61//     any(
62//         target_os = "linux",
63//         target_os = "dragonfly",
64//         target_os = "freebsd",
65//         target_os = "netbsd",
66//         target_os = "openbsd"
67//     )
68// ))]
69// use raw_window_handle::{HasRawDisplayHandle, RawDisplayHandle};
70use vizia_window::{Anchor, AnchorTarget, WindowPosition};
71
72#[derive(Debug)]
73pub enum UserEvent {
74    Event(ProxyEvent),
75    #[cfg(feature = "accesskit")]
76    AccessKitEvent(accesskit_winit::Event),
77    #[cfg(feature = "tray")]
78    TrayIconEvent(tray_icon::TrayIconEvent),
79    #[cfg(feature = "tray")]
80    TrayMenuEvent(tray_icon::menu::MenuEvent),
81}
82
83#[cfg(feature = "accesskit")]
84impl From<accesskit_winit::Event> for UserEvent {
85    fn from(action_request_event: accesskit_winit::Event) -> Self {
86        UserEvent::AccessKitEvent(action_request_event)
87    }
88}
89
90type IdleCallback = Option<Box<dyn Fn(&mut Context)>>;
91
92#[cfg(feature = "tray")]
93type TrayIconBuilderCallback = Box<dyn FnOnce() -> tray_icon::TrayIconBuilder + Send>;
94
95#[derive(Debug)]
96pub enum ApplicationError {
97    EventLoopError(EventLoopError),
98    LogError,
99}
100
101impl Display for ApplicationError {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            ApplicationError::EventLoopError(ele) => write!(f, "{}", ele),
105            ApplicationError::LogError => write!(f, "log error"),
106        }
107    }
108}
109
110impl std::error::Error for ApplicationError {}
111
112/// Creating an application creates a `Context`. Create windows explicitly with `Window::new`.
113///
114/// # Example
115/// ```no_run
116/// # use vizia_core::prelude::*;
117/// # use vizia_winit::application::Application;
118/// # use vizia_winit::window::Window;
119/// Application::new(|cx| {
120///     Window::new(cx, |cx| {
121///         Label::new(cx, "Hello, Vizia!");
122///     });
123/// })
124/// .run();
125///```
126/// Calling `run()` on the `Application` enters the event loop.
127pub struct Application {
128    cx: BackendContext,
129    event_manager: EventManager,
130    pub(crate) event_loop: Option<EventLoop<UserEvent>>,
131    on_idle: IdleCallback,
132    control_flow: ControlFlow,
133    event_loop_proxy: EventLoopProxy<UserEvent>,
134    windows: HashMap<WindowId, WinState>,
135    window_ids: HashMap<Entity, WindowId>,
136    custom_cursors: Arc<HashMap<CursorIcon, CustomCursor>>,
137    exit_when_no_windows: bool,
138    had_windows: bool,
139    #[cfg(feature = "tray")]
140    tray_icon_builder: Option<TrayIconBuilderCallback>,
141    #[cfg(all(
142        feature = "tray",
143        not(any(
144            target_os = "linux",
145            target_os = "dragonfly",
146            target_os = "freebsd",
147            target_os = "netbsd",
148            target_os = "openbsd"
149        ))
150    ))]
151    tray_icon: Option<tray_icon::TrayIcon>,
152    #[cfg(feature = "accesskit")]
153    accesskit_adapter: Option<accesskit_winit::Adapter>,
154    #[cfg(feature = "accesskit")]
155    adapter_initialized: bool,
156}
157
158pub struct WinitEventProxy(EventLoopProxy<UserEvent>);
159
160impl EventProxy for WinitEventProxy {
161    fn send(&self, event: ProxyEvent) -> Result<(), ()> {
162        self.0.send_event(UserEvent::Event(event)).map_err(|_| ())
163    }
164
165    fn make_clone(&self) -> Box<dyn EventProxy> {
166        Box::new(WinitEventProxy(self.0.clone()))
167    }
168}
169
170impl Application {
171    pub fn new<F>(content: F) -> Self
172    where
173        F: 'static + FnOnce(&mut Context),
174    {
175        let context = Context::new();
176
177        let event_loop =
178            EventLoop::<UserEvent>::with_user_event().build().expect("Failed to create event loop");
179
180        let mut cx = BackendContext::new(context);
181
182        // Mark the current thread as the UI thread so that rayon workers
183        // correctly enqueue effects via SYNC_RUNTIME instead of the
184        // thread-local RUNTIME (which nobody drains).
185        Runtime::init_on_ui_thread();
186
187        let proxy = event_loop.create_proxy();
188        cx.set_event_proxy(Box::new(WinitEventProxy(proxy.clone())));
189
190        // Wake the event loop when a SyncSignal changes off the UI thread.
191        let waker_proxy = proxy.clone();
192        Runtime::set_sync_effect_waker(move || {
193            let _ = waker_proxy.send_event(UserEvent::Event(ProxyEvent::new(())));
194        });
195
196        cx.renegotiate_language();
197        cx.0.add_built_in_translations();
198        (content)(cx.context());
199        cx.0.add_built_in_styles();
200
201        Self {
202            cx,
203            event_manager: EventManager::new(),
204            event_loop: Some(event_loop),
205            on_idle: None,
206            control_flow: ControlFlow::Wait,
207            event_loop_proxy: proxy,
208            windows: HashMap::new(),
209            window_ids: HashMap::new(),
210            custom_cursors: Arc::new(HashMap::new()),
211            exit_when_no_windows: true,
212            had_windows: false,
213            #[cfg(feature = "tray")]
214            tray_icon_builder: None,
215            #[cfg(all(
216                feature = "tray",
217                not(any(
218                    target_os = "linux",
219                    target_os = "dragonfly",
220                    target_os = "freebsd",
221                    target_os = "netbsd",
222                    target_os = "openbsd"
223                ))
224            ))]
225            tray_icon: None,
226            #[cfg(feature = "accesskit")]
227            accesskit_adapter: None,
228            #[cfg(feature = "accesskit")]
229            adapter_initialized: false,
230        }
231    }
232
233    fn create_window(
234        &mut self,
235        event_loop: &ActiveEventLoop,
236        window_entity: Entity,
237        window_description: &WindowDescription,
238        #[allow(unused_variables)] owner: Option<Arc<winit::window::Window>>,
239    ) -> Result<Arc<winit::window::Window>, Box<dyn Error>> {
240        let window_attributes = apply_window_description(window_description);
241
242        let window_state = WinState::new(
243            event_loop,
244            window_entity,
245            window_attributes,
246            window_description.skia_resource_cache_limit,
247            owner,
248        )?;
249        let window = window_state.window.clone();
250
251        if let Some(position) = window_description.position {
252            window.set_outer_position(LogicalPosition::new(position.x, position.y));
253        } else {
254            let (anchor, mut parent_anchor) =
255                match (window_description.anchor, window_description.parent_anchor) {
256                    (Some(a), None) => (Some(a), Some(a)),
257                    (None, Some(b)) => (Some(b.opposite()), Some(b)),
258                    t => t,
259                };
260
261            if let Some(anchor) = anchor {
262                let (y, x) = match anchor {
263                    Anchor::TopLeft => (0.0, 0.0),
264                    Anchor::TopCenter => (0.0, 0.5),
265                    Anchor::TopRight => (0.0, 1.0),
266                    Anchor::Left => (0.5, 0.0),
267                    Anchor::Center => (0.5, 0.5),
268                    Anchor::Right => (0.5, 1.0),
269                    Anchor::BottomLeft => (1.0, 0.0),
270                    Anchor::BottomCenter => (1.0, 0.5),
271                    Anchor::BottomRight => (1.0, 1.0),
272                };
273
274                let window_size = window.inner_size();
275                let anchor_target = window_description.anchor_target.unwrap_or_default();
276                let parent = match anchor_target {
277                    AnchorTarget::Monitor => window
278                        .current_monitor()
279                        .map(|monitor| (PhysicalPosition::default(), monitor.size())),
280                    AnchorTarget::Window => self
281                        .cx
282                        .0
283                        .tree
284                        .get_parent_window(window_entity)
285                        .and_then(|parent_window| self.window_ids.get(&parent_window))
286                        .and_then(|id| self.windows.get(id))
287                        .and_then(|WinState { window, .. }| {
288                            let position = window
289                                .outer_position()
290                                .inspect_err(|e| warn!("can't get window position: {e:?}"));
291                            Some((position.ok()?, window.inner_size()))
292                        }),
293                    AnchorTarget::Mouse => self
294                        .cx
295                        .0
296                        .tree
297                        .get_parent_window(window_entity)
298                        .and_then(|parent_window| self.window_ids.get(&parent_window))
299                        .and_then(|id| self.windows.get(id))
300                        .and_then(|WinState { window, .. }| {
301                            window
302                                .outer_position()
303                                .inspect_err(|e| warn!("can't get window position: {e:?}"))
304                                .ok()
305                        })
306                        .map(|pos| {
307                            (
308                                PhysicalPosition::new(
309                                    pos.x + self.cx.0.mouse.cursor_x as i32,
310                                    pos.y + self.cx.0.mouse.cursor_y as i32,
311                                ),
312                                PhysicalSize::new(0, 0),
313                            )
314                        }),
315                };
316
317                if let Some((parent_position, parent_size)) = parent {
318                    if anchor_target != AnchorTarget::Window {
319                        parent_anchor = Some(anchor);
320                    }
321
322                    let (py, px) = match parent_anchor.unwrap_or_default() {
323                        Anchor::TopLeft => (0.0, 0.0),
324                        Anchor::TopCenter => (0.0, 0.5),
325                        Anchor::TopRight => (0.0, 1.0),
326                        Anchor::Left => (0.5, 0.0),
327                        Anchor::Center => (0.5, 0.5),
328                        Anchor::Right => (0.5, 1.0),
329                        Anchor::BottomLeft => (1.0, 0.0),
330                        Anchor::BottomCenter => (1.0, 0.5),
331                        Anchor::BottomRight => (1.0, 1.0),
332                    };
333
334                    let x = (((parent_size.width as f32 * px) as i32
335                        - (window_size.width as f32 * x) as i32)
336                        as f32) as i32;
337                    let y = (((parent_size.height as f32 * py) as i32
338                        - (window_size.height as f32 * y) as i32)
339                        as f32) as i32;
340                    let offset = window_description.offset.unwrap_or_default();
341                    let offset: PhysicalPosition<i32> = PhysicalPosition::from_logical(
342                        LogicalPosition::new(offset.x, offset.y),
343                        window.scale_factor(),
344                    );
345
346                    window.set_outer_position(PhysicalPosition::new(
347                        parent_position.x + x + offset.x,
348                        parent_position.y + y + offset.y,
349                    ));
350                }
351            }
352        }
353
354        let window_id = window_state.window.id();
355        self.windows.insert(window_id, window_state);
356        self.window_ids.insert(window_entity, window_id);
357
358        #[cfg(all(
359            feature = "clipboard",
360            feature = "wayland",
361            any(
362                target_os = "linux",
363                target_os = "dragonfly",
364                target_os = "freebsd",
365                target_os = "netbsd",
366                target_os = "openbsd"
367            )
368        ))]
369        self.init_wayland_clipboard(window_entity, &window);
370
371        self.had_windows = true;
372        Ok(window)
373    }
374
375    #[cfg(all(
376        feature = "clipboard",
377        feature = "wayland",
378        any(
379            target_os = "linux",
380            target_os = "dragonfly",
381            target_os = "freebsd",
382            target_os = "netbsd",
383            target_os = "openbsd"
384        )
385    ))]
386    fn init_wayland_clipboard(&mut self, window_entity: Entity, window: &winit::window::Window) {
387        let Ok(display_handle) = window.display_handle() else {
388            return;
389        };
390
391        if let RawDisplayHandle::Wayland(handle) = display_handle.as_raw() {
392            // SAFETY: The display handle is from a live window and is valid for the provider's lifetime.
393            let (_, clipboard) =
394                unsafe { create_clipboards_from_external(handle.display.as_ptr()) };
395            self.cx.set_clipboard_provider(window_entity, Box::new(clipboard));
396        }
397    }
398
399    /// Sets the default built-in theming to be ignored.
400    pub fn ignore_default_theme(mut self) -> Self {
401        self.cx.context().ignore_default_theme = true;
402        self
403    }
404
405    pub fn should_poll(mut self) -> Self {
406        self.control_flow = ControlFlow::Poll;
407
408        self
409    }
410
411    /// Takes a closure which will be called at the end of every loop of the application.
412    ///
413    /// The callback provides a place to run 'idle' processing and happens at the end of each loop but before drawing.
414    /// If the callback pushes events into the queue in state then the event loop will re-run. Care must be taken not to
415    /// push events into the queue every time the callback runs unless this is intended.
416    ///
417    /// # Example
418    ///
419    /// ```no_run
420    /// # use vizia_core::prelude::*;
421    /// # use vizia_winit::application::Application;
422    /// # use vizia_winit::window::Window;
423    /// #
424    /// Application::new(|cx| {
425    ///     Window::new(cx, |cx| {
426    ///         // Build application here
427    ///     });
428    /// })
429    /// .on_idle(|cx| {
430    ///     // Code here runs at the end of every event loop after OS and vizia events have been handled
431    /// })
432    /// .run();
433    /// ```
434    pub fn on_idle<F: 'static + Fn(&mut Context)>(mut self, callback: F) -> Self {
435        self.on_idle = Some(Box::new(callback));
436
437        self
438    }
439
440    /// Controls whether the application exits automatically when all windows are closed.
441    ///
442    /// Defaults to `true`. The exit only triggers once at least one window has been opened and
443    /// then all windows are closed, so applications that start without windows are not affected
444    /// until their first window is created and subsequently closed.
445    /// Set to `false` to keep the event loop running as a daemon even after all windows close.
446    pub fn exit_when_no_windows(mut self, exit: bool) -> Self {
447        self.exit_when_no_windows = exit;
448        self
449    }
450
451    /// Adds a system tray icon to the application, built with the [`tray-icon`](https://docs.rs/tray-icon) crate.
452    ///
453    /// The provided closure is called once the event loop is running and should return a
454    /// [`tray_icon::TrayIconBuilder`] describing the tray icon. The returned builder is built by
455    /// vizia at the appropriate time for each platform:
456    ///
457    /// - On Windows the tray icon is created once the event loop has started.
458    /// - On macOS the tray icon is created once the event loop has started, as required by the OS.
459    /// - On Linux and the BSDs the closure is invoked on a dedicated thread which initializes
460    ///   `gtk`, since the tray icon requires gtk while winit does not use it. This is why the
461    ///   closure must be `Send`.
462    ///
463    /// [`tray_icon::TrayIconEvent`]s and [`tray_icon::menu::MenuEvent`]s are forwarded to the
464    /// application and propagated through the entire tree, so they can be handled from any view
465    /// or model with [`Event::map`](vizia_core::events::Event::map).
466    ///
467    /// # Example
468    ///
469    /// ```no_run
470    /// # use vizia_core::prelude::*;
471    /// # use vizia_winit::application::Application;
472    /// # use vizia_winit::tray_icon;
473    /// # let icon_rgba: Vec<u8> = vec![255; 32 * 32 * 4];
474    /// Application::new(|cx| {
475    ///     // Build application here
476    /// })
477    /// .with_tray_icon(move || {
478    ///     let icon = tray_icon::Icon::from_rgba(icon_rgba, 32, 32).unwrap();
479    ///     tray_icon::TrayIconBuilder::new().with_tooltip("My app").with_icon(icon)
480    /// })
481    /// .run();
482    /// ```
483    #[cfg(feature = "tray")]
484    pub fn with_tray_icon<F>(mut self, build_tray: F) -> Self
485    where
486        F: FnOnce() -> tray_icon::TrayIconBuilder + Send + 'static,
487    {
488        // Forward tray icon and tray menu events to the event loop, waking it up in the process.
489        let proxy = self.event_loop_proxy.clone();
490        tray_icon::TrayIconEvent::set_event_handler(Some(move |event| {
491            let _ = proxy.send_event(UserEvent::TrayIconEvent(event));
492        }));
493
494        let proxy = self.event_loop_proxy.clone();
495        tray_icon::menu::MenuEvent::set_event_handler(Some(move |event| {
496            let _ = proxy.send_event(UserEvent::TrayMenuEvent(event));
497        }));
498
499        self.tray_icon_builder = Some(Box::new(build_tray));
500        self
501    }
502
503    #[cfg(all(
504        feature = "tray",
505        not(any(
506            target_os = "linux",
507            target_os = "dragonfly",
508            target_os = "freebsd",
509            target_os = "netbsd",
510            target_os = "openbsd"
511        ))
512    ))]
513    fn create_tray_icon(&mut self) {
514        let Some(build_tray) = self.tray_icon_builder.take() else {
515            return;
516        };
517
518        match (build_tray)().build() {
519            Ok(tray_icon) => self.tray_icon = Some(tray_icon),
520            Err(err) => warn!("Failed to create tray icon: {}", err),
521        }
522
523        // On macOS the main run loop must be woken up for the tray icon to show up immediately.
524        #[cfg(target_os = "macos")]
525        if let Some(run_loop) = objc2_core_foundation::CFRunLoop::main() {
526            run_loop.wake_up();
527        }
528    }
529
530    /// Returns a `ContextProxy` which can be used to send events from another thread.
531    pub fn get_proxy(&self) -> ContextProxy {
532        self.cx.0.get_proxy()
533    }
534
535    pub fn run(mut self) -> Result<(), ApplicationError> {
536        // Winit doesn't use gtk on Linux but the tray icon requires it, so initialize gtk and
537        // create the tray icon on a dedicated thread.
538        #[cfg(all(
539            feature = "tray",
540            any(
541                target_os = "linux",
542                target_os = "dragonfly",
543                target_os = "freebsd",
544                target_os = "netbsd",
545                target_os = "openbsd"
546            )
547        ))]
548        if let Some(build_tray) = self.tray_icon_builder.take() {
549            std::thread::spawn(move || {
550                if let Err(err) = gtk::init() {
551                    warn!("Failed to initialize gtk for the tray icon: {}", err);
552                    return;
553                }
554
555                match (build_tray)().build() {
556                    Ok(_tray_icon) => gtk::main(),
557                    Err(err) => warn!("Failed to create tray icon: {}", err),
558                }
559            });
560        }
561
562        self.event_loop.take().unwrap().run_app(&mut self).map_err(ApplicationError::EventLoopError)
563    }
564}
565
566impl ApplicationHandler<UserEvent> for Application {
567    fn user_event(&mut self, _event_loop: &ActiveEventLoop, user_event: UserEvent) {
568        match user_event {
569            UserEvent::Event(event) => {
570                self.cx.send_event(event.into_event());
571            }
572
573            #[cfg(feature = "tray")]
574            UserEvent::TrayIconEvent(event) => {
575                self.cx.send_event(
576                    Event::new(event)
577                        .target(Entity::root())
578                        .origin(Entity::root())
579                        .propagate(Propagation::Subtree),
580                );
581            }
582
583            #[cfg(feature = "tray")]
584            UserEvent::TrayMenuEvent(event) => {
585                self.cx.send_event(
586                    Event::new(event)
587                        .target(Entity::root())
588                        .origin(Entity::root())
589                        .propagate(Propagation::Subtree),
590                );
591            }
592
593            #[cfg(feature = "accesskit")]
594            UserEvent::AccessKitEvent(access_event) => {
595                match access_event.window_event {
596                    accesskit_winit::WindowEvent::InitialTreeRequested => {
597                        let tree_update = self.cx.init_accessibility_tree();
598                        if let Some(adapter) = &mut self.accesskit_adapter {
599                            adapter.update_if_active(|| {
600                                self.adapter_initialized = true;
601                                tree_update
602                            });
603                        }
604                    }
605                    accesskit_winit::WindowEvent::ActionRequested(action_request) => {
606                        let node_id = action_request.target_node;
607
608                        if action_request.action != Action::ScrollIntoView {
609                            let entity = Entity::new(node_id.0, 0);
610
611                            // Handle focus action from screen reader
612                            if action_request.action == Action::Focus {
613                                self.cx.0.with_current(entity, |cx| {
614                                    cx.focus();
615                                });
616                            }
617
618                            self.cx.send_event(
619                                Event::new(WindowEvent::ActionRequest(action_request))
620                                    .direct(entity),
621                            );
622                        }
623                    }
624                    accesskit_winit::WindowEvent::AccessibilityDeactivated => todo!(),
625                }
626            }
627        }
628    }
629
630    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
631        if self.windows.is_empty() {
632            if self.custom_cursors.is_empty() {
633                self.custom_cursors = Arc::new(load_default_cursors(event_loop));
634            }
635            self.cx.0.add_built_in_styles();
636
637            // Create user-defined windows.
638            for (window_entity, window_state) in self.cx.0.windows.clone().into_iter() {
639                let owner = window_state.owner.and_then(|entity| {
640                    self.window_ids
641                        .get(&entity)
642                        .and_then(|id| self.windows.get(id).map(|ws| ws.window.clone()))
643                });
644
645                let window = self
646                    .create_window(
647                        event_loop,
648                        window_entity,
649                        &window_state.window_description,
650                        owner,
651                    )
652                    .expect("Failed to create window");
653
654                #[cfg(feature = "accesskit")]
655                if self.accesskit_adapter.is_none() {
656                    self.accesskit_adapter = Some(Adapter::with_event_loop_proxy(
657                        event_loop,
658                        &window,
659                        self.event_loop_proxy.clone(),
660                    ));
661                }
662
663                self.cx.add_main_window(
664                    window_entity,
665                    &window_state.window_description,
666                    window.scale_factor() as f32,
667                );
668                window.set_visible(window_state.window_description.visible);
669
670                self.cx.0.with_current(window_entity, |cx| {
671                    if let Some(content) = &window_state.content {
672                        (content)(cx)
673                    }
674                });
675                self.cx.mutate_window(window_entity, |cx, win: &mut Window| {
676                    win.window = Some(window.clone());
677                    win.custom_cursors = self.custom_cursors.clone();
678                    if let Some(callback) = &win.on_create {
679                        (callback)(&mut EventContext::new_with_current(
680                            cx.context(),
681                            window_entity,
682                        ));
683                    }
684                });
685                if self.windows.len() == 1
686                    && let Some(theme) = window.theme()
687                {
688                    let theme = match theme {
689                        winit::window::Theme::Light => ThemeMode::LightMode,
690                        winit::window::Theme::Dark => ThemeMode::DarkMode,
691                    };
692                    self.cx.emit_origin(WindowEvent::ThemeChanged(theme));
693                }
694                self.cx.needs_refresh(window_entity);
695            }
696        }
697    }
698
699    fn window_event(
700        &mut self,
701        _event_loop: &ActiveEventLoop,
702        window_id: WindowId,
703        event: winit::event::WindowEvent,
704    ) {
705        let window = match self.windows.get_mut(&window_id) {
706            Some(window) => window,
707            None => return,
708        };
709
710        match event {
711            winit::event::WindowEvent::Resized(size) => {
712                if let Some((width, height)) = resized_bounds(size, |size| window.resize(size)) {
713                    self.cx.set_window_size(window.entity, width, height);
714                    self.cx.needs_resize_redraw(window.entity);
715                }
716                window.window().request_redraw();
717
718                #[cfg(target_os = "windows")]
719                {
720                    self.event_manager.flush_events(self.cx.context(), |_| {});
721
722                    self.cx.process_style_updates();
723
724                    if self.cx.process_animations() {
725                        window.window().request_redraw();
726                    }
727
728                    self.cx.process_visual_updates();
729
730                    // #[cfg(feature = "accesskit")]
731
732                    // self.cx.process_tree_updates(|tree_updates| {
733                    //     for update in tree_updates.iter_mut() {
734                    //         self.accesskit_adapter
735                    //             .unwrap()
736                    //             .update_if_active(|| update.take().unwrap());
737                    //     }
738                    // });
739
740                    // for update in self.cx.0.tree_updates.iter_mut() {
741                    //     self.accesskit_adapter
742                    //         .as_mut()
743                    //         .unwrap()
744                    //         .update_if_active(|| update.take().unwrap());
745                    // }
746
747                    // self.cx.0.tree_updates.clear();
748
749                    window.window().request_redraw();
750                }
751            }
752
753            winit::event::WindowEvent::Moved(position) => {
754                let window_entity = window.entity;
755                self.cx.emit_window_event(
756                    window_entity,
757                    WindowEvent::WindowMoved(WindowPosition { x: position.x, y: position.y }),
758                );
759
760                #[cfg(target_os = "windows")]
761                {
762                    self.event_manager.flush_events(self.cx.context(), |_| {});
763
764                    self.cx.process_style_updates();
765
766                    if self.cx.process_animations() {
767                        window.window().request_redraw();
768                    }
769
770                    self.cx.process_visual_updates();
771
772                    // #[cfg(feature = "accesskit")]
773
774                    // self.cx.process_tree_updates(|tree_updates| {
775                    //     for update in tree_updates.iter_mut() {
776                    //         self.accesskit_adapter
777                    //             .unwrap()
778                    //             .update_if_active(|| update.take().unwrap());
779                    //     }
780                    // });
781
782                    // for update in self.cx.0.tree_updates.iter_mut() {
783                    //     self.accesskit_adapter
784                    //         .as_mut()
785                    //         .unwrap()
786                    //         .update_if_active(|| update.take().unwrap());
787                    // }
788
789                    // self.cx.0.tree_updates.clear();
790                }
791            }
792
793            winit::event::WindowEvent::CloseRequested | winit::event::WindowEvent::Destroyed => {
794                let window_entity = window.entity;
795                self.cx.emit_window_event(window_entity, WindowEvent::WindowClose);
796            }
797            winit::event::WindowEvent::DroppedFile(path) => {
798                self.cx.emit_window_event(window.entity, WindowEvent::Drop(DropData::File(path)));
799            }
800
801            winit::event::WindowEvent::HoveredFile(_) => {}
802            winit::event::WindowEvent::HoveredFileCancelled => {}
803            winit::event::WindowEvent::Focused(is_focused) => {
804                self.cx.emit_window_event(window.entity, WindowEvent::WindowFocused(is_focused));
805
806                self.cx.0.window_has_focus = is_focused;
807                // #[cfg(feature = "accesskit")]
808                // accesskit.update_if_active(|| TreeUpdate {
809                //     nodes: vec![],
810                //     tree: None,
811                //     focus: is_focused.then_some(self.cx.focused().accesskit_id()).unwrap_or(NodeId(0)),
812                // });
813            }
814            winit::event::WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
815                let code = match event.physical_key {
816                    PhysicalKey::Code(code) => winit_key_code_to_code(code),
817                    PhysicalKey::Unidentified(native) => match native {
818                        NativeKeyCode::Windows(_scancode) => return,
819                        _ => return,
820                    },
821                };
822
823                let key = match &event.logical_key {
824                    winit::keyboard::Key::Named(named_key) => winit_key_to_key(*named_key),
825                    winit::keyboard::Key::Character(character) => {
826                        Some(vizia_input::Key::Character(character.to_string()))
827                    }
828                    winit::keyboard::Key::Unidentified(_) => {
829                        Some(vizia_input::Key::Named(vizia_input::NamedKey::Unidentified))
830                    }
831                    winit::keyboard::Key::Dead(_) => {
832                        Some(vizia_input::Key::Named(vizia_input::NamedKey::Dead))
833                    }
834                };
835
836                if event.state == ElementState::Pressed {
837                    match &event.logical_key {
838                        winit::keyboard::Key::Character(character) => {
839                            if let Some(character) = character.as_str().chars().next() {
840                                self.cx.emit_window_event(
841                                    window.entity,
842                                    WindowEvent::CharInput(character),
843                                );
844                            }
845                        }
846                        // Some platforms report space as a named key instead of character text.
847                        winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space) => {
848                            self.cx.emit_window_event(window.entity, WindowEvent::CharInput(' '));
849                        }
850                        _ => {}
851                    }
852                }
853
854                let event = match event.state {
855                    winit::event::ElementState::Pressed => WindowEvent::KeyDown(code, key),
856                    winit::event::ElementState::Released => WindowEvent::KeyUp(code, key),
857                };
858
859                self.cx.emit_window_event(window.entity, event);
860            }
861            winit::event::WindowEvent::ModifiersChanged(modifiers) => {
862                self.cx.modifiers().set(Modifiers::SHIFT, modifiers.state().shift_key());
863
864                self.cx.modifiers().set(Modifiers::ALT, modifiers.state().alt_key());
865
866                self.cx.modifiers().set(Modifiers::CTRL, modifiers.state().control_key());
867
868                self.cx.modifiers().set(Modifiers::SUPER, modifiers.state().super_key());
869            }
870            winit::event::WindowEvent::Ime(ime) => match ime {
871                winit::event::Ime::Enabled => {
872                    self.cx.0.set_ime_state(ImeState::StartComposition);
873                    self.cx.emit_window_event(window.entity, WindowEvent::ImeActivate(true));
874                }
875                winit::event::Ime::Preedit(text, cursor) => {
876                    self.cx.0.set_ime_state(ImeState::Composing {
877                        preedit: Some(text.clone()),
878                        cursor_pos: cursor,
879                    });
880                    self.cx.emit_window_event(window.entity, WindowEvent::ImePreedit(text, cursor));
881                }
882                winit::event::Ime::Commit(text) => {
883                    self.cx.0.set_ime_state(ImeState::EndComposition);
884                    self.cx.emit_window_event(window.entity, WindowEvent::ImeCommit(text));
885                }
886                winit::event::Ime::Disabled => {
887                    self.cx.0.set_ime_state(ImeState::Inactive);
888                    self.cx.emit_window_event(window.entity, WindowEvent::ImeActivate(false));
889                }
890            },
891            winit::event::WindowEvent::CursorMoved { device_id: _, position } => {
892                self.cx.emit_window_event(
893                    window.entity,
894                    WindowEvent::MouseMove(position.x as f32, position.y as f32),
895                );
896            }
897            winit::event::WindowEvent::CursorEntered { device_id: _ } => {
898                self.cx.emit_window_event(window.entity, WindowEvent::MouseEnter);
899            }
900            winit::event::WindowEvent::CursorLeft { device_id: _ } => {
901                self.cx.emit_window_event(window.entity, WindowEvent::MouseLeave);
902            }
903            winit::event::WindowEvent::MouseWheel { device_id: _, delta, phase: _ } => {
904                let out_event = match delta {
905                    winit::event::MouseScrollDelta::LineDelta(x, y) => {
906                        WindowEvent::MouseScroll(x, y)
907                    }
908                    winit::event::MouseScrollDelta::PixelDelta(pos) => {
909                        WindowEvent::MouseScroll(
910                            pos.x as f32 / 20.0,
911                            pos.y as f32 / 20.0, // this number calibrated for wayland
912                        )
913                    }
914                };
915
916                self.cx.emit_window_event(window.entity, out_event);
917            }
918            winit::event::WindowEvent::MouseInput { device_id: _, state, button } => {
919                let button = match button {
920                    winit::event::MouseButton::Left => MouseButton::Left,
921                    winit::event::MouseButton::Right => MouseButton::Right,
922                    winit::event::MouseButton::Middle => MouseButton::Middle,
923                    winit::event::MouseButton::Other(val) => MouseButton::Other(val),
924                    winit::event::MouseButton::Back => MouseButton::Back,
925                    winit::event::MouseButton::Forward => MouseButton::Forward,
926                };
927
928                let event = match state {
929                    winit::event::ElementState::Pressed => WindowEvent::MouseDown(button),
930                    winit::event::ElementState::Released => WindowEvent::MouseUp(button),
931                };
932
933                self.cx.emit_window_event(window.entity, event);
934            }
935
936            winit::event::WindowEvent::ScaleFactorChanged {
937                scale_factor,
938                inner_size_writer: _,
939            } => {
940                self.cx.set_scale_factor(scale_factor);
941                self.cx.needs_refresh(window.entity);
942            }
943            winit::event::WindowEvent::ThemeChanged(theme) => {
944                let theme = match theme {
945                    winit::window::Theme::Light => ThemeMode::LightMode,
946                    winit::window::Theme::Dark => ThemeMode::DarkMode,
947                };
948                self.cx.emit_window_event(window.entity, WindowEvent::ThemeChanged(theme));
949            }
950            winit::event::WindowEvent::Occluded(_) => {}
951            winit::event::WindowEvent::RedrawRequested => {
952                let _scope = vizia_core::profiling::scope("draw");
953                window.make_current();
954                if self.cx.draw(window.entity, &mut window.surface, &mut window.dirty_surface) {
955                    window.swap_buffers();
956                }
957
958                // Un-cloak
959                #[cfg(target_os = "windows")]
960                if window.is_initially_cloaked {
961                    window.is_initially_cloaked = false;
962                    set_cloak(window.window(), false);
963                }
964            }
965
966            _ => {}
967        }
968    }
969
970    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
971        if self.custom_cursors.is_empty() {
972            self.custom_cursors = Arc::new(load_default_cursors(event_loop));
973        }
974
975        event_loop.set_control_flow(self.control_flow);
976
977        let update_scope = vizia_core::profiling::scope("update");
978
979        Runtime::drain_pending_work();
980
981        self.event_manager.flush_events(self.cx.context(), |_| {});
982
983        self.cx.process_style_updates();
984
985        if self.cx.process_animations() {
986            for window in self.windows.values() {
987                window.window().request_redraw();
988            }
989        }
990
991        self.cx.process_visual_updates();
992
993        #[cfg(feature = "accesskit")]
994        {
995            self.cx.process_tree_updates();
996
997            if self.adapter_initialized {
998                for update in self.cx.0.tree_updates.iter_mut() {
999                    self.accesskit_adapter
1000                        .as_mut()
1001                        .unwrap()
1002                        .update_if_active(|| update.take().unwrap());
1003                }
1004            }
1005
1006            self.cx.0.tree_updates.clear();
1007        }
1008
1009        if let Some(idle_callback) = &self.on_idle {
1010            self.cx.set_current(Entity::root());
1011            (idle_callback)(self.cx.context());
1012        }
1013        drop(update_scope);
1014
1015        if self.cx.has_queued_events() {
1016            self.event_loop_proxy
1017                .send_event(UserEvent::Event(ProxyEvent::new(())))
1018                .expect("Failed to send event");
1019        }
1020
1021        for window in self.windows.values() {
1022            let needs_redraw = self.cx.0.windows.get(&window.entity).is_some_and(|window_state| {
1023                !window_state.redraw_list.is_empty() || window_state.dirty_rect.is_some()
1024            });
1025            if needs_redraw {
1026                window.window().request_redraw();
1027            }
1028        }
1029
1030        if self.control_flow != ControlFlow::Poll {
1031            if let Some(timer_time) = self.cx.get_next_timer_time() {
1032                event_loop.set_control_flow(ControlFlow::WaitUntil(timer_time));
1033            } else {
1034                event_loop.set_control_flow(ControlFlow::Wait);
1035            }
1036        }
1037
1038        let window_entities = self
1039            .cx
1040            .0
1041            .windows
1042            .iter()
1043            .filter_map(|(entity, state)| state.should_close.then_some(*entity))
1044            .collect::<Vec<_>>();
1045
1046        for window_entity in window_entities {
1047            self.cx.0.remove(window_entity);
1048        }
1049
1050        // Sync OS window state with the logical window map.
1051        self.windows.retain(|_, win| self.cx.0.windows.contains_key(&win.entity));
1052        self.window_ids.retain(|e, _| self.cx.0.windows.contains_key(e));
1053
1054        // Create any logical windows that don't yet have an OS window.
1055        if self.windows.len() != self.cx.0.windows.len() {
1056            for (window_entity, window_state) in self.cx.0.windows.clone().iter() {
1057                if !self.window_ids.contains_key(window_entity) {
1058                    let owner = window_state.owner.and_then(|entity| {
1059                        self.window_ids
1060                            .get(&entity)
1061                            .and_then(|id| self.windows.get(id).map(|ws| ws.window.clone()))
1062                    });
1063
1064                    let window = self
1065                        .create_window(
1066                            event_loop,
1067                            *window_entity,
1068                            &window_state.window_description,
1069                            owner,
1070                        )
1071                        .expect("Failed to create window");
1072
1073                    #[cfg(feature = "accesskit")]
1074                    if self.accesskit_adapter.is_none() {
1075                        self.accesskit_adapter = Some(Adapter::with_event_loop_proxy(
1076                            event_loop,
1077                            &window,
1078                            self.event_loop_proxy.clone(),
1079                        ));
1080                    }
1081
1082                    self.cx.add_main_window(
1083                        *window_entity,
1084                        &window_state.window_description,
1085                        window.scale_factor() as f32,
1086                    );
1087                    window.set_visible(window_state.window_description.visible);
1088
1089                    self.cx.0.with_current(*window_entity, |cx| {
1090                        if let Some(content) = &window_state.content {
1091                            (content)(cx)
1092                        }
1093                    });
1094
1095                    self.cx.mutate_window(*window_entity, |cx, win: &mut Window| {
1096                        win.window = Some(window.clone());
1097                        win.custom_cursors = self.custom_cursors.clone();
1098                        if let Some(callback) = &win.on_create {
1099                            (callback)(&mut EventContext::new_with_current(
1100                                cx.context(),
1101                                *window_entity,
1102                            ));
1103                        }
1104                    });
1105                }
1106            }
1107        }
1108
1109        // Exit when all windows have been closed. The `had_windows` guard prevents
1110        // premature exit at startup for applications that begin without windows —
1111        // the exit only fires after at least one window has been opened and closed.
1112        if self.exit_when_no_windows
1113            && self.had_windows
1114            && self.windows.is_empty()
1115            && self.cx.0.windows.is_empty()
1116        {
1117            event_loop.exit();
1118        }
1119    }
1120
1121    fn new_events(&mut self, _event_loop: &ActiveEventLoop, _cause: winit::event::StartCause) {
1122        // Create the tray icon once the event loop is actually running to prevent issues
1123        // such as https://github.com/tauri-apps/tray-icon/issues/90.
1124        #[cfg(all(
1125            feature = "tray",
1126            not(any(
1127                target_os = "linux",
1128                target_os = "dragonfly",
1129                target_os = "freebsd",
1130                target_os = "netbsd",
1131                target_os = "openbsd"
1132            ))
1133        ))]
1134        if matches!(_cause, winit::event::StartCause::Init) {
1135            self.create_tray_icon();
1136        }
1137
1138        self.cx.process_timers();
1139        self.cx.emit_scheduled_events();
1140    }
1141
1142    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
1143        Runtime::deinit_on_ui_thread();
1144    }
1145}
1146
1147fn apply_window_description(description: &WindowDescription) -> WindowAttributes {
1148    let mut window_attributes = winit::window::Window::default_attributes();
1149
1150    window_attributes = window_attributes.with_title(&description.title).with_inner_size(
1151        LogicalSize::new(description.inner_size.width, description.inner_size.height),
1152    );
1153
1154    if let Some(min_inner_size) = description.min_inner_size {
1155        window_attributes = window_attributes
1156            .with_min_inner_size(LogicalSize::new(min_inner_size.width, min_inner_size.height));
1157    }
1158
1159    if let Some(max_inner_size) = description.max_inner_size {
1160        window_attributes = window_attributes
1161            .with_max_inner_size(LogicalSize::new(max_inner_size.width, max_inner_size.height));
1162    }
1163
1164    if let Some(position) = description.position {
1165        window_attributes =
1166            window_attributes.with_position(LogicalPosition::new(position.x, position.y));
1167    }
1168
1169    window_attributes
1170        .with_resizable(description.resizable)
1171        .with_maximized(description.maximized)
1172        // Accesskit requires that the window start invisible until accesskit is initialized.
1173        .with_visible(false)
1174        .with_window_level(if description.always_on_top {
1175            WindowLevel::AlwaysOnTop
1176        } else {
1177            WindowLevel::Normal
1178        })
1179        .with_transparent(description.transparent)
1180        .with_decorations(description.decorations)
1181        .with_window_icon(description.icon.as_ref().map(|icon| {
1182            winit::window::Icon::from_rgba(
1183                icon.clone(),
1184                description.icon_width,
1185                description.icon_height,
1186            )
1187            .unwrap()
1188        }))
1189        .with_enabled_buttons(
1190            winit::window::WindowButtons::from_bits(description.enabled_window_buttons.bits())
1191                .unwrap(),
1192        )
1193}
1194
1195#[allow(unused_variables)]
1196pub fn load_default_cursors(event_loop: &ActiveEventLoop) -> HashMap<CursorIcon, CustomCursor> {
1197    #[allow(unused_mut)]
1198    let mut custom_cursors = HashMap::new();
1199
1200    #[cfg(target_os = "windows")]
1201    {
1202        let mut load_cursor = |cursor, bytes, x, y| {
1203            custom_cursors.insert(
1204                cursor,
1205                event_loop.create_custom_cursor(
1206                    CustomCursor::from_rgba(bytes, 32, 32, x, y)
1207                        .expect("Failed to create custom cursor"),
1208                ),
1209            );
1210        };
1211
1212        load_cursor(
1213            CursorIcon::Alias, //
1214            include_bytes!("../resources/cursors/windows/aliasb"),
1215            0,
1216            0,
1217        );
1218        load_cursor(
1219            CursorIcon::Cell, //
1220            include_bytes!("../resources/cursors/windows/cell"),
1221            7,
1222            7,
1223        );
1224        load_cursor(
1225            CursorIcon::ColResize,
1226            include_bytes!("../resources/cursors/windows/col_resize"),
1227            10,
1228            8,
1229        );
1230        load_cursor(
1231            CursorIcon::Copy, //
1232            include_bytes!("../resources/cursors/windows/copy"),
1233            0,
1234            0,
1235        );
1236        load_cursor(
1237            CursorIcon::Grab, //
1238            include_bytes!("../resources/cursors/windows/grab"),
1239            6,
1240            0,
1241        );
1242        load_cursor(
1243            CursorIcon::Grabbing, //
1244            include_bytes!("../resources/cursors/windows/grabbing"),
1245            6,
1246            0,
1247        );
1248        load_cursor(
1249            CursorIcon::RowResize, //
1250            include_bytes!("../resources/cursors/windows/row_resize"),
1251            9,
1252            10,
1253        );
1254        load_cursor(
1255            CursorIcon::VerticalText, //
1256            include_bytes!("../resources/cursors/windows/vertical_text"),
1257            9,
1258            3,
1259        );
1260        load_cursor(
1261            CursorIcon::ZoomIn, //
1262            include_bytes!("../resources/cursors/windows/zoom_in"),
1263            6,
1264            6,
1265        );
1266        load_cursor(
1267            CursorIcon::ZoomOut, //
1268            include_bytes!("../resources/cursors/windows/zoom_out"),
1269            6,
1270            6,
1271        );
1272    }
1273
1274    custom_cursors
1275}
1276
1277/// Applies a `Resized` extent through `resize` and returns the window bounds to publish.
1278///
1279/// Returns `None` when `resize` leaves the existing targets untouched (a zero extent), so the
1280/// caller neither sets the window size nor requests a resize redraw.
1281fn resized_bounds(
1282    size: winit::dpi::PhysicalSize<u32>,
1283    resize: impl FnOnce(winit::dpi::PhysicalSize<u32>) -> bool,
1284) -> Option<(f32, f32)> {
1285    resize(size).then_some((size.width as f32, size.height as f32))
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290    use super::*;
1291    use winit::dpi::PhysicalSize;
1292
1293    fn resized_bounds_through_targets(size: PhysicalSize<u32>) -> Option<(f32, f32)> {
1294        resized_bounds(size, |size| {
1295            crate::window::resize_targets(size, |_, _| {}, |_| ()).is_some()
1296        })
1297    }
1298
1299    #[test]
1300    fn resized_bounds_skips_zero_extent() {
1301        for extent in
1302            [PhysicalSize::new(0, 1480), PhysicalSize::new(2320, 0), PhysicalSize::new(0, 0)]
1303        {
1304            assert_eq!(resized_bounds_through_targets(extent), None);
1305        }
1306    }
1307
1308    #[test]
1309    fn resized_bounds_publishes_non_zero_extent() {
1310        assert_eq!(
1311            resized_bounds_through_targets(PhysicalSize::new(2320, 1480)),
1312            Some((2320.0, 1480.0))
1313        );
1314    }
1315}