Skip to main content

EventLoop

Struct EventLoop 

Source
pub struct EventLoop { /* private fields */ }
Expand description

Provides a way to retrieve events from the system and from the windows that were registered to the events loop.

An EventLoop can be seen more or less as a “context”. Calling EventLoop::new initializes everything that will be required to create windows. For example on Linux creating an event loop opens a connection to the X or Wayland server.

To wake up an EventLoop from a another thread, see the EventLoopProxy docs.

Note that this cannot be shared across threads (due to platform-dependant logic forbidding it), as such it is neither Send nor Sync. If you need cross-thread access, the Window created from this can be sent to an other thread, and the EventLoopProxy allows you to wake up an EventLoop from another thread.

Implementations§

Source§

impl EventLoop

Source

pub fn new() -> Result<EventLoop, EventLoopError>

Create the event loop.

This is an alias of EventLoop::builder().build().

Source

pub fn builder() -> EventLoopBuilder

Start building a new event loop.

This returns an EventLoopBuilder, to allow configuring the event loop before creation.

To get the actual event loop, call build on that.

Source

pub fn run_app<A>(self, app: A) -> Result<(), EventLoopError>
where A: ApplicationHandler + 'static,

Run the event loop with the given application on the calling thread.

The app is dropped when the event loop is shut down.

§Event loop flow

This function internally handles the different parts of a traditional event-handling loop. You can imagine this method as being implemented like this:

let mut start_cause = StartCause::Init;

// Run the event loop.
while !event_loop.exiting() {
    // Wake up.
    app.new_events(event_loop, start_cause);

    // Indicate that surfaces can now safely be created.
    if start_cause == StartCause::Init {
        app.can_create_surfaces(event_loop);
    }

    // Handle proxy wake-up event.
    if event_loop.proxy_wake_up_set() {
        event_loop.proxy_wake_up_clear();
        app.proxy_wake_up(event_loop);
    }

    // Handle actions done by the user / system such as moving the cursor, resizing the
    // window, changing the window theme, etc.
    for event in event_loop.events() {
        match event {
            window event => app.window_event(event_loop, window_id, event),
            device event => app.device_event(event_loop, device_id, event),
        }
    }

    // Handle redraws.
    for window_id in event_loop.pending_redraws() {
        app.window_event(event_loop, window_id, WindowEvent::RedrawRequested);
    }

    // Done handling events, wait until we're woken up again.
    app.about_to_wait(event_loop);
    start_cause = event_loop.wait_if_necessary();
}

// Finished running, drop application state.
drop(app);

This is of course a very coarse-grained overview, and leaves out timing details like ControlFlow::WaitUntil and life-cycle methods like ApplicationHandler::resumed, but it should give you an idea of how things fit together.

§Returns

The semantics of this function can be a bit confusing, because the way different platforms control their event loop varies significantly.

On most platforms (Android, macOS, Orbital, X11, Wayland, Windows), this blocks the caller, runs the event loop internally, and then returns once ActiveEventLoop::exit is called. See run_app_on_demand for more detailed semantics.

On iOS, this will register the application handler, and then call UIApplicationMain (which is the only way to run the system event loop), which never returns to the caller (the process instead exits after the handler has been dropped). See also run_app_never_return.

On the web, this works by registering the application handler, and then immediately returning to the caller. This is necessary because WebAssembly (and JavaScript) is always executed in the context of the browser’s own (internal) event loop, and thus we need to return to avoid blocking that and allow events to later be delivered asynchronously. See also register_app.

If you call this function inside fn main, you usually do not need to think about these details.

§Static

To alleviate the issues noted above, this function requires that you pass in a 'static handler, to ensure that any state your application uses will be alive as long as the application is running.

To be clear, you should avoid doing e.g. event_loop.run_app(&mut app)?, and prefer event_loop.run_app(app)? instead.

If this requirement is prohibitive for you, consider using run_app_on_demand instead (though note that this is not available on iOS and web).

Source

pub fn create_proxy(&self) -> EventLoopProxy

Creates an EventLoopProxy that can be used to dispatch user events to the main event loop, possibly from another thread.

Source

pub fn owned_display_handle(&self) -> OwnedDisplayHandle

Gets a persistent reference to the underlying platform display.

See the OwnedDisplayHandle type for more information.

Source

pub fn listen_device_events(&self, allowed: DeviceEvents)

Change if or when DeviceEvents are captured.

See ActiveEventLoop::listen_device_events for details.

Source

pub fn set_control_flow(&self, control_flow: ControlFlow)

Sets the ControlFlow.

Source

pub fn create_custom_cursor( &self, custom_cursor: CustomCursorSource, ) -> Result<CustomCursor, RequestError>

Create custom cursor.

§Platform-specific

iOS / Android / Orbital: Unsupported.

Trait Implementations§

Source§

impl AsFd for EventLoop

Available on x11_platform or wayland_platform only.
Source§

fn as_fd(&self) -> BorrowedFd<'_>

Get the underlying EventLoop’s fd which you can register into other event loop, like calloop or mio. When doing so, the loop must be polled with the pump_app_events API.

Source§

impl AsRawFd for EventLoop

Available on x11_platform or wayland_platform only.
Source§

fn as_raw_fd(&self) -> i32

Get the underlying EventLoop’s raw fd which you can register into other event loop, like calloop or mio. When doing so, the loop must be polled with the pump_app_events API.

Source§

impl Debug for EventLoop

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl EventLoopExtPumpEvents for EventLoop

Available on windows_platform or macos_platform or android_platform or x11_platform or wayland_platform or docsrs only.
Source§

fn pump_app_events<A>( &mut self, timeout: Option<Duration>, app: A, ) -> PumpStatus

Pump the EventLoop to check for and dispatch pending events. Read more
Source§

impl EventLoopExtRunOnDemand for EventLoop

Available on windows_platform or macos_platform or android_platform or orbital_platform or x11_platform or wayland_platform or docsrs only.
Source§

fn run_app_on_demand<A>(&mut self, app: A) -> Result<(), EventLoopError>

Run the application with the event loop on the calling thread. Read more
Source§

impl EventLoopExtWayland for EventLoop

Available on wayland_platform only.
Source§

fn is_wayland(&self) -> bool

True if the EventLoop uses Wayland.
Source§

impl EventLoopExtX11 for EventLoop

Available on x11_platform only.
Source§

fn is_x11(&self) -> bool

True if the EventLoop uses X11.
Source§

impl HasDisplayHandle for EventLoop

Source§

fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError>

Get a handle to the display controller of the windowing system.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> HasRawDisplayHandle for T
where T: HasDisplayHandle + ?Sized,

Source§

fn raw_display_handle(&self) -> Result<RawDisplayHandle, HandleError>

👎Deprecated:

Use HasDisplayHandle instead

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsSource for T
where T: AsFd,

Source§

fn source(&self) -> BorrowedFd<'_>

Returns the borrowed file descriptor.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeBoxed<Box<T>> for T

Source§

fn maybe_boxed(self) -> Box<T>

Convert
Source§

impl<T> MaybeBoxed<T> for T

Source§

fn maybe_boxed(self) -> T

Convert
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,