cart_tmp_winit/
event_loop.rs

1//! The `EventLoop` struct and assorted supporting types, including `ControlFlow`.
2//!
3//! If you want to send custom events to the event loop, use [`EventLoop::create_proxy()`][create_proxy]
4//! to acquire an [`EventLoopProxy`][event_loop_proxy] and call its [`send_event`][send_event] method.
5//!
6//! See the root-level documentation for information on how to create and use an event loop to
7//! handle events.
8//!
9//! [create_proxy]: crate::event_loop::EventLoop::create_proxy
10//! [event_loop_proxy]: crate::event_loop::EventLoopProxy
11//! [send_event]: crate::event_loop::EventLoopProxy::send_event
12use instant::Instant;
13use std::ops::Deref;
14use std::{error, fmt};
15
16use crate::{event::Event, monitor::MonitorHandle, platform_impl};
17
18/// Provides a way to retrieve events from the system and from the windows that were registered to
19/// the events loop.
20///
21/// An `EventLoop` can be seen more or less as a "context". Calling `EventLoop::new()`
22/// initializes everything that will be required to create windows. For example on Linux creating
23/// an event loop opens a connection to the X or Wayland server.
24///
25/// To wake up an `EventLoop` from a another thread, see the `EventLoopProxy` docs.
26///
27/// Note that the `EventLoop` cannot be shared across threads (due to platform-dependant logic
28/// forbidding it), as such it is neither `Send` nor `Sync`. If you need cross-thread access, the
29/// `Window` created from this `EventLoop` _can_ be sent to an other thread, and the
30/// `EventLoopProxy` allows you to wake up an `EventLoop` from another thread.
31///
32pub struct EventLoop<T: 'static> {
33    pub(crate) event_loop: platform_impl::EventLoop<T>,
34    pub(crate) _marker: ::std::marker::PhantomData<*mut ()>, // Not Send nor Sync
35}
36
37/// Target that associates windows with an `EventLoop`.
38///
39/// This type exists to allow you to create new windows while Winit executes
40/// your callback. `EventLoop` will coerce into this type (`impl<T> Deref for
41/// EventLoop<T>`), so functions that take this as a parameter can also take
42/// `&EventLoop`.
43pub struct EventLoopWindowTarget<T: 'static> {
44    pub(crate) p: platform_impl::EventLoopWindowTarget<T>,
45    pub(crate) _marker: ::std::marker::PhantomData<*mut ()>, // Not Send nor Sync
46}
47
48impl<T> fmt::Debug for EventLoop<T> {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.pad("EventLoop { .. }")
51    }
52}
53
54impl<T> fmt::Debug for EventLoopWindowTarget<T> {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.pad("EventLoopWindowTarget { .. }")
57    }
58}
59
60/// Set by the user callback given to the `EventLoop::run` method.
61///
62/// Indicates the desired behavior of the event loop after [`Event::RedrawEventsCleared`][events_cleared]
63/// is emitted. Defaults to `Poll`.
64///
65/// ## Persistency
66/// Almost every change is persistent between multiple calls to the event loop closure within a
67/// given run loop. The only exception to this is `Exit` which, once set, cannot be unset. Changes
68/// are **not** persistent between multiple calls to `run_return` - issuing a new call will reset
69/// the control flow to `Poll`.
70///
71/// [events_cleared]: crate::event::Event::RedrawEventsCleared
72#[derive(Copy, Clone, Debug, PartialEq, Eq)]
73pub enum ControlFlow {
74    /// When the current loop iteration finishes, immediately begin a new iteration regardless of
75    /// whether or not new events are available to process. For web, events are sent when
76    /// `requestAnimationFrame` fires.
77    Poll,
78    /// When the current loop iteration finishes, suspend the thread until another event arrives.
79    Wait,
80    /// When the current loop iteration finishes, suspend the thread until either another event
81    /// arrives or the given time is reached.
82    WaitUntil(Instant),
83    /// Send a `LoopDestroyed` event and stop the event loop. This variant is *sticky* - once set,
84    /// `control_flow` cannot be changed from `Exit`, and any future attempts to do so will result
85    /// in the `control_flow` parameter being reset to `Exit`.
86    Exit,
87}
88
89impl Default for ControlFlow {
90    #[inline(always)]
91    fn default() -> ControlFlow {
92        ControlFlow::Poll
93    }
94}
95
96impl EventLoop<()> {
97    /// Builds a new event loop with a `()` as the user event type.
98    ///
99    /// ***For cross-platform compatibility, the `EventLoop` must be created on the main thread.***
100    /// Attempting to create the event loop on a different thread will panic. This restriction isn't
101    /// strictly necessary on all platforms, but is imposed to eliminate any nasty surprises when
102    /// porting to platforms that require it. `EventLoopExt::new_any_thread` functions are exposed
103    /// in the relevant `platform` module if the target platform supports creating an event loop on
104    /// any thread.
105    ///
106    /// Usage will result in display backend initialisation, this can be controlled on linux
107    /// using an environment variable `WINIT_UNIX_BACKEND`. Legal values are `x11` and `wayland`.
108    /// If it is not set, winit will try to connect to a wayland connection, and if it fails will
109    /// fallback on x11. If this variable is set with any other value, winit will panic.
110    ///
111    /// ## Platform-specific
112    ///
113    /// - **iOS:** Can only be called on the main thread.
114    pub fn new() -> EventLoop<()> {
115        EventLoop::<()>::with_user_event()
116    }
117}
118
119impl<T> EventLoop<T> {
120    /// Builds a new event loop.
121    ///
122    /// All caveats documented in [`EventLoop::new`] apply to this function.
123    ///
124    /// ## Platform-specific
125    ///
126    /// - **iOS:** Can only be called on the main thread.
127    pub fn with_user_event() -> EventLoop<T> {
128        EventLoop {
129            event_loop: platform_impl::EventLoop::new(),
130            _marker: ::std::marker::PhantomData,
131        }
132    }
133
134    /// Hijacks the calling thread and initializes the winit event loop with the provided
135    /// closure. Since the closure is `'static`, it must be a `move` closure if it needs to
136    /// access any data from the calling context.
137    ///
138    /// See the [`ControlFlow`] docs for information on how changes to `&mut ControlFlow` impact the
139    /// event loop's behavior.
140    ///
141    /// Any values not passed to this function will *not* be dropped.
142    ///
143    /// [`ControlFlow`]: crate::event_loop::ControlFlow
144    #[inline]
145    pub fn run<F>(self, event_handler: F) -> !
146    where
147        F: 'static + FnMut(Event<'_, T>, &EventLoopWindowTarget<T>, &mut ControlFlow),
148    {
149        self.event_loop.run(event_handler)
150    }
151
152    /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
153    pub fn create_proxy(&self) -> EventLoopProxy<T> {
154        EventLoopProxy {
155            event_loop_proxy: self.event_loop.create_proxy(),
156        }
157    }
158}
159
160impl<T> Deref for EventLoop<T> {
161    type Target = EventLoopWindowTarget<T>;
162    fn deref(&self) -> &EventLoopWindowTarget<T> {
163        self.event_loop.window_target()
164    }
165}
166
167impl<T> EventLoopWindowTarget<T> {
168    /// Returns the list of all the monitors available on the system.
169    #[inline]
170    pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
171        self.p
172            .available_monitors()
173            .into_iter()
174            .map(|inner| MonitorHandle { inner })
175    }
176
177    /// Returns the primary monitor of the system.
178    #[inline]
179    pub fn primary_monitor(&self) -> MonitorHandle {
180        MonitorHandle {
181            inner: self.p.primary_monitor(),
182        }
183    }
184}
185
186/// Used to send custom events to `EventLoop`.
187pub struct EventLoopProxy<T: 'static> {
188    event_loop_proxy: platform_impl::EventLoopProxy<T>,
189}
190
191impl<T: 'static> Clone for EventLoopProxy<T> {
192    fn clone(&self) -> Self {
193        Self {
194            event_loop_proxy: self.event_loop_proxy.clone(),
195        }
196    }
197}
198
199impl<T: 'static> EventLoopProxy<T> {
200    /// Send an event to the `EventLoop` from which this proxy was created. This emits a
201    /// `UserEvent(event)` event in the event loop, where `event` is the value passed to this
202    /// function.
203    ///
204    /// Returns an `Err` if the associated `EventLoop` no longer exists.
205    pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
206        self.event_loop_proxy.send_event(event)
207    }
208}
209
210impl<T: 'static> fmt::Debug for EventLoopProxy<T> {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.pad("EventLoopProxy { .. }")
213    }
214}
215
216/// The error that is returned when an `EventLoopProxy` attempts to wake up an `EventLoop` that
217/// no longer exists. Contains the original event given to `send_event`.
218#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
219pub struct EventLoopClosed<T>(pub T);
220
221impl<T> fmt::Display for EventLoopClosed<T> {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        f.write_str("Tried to wake up a closed `EventLoop`")
224    }
225}
226
227impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {}