i_slint_backend_winit/
event_loop.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4#![warn(missing_docs)]
5/*!
6    This module contains the event loop implementation using winit, as well as the
7    [WindowAdapter] trait used by the generated code and the run-time to change
8    aspects of windows on the screen.
9*/
10use crate::drag_resize_window::{handle_cursor_move_for_resize, handle_resize};
11use crate::winitwindowadapter::WindowVisibility;
12use crate::EventResult;
13use crate::{SharedBackendData, SlintEvent};
14use corelib::graphics::euclid;
15use corelib::input::{KeyEvent, KeyEventType, MouseEvent};
16use corelib::items::{ColorScheme, PointerEventButton};
17use corelib::lengths::LogicalPoint;
18use corelib::platform::PlatformError;
19use corelib::window::*;
20use i_slint_core as corelib;
21
22#[allow(unused_imports)]
23use std::cell::{RefCell, RefMut};
24use std::rc::Rc;
25use winit::event::WindowEvent;
26use winit::event_loop::ActiveEventLoop;
27use winit::event_loop::ControlFlow;
28use winit::window::ResizeDirection;
29
30/// This enum captures run-time specific events that can be dispatched to the event loop in
31/// addition to the winit events.
32pub enum CustomEvent {
33    /// On wasm request_redraw doesn't wake the event loop, so we need to manually send an event
34    /// so that the event loop can run
35    #[cfg(target_arch = "wasm32")]
36    WakeEventLoopWorkaround,
37    /// Slint internal: Invoke the
38    UserEvent(Box<dyn FnOnce() + Send>),
39    Exit,
40    #[cfg(enable_accesskit)]
41    Accesskit(accesskit_winit::Event),
42    #[cfg(muda)]
43    Muda(muda::MenuEvent),
44}
45
46impl std::fmt::Debug for CustomEvent {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        match self {
49            #[cfg(target_arch = "wasm32")]
50            Self::WakeEventLoopWorkaround => write!(f, "WakeEventLoopWorkaround"),
51            Self::UserEvent(_) => write!(f, "UserEvent"),
52            Self::Exit => write!(f, "Exit"),
53            #[cfg(enable_accesskit)]
54            Self::Accesskit(a) => write!(f, "AccessKit({a:?})"),
55            #[cfg(muda)]
56            Self::Muda(e) => write!(f, "Muda({e:?})"),
57        }
58    }
59}
60
61pub struct EventLoopState {
62    shared_backend_data: Rc<SharedBackendData>,
63    // last seen cursor position
64    cursor_pos: LogicalPoint,
65    pressed: bool,
66    current_touch_id: Option<u64>,
67
68    loop_error: Option<PlatformError>,
69    current_resize_direction: Option<ResizeDirection>,
70
71    /// Set to true when pumping events for the shortest amount of time possible.
72    pumping_events_instantly: bool,
73
74    custom_application_handler: Option<Box<dyn crate::CustomApplicationHandler>>,
75}
76
77impl EventLoopState {
78    pub fn new(
79        shared_backend_data: Rc<SharedBackendData>,
80        custom_application_handler: Option<Box<dyn crate::CustomApplicationHandler>>,
81    ) -> Self {
82        Self {
83            shared_backend_data,
84            cursor_pos: Default::default(),
85            pressed: Default::default(),
86            current_touch_id: Default::default(),
87            loop_error: Default::default(),
88            current_resize_direction: Default::default(),
89            pumping_events_instantly: Default::default(),
90            custom_application_handler,
91        }
92    }
93
94    /// Free graphics resources for any hidden windows. Called when quitting the event loop, to work
95    /// around #8795.
96    fn suspend_all_hidden_windows(&self) {
97        let windows_to_suspend = self
98            .shared_backend_data
99            .active_windows
100            .borrow()
101            .values()
102            .filter_map(|w| w.upgrade())
103            .filter(|w| matches!(w.visibility(), WindowVisibility::Hidden))
104            .collect::<Vec<_>>();
105        for window in windows_to_suspend.into_iter() {
106            let _ = window.suspend();
107        }
108    }
109}
110
111impl winit::application::ApplicationHandler<SlintEvent> for EventLoopState {
112    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
113        if matches!(
114            self.custom_application_handler
115                .as_mut()
116                .map_or(EventResult::Propagate, |handler| { handler.resumed(event_loop) }),
117            EventResult::PreventDefault
118        ) {
119            return;
120        }
121        if let Err(err) = self.shared_backend_data.create_inactive_windows(event_loop) {
122            self.loop_error = Some(err);
123            event_loop.exit();
124        }
125    }
126
127    fn window_event(
128        &mut self,
129        event_loop: &ActiveEventLoop,
130        window_id: winit::window::WindowId,
131        event: WindowEvent,
132    ) {
133        let Some(window) = self.shared_backend_data.window_by_id(window_id) else {
134            if let Some(handler) = self.custom_application_handler.as_mut() {
135                handler.window_event(event_loop, window_id, None, None, &event);
136            }
137            return;
138        };
139
140        if let Some(winit_window) = window.winit_window() {
141            if matches!(
142                self.custom_application_handler.as_mut().map_or(
143                    EventResult::Propagate,
144                    |handler| handler.window_event(
145                        event_loop,
146                        window_id,
147                        Some(&*winit_window),
148                        Some(window.window()),
149                        &event
150                    )
151                ),
152                EventResult::PreventDefault
153            ) {
154                return;
155            }
156
157            if let Some(mut window_event_filter) = window.window_event_filter.take() {
158                let event_result = window_event_filter(window.window(), &event);
159                window.window_event_filter.set(Some(window_event_filter));
160
161                match event_result {
162                    EventResult::PreventDefault => return,
163                    EventResult::Propagate => (),
164                }
165            }
166
167            #[cfg(enable_accesskit)]
168            window
169                .accesskit_adapter()
170                .expect("internal error: accesskit adapter must exist when window exists")
171                .borrow_mut()
172                .process_event(&winit_window, &event);
173        } else {
174            return;
175        }
176
177        let runtime_window = WindowInner::from_pub(window.window());
178        match event {
179            WindowEvent::RedrawRequested => {
180                self.loop_error = window.draw().err();
181            }
182            WindowEvent::Resized(size) => {
183                self.loop_error = window.resize_event(size).err();
184
185                // Entering fullscreen, maximizing or minimizing the window will
186                // trigger a resize event. We need to update the internal window
187                // state to match the actual window state. We simulate a "window
188                // state event" since there is not an official event for it yet.
189                // Because we don't always get a Resized event (eg, minimized), also handle Occluded
190                // See: https://github.com/rust-windowing/winit/issues/2334
191                window.window_state_event();
192            }
193            WindowEvent::CloseRequested => {
194                self.loop_error = window
195                    .window()
196                    .try_dispatch_event(corelib::platform::WindowEvent::CloseRequested)
197                    .err();
198            }
199            WindowEvent::Focused(have_focus) => {
200                // Work around https://github.com/rust-windowing/winit/issues/4371
201                let have_focus = if cfg!(target_os = "macos") {
202                    window.winit_window().map_or(have_focus, |w| w.has_focus())
203                } else {
204                    have_focus
205                };
206                self.loop_error = window.activation_changed(have_focus).err();
207            }
208
209            WindowEvent::KeyboardInput { event, is_synthetic, .. } => {
210                let key_code = event.logical_key;
211                // For now: Match Qt's behavior of mapping command to control and control to meta (LWin/RWin).
212                let swap_cmd_ctrl = i_slint_core::is_apple_platform();
213
214                let key_code = if swap_cmd_ctrl {
215                    match key_code {
216                        winit::keyboard::Key::Named(winit::keyboard::NamedKey::Control) => {
217                            winit::keyboard::Key::Named(winit::keyboard::NamedKey::Super)
218                        }
219                        winit::keyboard::Key::Named(winit::keyboard::NamedKey::Super) => {
220                            winit::keyboard::Key::Named(winit::keyboard::NamedKey::Control)
221                        }
222                        code => code,
223                    }
224                } else {
225                    key_code
226                };
227
228                macro_rules! winit_key_to_char {
229                ($($char:literal # $name:ident # $($_qt:ident)|* # $($winit:ident $(($pos:ident))?)|* # $($_xkb:ident)|*;)*) => {
230                    match &key_code {
231                        $($(winit::keyboard::Key::Named(winit::keyboard::NamedKey::$winit) $(if event.location == winit::keyboard::KeyLocation::$pos)? => $char.into(),)*)*
232                        winit::keyboard::Key::Character(str) => str.as_str().into(),
233                        _ => {
234                            if let Some(text) = &event.text {
235                                text.as_str().into()
236                            } else {
237                                return;
238                            }
239                        }
240                    }
241                }
242            }
243                let text = i_slint_common::for_each_special_keys!(winit_key_to_char);
244
245                self.loop_error = window
246                    .window()
247                    .try_dispatch_event(match event.state {
248                        winit::event::ElementState::Pressed if event.repeat => {
249                            corelib::platform::WindowEvent::KeyPressRepeated { text }
250                        }
251                        winit::event::ElementState::Pressed => {
252                            if is_synthetic {
253                                // Synthetic event are sent when the focus is acquired, for all the keys currently pressed.
254                                // Don't forward these keys other than modifiers to the app
255                                use winit::keyboard::{Key::Named, NamedKey as N};
256                                if !matches!(
257                                    key_code,
258                                    Named(N::Control | N::Shift | N::Super | N::Alt | N::AltGraph),
259                                ) {
260                                    return;
261                                }
262                            }
263                            corelib::platform::WindowEvent::KeyPressed { text }
264                        }
265                        winit::event::ElementState::Released => {
266                            corelib::platform::WindowEvent::KeyReleased { text }
267                        }
268                    })
269                    .err();
270            }
271            WindowEvent::Ime(winit::event::Ime::Preedit(string, preedit_selection)) => {
272                let event = KeyEvent {
273                    event_type: KeyEventType::UpdateComposition,
274                    preedit_text: string.into(),
275                    preedit_selection: preedit_selection.map(|e| e.0 as i32..e.1 as i32),
276                    ..Default::default()
277                };
278                runtime_window.process_key_input(event);
279            }
280            WindowEvent::Ime(winit::event::Ime::Commit(string)) => {
281                let event = KeyEvent {
282                    event_type: KeyEventType::CommitComposition,
283                    text: string.into(),
284                    ..Default::default()
285                };
286                runtime_window.process_key_input(event);
287            }
288            WindowEvent::CursorMoved { position, .. } => {
289                self.current_resize_direction = handle_cursor_move_for_resize(
290                    &window.winit_window().unwrap(),
291                    position,
292                    self.current_resize_direction,
293                    runtime_window
294                        .window_item()
295                        .map_or(0_f64, |w| w.as_pin_ref().resize_border_width().get().into()),
296                );
297                let position = position.to_logical(runtime_window.scale_factor() as f64);
298                self.cursor_pos = euclid::point2(position.x, position.y);
299                runtime_window.process_mouse_input(MouseEvent::Moved { position: self.cursor_pos });
300            }
301            WindowEvent::CursorLeft { .. } => {
302                // On the html canvas, we don't get the mouse move or release event when outside the canvas. So we have no choice but canceling the event
303                if cfg!(target_arch = "wasm32") || !self.pressed {
304                    self.pressed = false;
305                    runtime_window.process_mouse_input(MouseEvent::Exit);
306                }
307            }
308            WindowEvent::MouseWheel { delta, .. } => {
309                let (delta_x, delta_y) = match delta {
310                    winit::event::MouseScrollDelta::LineDelta(lx, ly) => (lx * 60., ly * 60.),
311                    winit::event::MouseScrollDelta::PixelDelta(d) => {
312                        let d = d.to_logical(runtime_window.scale_factor() as f64);
313                        (d.x, d.y)
314                    }
315                };
316                runtime_window.process_mouse_input(MouseEvent::Wheel {
317                    position: self.cursor_pos,
318                    delta_x,
319                    delta_y,
320                });
321            }
322            WindowEvent::MouseInput { state, button, .. } => {
323                let button = match button {
324                    winit::event::MouseButton::Left => PointerEventButton::Left,
325                    winit::event::MouseButton::Right => PointerEventButton::Right,
326                    winit::event::MouseButton::Middle => PointerEventButton::Middle,
327                    winit::event::MouseButton::Back => PointerEventButton::Back,
328                    winit::event::MouseButton::Forward => PointerEventButton::Forward,
329                    winit::event::MouseButton::Other(_) => PointerEventButton::Other,
330                };
331                let ev = match state {
332                    winit::event::ElementState::Pressed => {
333                        if button == PointerEventButton::Left
334                            && self.current_resize_direction.is_some()
335                        {
336                            handle_resize(
337                                &window.winit_window().unwrap(),
338                                self.current_resize_direction,
339                            );
340                            return;
341                        }
342
343                        self.pressed = true;
344                        MouseEvent::Pressed { position: self.cursor_pos, button, click_count: 0 }
345                    }
346                    winit::event::ElementState::Released => {
347                        self.pressed = false;
348                        MouseEvent::Released { position: self.cursor_pos, button, click_count: 0 }
349                    }
350                };
351                runtime_window.process_mouse_input(ev);
352            }
353            WindowEvent::Touch(touch) => {
354                if Some(touch.id) == self.current_touch_id || self.current_touch_id.is_none() {
355                    let location = touch.location.to_logical(runtime_window.scale_factor() as f64);
356                    let position = euclid::point2(location.x, location.y);
357                    let ev = match touch.phase {
358                        winit::event::TouchPhase::Started => {
359                            self.pressed = true;
360                            if self.current_touch_id.is_none() {
361                                self.current_touch_id = Some(touch.id);
362                            }
363                            MouseEvent::Pressed {
364                                position,
365                                button: PointerEventButton::Left,
366                                click_count: 0,
367                            }
368                        }
369                        winit::event::TouchPhase::Ended | winit::event::TouchPhase::Cancelled => {
370                            self.pressed = false;
371                            self.current_touch_id = None;
372                            MouseEvent::Released {
373                                position,
374                                button: PointerEventButton::Left,
375                                click_count: 0,
376                            }
377                        }
378                        winit::event::TouchPhase::Moved => MouseEvent::Moved { position },
379                    };
380                    runtime_window.process_mouse_input(ev);
381                }
382            }
383            WindowEvent::ScaleFactorChanged { scale_factor, inner_size_writer: _ } => {
384                if std::env::var("SLINT_SCALE_FACTOR").is_err() {
385                    self.loop_error = window
386                        .window()
387                        .try_dispatch_event(corelib::platform::WindowEvent::ScaleFactorChanged {
388                            scale_factor: scale_factor as f32,
389                        })
390                        .err();
391                    // TODO: send a resize event or try to keep the logical size the same.
392                    //window.resize_event(inner_size_writer.???)?;
393                }
394            }
395            WindowEvent::ThemeChanged(theme) => window.set_color_scheme(match theme {
396                winit::window::Theme::Dark => ColorScheme::Dark,
397                winit::window::Theme::Light => ColorScheme::Light,
398            }),
399            WindowEvent::Occluded(x) => {
400                window.renderer.occluded(x);
401
402                // In addition to the hack done for WindowEvent::Resize, also do it for Occluded so we handle Minimized change
403                window.window_state_event();
404            }
405            _ => {}
406        }
407
408        if self.loop_error.is_some() {
409            event_loop.exit();
410        }
411    }
412
413    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: SlintEvent) {
414        match event.0 {
415            CustomEvent::UserEvent(user_callback) => user_callback(),
416            CustomEvent::Exit => {
417                self.suspend_all_hidden_windows();
418                event_loop.exit()
419            }
420            #[cfg(enable_accesskit)]
421            CustomEvent::Accesskit(accesskit_winit::Event { window_id, window_event }) => {
422                if let Some(window) = self.shared_backend_data.window_by_id(window_id) {
423                    let deferred_action = window
424                        .accesskit_adapter()
425                        .expect("internal error: accesskit adapter must exist when window exists")
426                        .borrow_mut()
427                        .process_accesskit_event(window_event);
428                    // access kit adapter not borrowed anymore, now invoke the deferred action
429                    if let Some(deferred_action) = deferred_action {
430                        deferred_action.invoke(window.window());
431                    }
432                }
433            }
434            #[cfg(target_arch = "wasm32")]
435            CustomEvent::WakeEventLoopWorkaround => {
436                event_loop.set_control_flow(ControlFlow::Poll);
437            }
438            #[cfg(muda)]
439            CustomEvent::Muda(event) => {
440                if let Some((window, eid, muda_type)) =
441                    event.id().0.split_once('|').and_then(|(w, e)| {
442                        let (e, muda_type) = e.split_once('|')?;
443                        Some((
444                            self.shared_backend_data.window_by_id(
445                                winit::window::WindowId::from(w.parse::<u64>().ok()?),
446                            )?,
447                            e.parse::<usize>().ok()?,
448                            muda_type.parse::<crate::muda::MudaType>().ok()?,
449                        ))
450                    })
451                {
452                    window.muda_event(eid, muda_type);
453                };
454            }
455        }
456    }
457
458    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
459        if matches!(
460            self.custom_application_handler.as_mut().map_or(EventResult::Propagate, |handler| {
461                handler.new_events(event_loop, cause)
462            }),
463            EventResult::PreventDefault
464        ) {
465            return;
466        }
467
468        event_loop.set_control_flow(ControlFlow::Wait);
469
470        corelib::platform::update_timers_and_animations();
471    }
472
473    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
474        if matches!(
475            self.custom_application_handler
476                .as_mut()
477                .map_or(EventResult::Propagate, |handler| { handler.about_to_wait(event_loop) }),
478            EventResult::PreventDefault
479        ) {
480            return;
481        }
482
483        if let Err(err) = self.shared_backend_data.create_inactive_windows(event_loop) {
484            self.loop_error = Some(err);
485        }
486
487        if !event_loop.exiting() {
488            for w in self
489                .shared_backend_data
490                .active_windows
491                .borrow()
492                .iter()
493                .filter_map(|(_, w)| w.upgrade())
494            {
495                if w.window().has_active_animations() {
496                    w.request_redraw();
497                }
498            }
499        }
500
501        if event_loop.control_flow() == ControlFlow::Wait {
502            if let Some(next_timer) = corelib::platform::duration_until_next_timer_update() {
503                event_loop.set_control_flow(ControlFlow::wait_duration(next_timer));
504            }
505        }
506
507        if self.pumping_events_instantly {
508            event_loop.set_control_flow(ControlFlow::Poll);
509        }
510    }
511
512    fn device_event(
513        &mut self,
514        event_loop: &ActiveEventLoop,
515        device_id: winit::event::DeviceId,
516        event: winit::event::DeviceEvent,
517    ) {
518        if let Some(handler) = self.custom_application_handler.as_mut() {
519            handler.device_event(event_loop, device_id, event);
520        }
521    }
522
523    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
524        if let Some(handler) = self.custom_application_handler.as_mut() {
525            handler.suspended(event_loop);
526        }
527    }
528
529    fn exiting(&mut self, event_loop: &ActiveEventLoop) {
530        if let Some(handler) = self.custom_application_handler.as_mut() {
531            handler.exiting(event_loop);
532        }
533    }
534
535    fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
536        if let Some(handler) = self.custom_application_handler.as_mut() {
537            handler.memory_warning(event_loop);
538        }
539    }
540}
541
542impl EventLoopState {
543    /// Runs the event loop and renders the items in the provided `component` in its
544    /// own window.
545    #[allow(unused_mut)] // mut need changes for wasm
546    pub fn run(mut self) -> Result<Self, corelib::platform::PlatformError> {
547        let not_running_loop_instance = self
548            .shared_backend_data
549            .not_running_event_loop
550            .take()
551            .ok_or_else(|| PlatformError::from("Nested event loops are not supported"))?;
552        let mut winit_loop = not_running_loop_instance;
553
554        cfg_if::cfg_if! {
555            if #[cfg(any(target_arch = "wasm32", ios_and_friends))] {
556                winit_loop
557                    .run_app(&mut self)
558                    .map_err(|e| format!("Error running winit event loop: {e}"))?;
559                // This can't really happen, as run() doesn't return
560                Ok(Self::new(self.shared_backend_data.clone(), None))
561            } else {
562                use winit::platform::run_on_demand::EventLoopExtRunOnDemand as _;
563                winit_loop
564                    .run_app_on_demand(&mut self)
565                    .map_err(|e| format!("Error running winit event loop: {e}"))?;
566
567                // Keep the EventLoop instance alive and re-use it in future invocations of run_event_loop().
568                // Winit does not support creating multiple instances of the event loop.
569                self.shared_backend_data.not_running_event_loop.replace(Some(winit_loop));
570
571                if let Some(error) = self.loop_error {
572                    return Err(error);
573                }
574                Ok(self)
575            }
576        }
577    }
578
579    /// Runs the event loop and renders the items in the provided `component` in its
580    /// own window.
581    #[cfg(all(not(target_arch = "wasm32"), not(ios_and_friends)))]
582    pub fn pump_events(
583        mut self,
584        timeout: Option<std::time::Duration>,
585    ) -> Result<(Self, winit::platform::pump_events::PumpStatus), corelib::platform::PlatformError>
586    {
587        use winit::platform::pump_events::EventLoopExtPumpEvents;
588
589        let not_running_loop_instance = self
590            .shared_backend_data
591            .not_running_event_loop
592            .take()
593            .ok_or_else(|| PlatformError::from("Nested event loops are not supported"))?;
594        let mut winit_loop = not_running_loop_instance;
595
596        self.pumping_events_instantly = timeout.is_some_and(|duration| duration.is_zero());
597
598        let result = winit_loop.pump_app_events(timeout, &mut self);
599
600        self.pumping_events_instantly = false;
601
602        // Keep the EventLoop instance alive and re-use it in future invocations of run_event_loop().
603        // Winit does not support creating multiple instances of the event loop.
604        self.shared_backend_data.not_running_event_loop.replace(Some(winit_loop));
605
606        if let Some(error) = self.loop_error {
607            return Err(error);
608        }
609        Ok((self, result))
610    }
611
612    #[cfg(target_arch = "wasm32")]
613    pub fn spawn(self) -> Result<(), corelib::platform::PlatformError> {
614        use winit::platform::web::EventLoopExtWebSys;
615        let not_running_loop_instance = self
616            .shared_backend_data
617            .not_running_event_loop
618            .take()
619            .ok_or_else(|| PlatformError::from("Nested event loops are not supported"))?;
620
621        not_running_loop_instance.spawn_app(self);
622
623        Ok(())
624    }
625}