Struct ActiveEventLoop

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

Target that associates windows with an EventLoop.

This type exists to allow you to create new windows while Winit executes your callback.

Implementations§

Source§

impl ActiveEventLoop

Source

pub fn create_window( &self, window_attributes: WindowAttributes, ) -> Result<Window, OsError>

Create the window.

Possible causes of error include denied permission, incompatible system, and lack of memory.

§Platform-specific
  • Web: The window is created but not inserted into the web page automatically. Please see the web platform module for more information.
Examples found in repository?
examples/pump_events.rs (line 34)
31        fn resumed(&mut self, event_loop: &ActiveEventLoop) {
32            let window_attributes =
33                Window::default_attributes().with_title("A fantastic window!");
34            self.window = Some(event_loop.create_window(window_attributes).unwrap());
35        }
More examples
Hide additional examples
examples/control_flow.rs (line 74)
70    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
71        let window_attributes = Window::default_attributes().with_title(
72            "Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
73        );
74        self.window = Some(event_loop.create_window(window_attributes).unwrap());
75    }
examples/run_on_demand.rs (line 35)
31        fn resumed(&mut self, event_loop: &ActiveEventLoop) {
32            let window_attributes = Window::default_attributes()
33                .with_title("Fantastic window number one!")
34                .with_inner_size(rio_window::dpi::LogicalSize::new(128.0, 128.0));
35            let window = event_loop.create_window(window_attributes).unwrap();
36            self.window_id = Some(window.id());
37            self.window = Some(window);
38        }
examples/child_window.rs (line 25)
3fn main() -> Result<(), impl std::error::Error> {
4    use std::collections::HashMap;
5
6    use rio_window::dpi::{LogicalPosition, LogicalSize, Position};
7    use rio_window::event::{ElementState, Event, KeyEvent, WindowEvent};
8    use rio_window::event_loop::{ActiveEventLoop, EventLoop};
9    use rio_window::raw_window_handle::HasRawWindowHandle;
10    use rio_window::window::Window;
11
12    #[path = "util/fill.rs"]
13    mod fill;
14
15    fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
16        let parent = parent.raw_window_handle().unwrap();
17        let mut window_attributes = Window::default_attributes()
18            .with_title("child window")
19            .with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
20            .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
21            .with_visible(true);
22        // `with_parent_window` is unsafe. Parent window must be a valid window.
23        window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
24
25        event_loop.create_window(window_attributes).unwrap()
26    }
27
28    let mut windows = HashMap::new();
29
30    let event_loop: EventLoop<()> = EventLoop::new().unwrap();
31    let mut parent_window_id = None;
32
33    event_loop.run(move |event: Event<()>, event_loop| {
34        match event {
35            Event::Resumed => {
36                let attributes = Window::default_attributes()
37                    .with_title("parent window")
38                    .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
39                    .with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
40                let window = event_loop.create_window(attributes).unwrap();
41
42                parent_window_id = Some(window.id());
43
44                println!("Parent window id: {parent_window_id:?})");
45                windows.insert(window.id(), window);
46            }
47            Event::WindowEvent { window_id, event } => match event {
48                WindowEvent::CloseRequested => {
49                    windows.clear();
50                    event_loop.exit();
51                }
52                WindowEvent::CursorEntered { device_id: _ } => {
53                    // On x11, println when the cursor entered in a window even if the child window
54                    // is created by some key inputs.
55                    // the child windows are always placed at (0, 0) with size (200, 200) in the
56                    // parent window, so we also can see this log when we move
57                    // the cursor around (200, 200) in parent window.
58                    println!("cursor entered in the window {window_id:?}");
59                }
60                WindowEvent::KeyboardInput {
61                    event:
62                        KeyEvent {
63                            state: ElementState::Pressed,
64                            ..
65                        },
66                    ..
67                } => {
68                    let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
69                    let child_window = spawn_child_window(parent_window, event_loop);
70                    let child_id = child_window.id();
71                    println!("Child window created with id: {child_id:?}");
72                    windows.insert(child_id, child_window);
73                }
74                WindowEvent::RedrawRequested => {
75                    if let Some(window) = windows.get(&window_id) {
76                        fill::fill_window(window);
77                    }
78                }
79                _ => (),
80            },
81            _ => (),
82        }
83    })
84}
examples/window.rs (line 162)
131    fn create_window(
132        &mut self,
133        event_loop: &ActiveEventLoop,
134        _tab_id: Option<String>,
135    ) -> Result<WindowId, Box<dyn Error>> {
136        // TODO read-out activation token.
137
138        #[allow(unused_mut)]
139        let mut window_attributes = Window::default_attributes()
140            .with_title("Winit window")
141            .with_transparent(true)
142            .with_window_icon(Some(self.icon.clone()));
143
144        #[cfg(any(x11_platform, wayland_platform))]
145        if let Some(token) = event_loop.read_token_from_env() {
146            startup_notify::reset_activation_token_env();
147            info!("Using token {:?} to activate a window", token);
148            window_attributes = window_attributes.with_activation_token(token);
149        }
150
151        #[cfg(macos_platform)]
152        if let Some(tab_id) = _tab_id {
153            window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
154        }
155
156        #[cfg(web_platform)]
157        {
158            use rio_window::platform::web::WindowAttributesExtWebSys;
159            window_attributes = window_attributes.with_append(true);
160        }
161
162        let window = event_loop.create_window(window_attributes)?;
163
164        #[cfg(ios_platform)]
165        {
166            use rio_window::platform::ios::WindowExtIOS;
167            window.recognize_doubletap_gesture(true);
168            window.recognize_pinch_gesture(true);
169            window.recognize_rotation_gesture(true);
170            window.recognize_pan_gesture(true, 2, 2);
171        }
172
173        let window_state = WindowState::new(self, window)?;
174        let window_id = window_state.window.id();
175        info!("Created new window with id={window_id:?}");
176        self.windows.insert(window_id, window_state);
177        Ok(window_id)
178    }
Source

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

Create custom cursor.

Source

pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle>

Returns the list of all the monitors available on the system.

Examples found in repository?
examples/window.rs (line 242)
239    fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
240        info!("Monitors information");
241        let primary_monitor = event_loop.primary_monitor();
242        for monitor in event_loop.available_monitors() {
243            let intro = if primary_monitor.as_ref() == Some(&monitor) {
244                "Primary monitor"
245            } else {
246                "Monitor"
247            };
248
249            if let Some(name) = monitor.name() {
250                info!("{intro}: {name}");
251            } else {
252                info!("{intro}: [no name]");
253            }
254
255            let PhysicalSize { width, height } = monitor.size();
256            info!(
257                "  Current mode: {width}x{height}{}",
258                if let Some(m_hz) = monitor.refresh_rate_millihertz() {
259                    format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
260                } else {
261                    String::new()
262                }
263            );
264
265            let PhysicalPosition { x, y } = monitor.position();
266            info!("  Position: {x},{y}");
267
268            info!("  Scale factor: {}", monitor.scale_factor());
269
270            info!("  Available modes (width x height x bit-depth):");
271            for mode in monitor.video_modes() {
272                let PhysicalSize { width, height } = mode.size();
273                let bits = mode.bit_depth();
274                let m_hz = mode.refresh_rate_millihertz();
275                info!(
276                    "    {width}x{height}x{bits} @ {}.{} Hz",
277                    m_hz / 1000,
278                    m_hz % 1000
279                );
280            }
281        }
282    }
Source

pub fn primary_monitor(&self) -> Option<MonitorHandle>

Returns the primary monitor of the system.

Returns None if it can’t identify any monitor as a primary one.

§Platform-specific

Wayland / Web: Always returns None.

Examples found in repository?
examples/window.rs (line 241)
239    fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
240        info!("Monitors information");
241        let primary_monitor = event_loop.primary_monitor();
242        for monitor in event_loop.available_monitors() {
243            let intro = if primary_monitor.as_ref() == Some(&monitor) {
244                "Primary monitor"
245            } else {
246                "Monitor"
247            };
248
249            if let Some(name) = monitor.name() {
250                info!("{intro}: {name}");
251            } else {
252                info!("{intro}: [no name]");
253            }
254
255            let PhysicalSize { width, height } = monitor.size();
256            info!(
257                "  Current mode: {width}x{height}{}",
258                if let Some(m_hz) = monitor.refresh_rate_millihertz() {
259                    format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
260                } else {
261                    String::new()
262                }
263            );
264
265            let PhysicalPosition { x, y } = monitor.position();
266            info!("  Position: {x},{y}");
267
268            info!("  Scale factor: {}", monitor.scale_factor());
269
270            info!("  Available modes (width x height x bit-depth):");
271            for mode in monitor.video_modes() {
272                let PhysicalSize { width, height } = mode.size();
273                let bits = mode.bit_depth();
274                let m_hz = mode.refresh_rate_millihertz();
275                info!(
276                    "    {width}x{height}x{bits} @ {}.{} Hz",
277                    m_hz / 1000,
278                    m_hz % 1000
279                );
280            }
281        }
282    }
Source

pub fn listen_device_events(&self, allowed: DeviceEvents)

Change if or when DeviceEvents are captured.

Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, winit will ignore them by default for unfocused windows on Linux/BSD. This method allows changing this at runtime to explicitly capture them again.

§Platform-specific
  • Wayland / macOS / iOS / Android / Orbital: Unsupported.
Source

pub fn system_theme(&self) -> Option<Theme>

Returns the current system theme.

Returns None if it cannot be determined on the current platform.

§Platform-specific
  • iOS / Android / Wayland / x11 / Orbital: Unsupported.
Source

pub fn set_control_flow(&self, control_flow: ControlFlow)

Sets the ControlFlow.

Examples found in repository?
examples/control_flow.rs (line 136)
130    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
131        if self.request_redraw && !self.wait_cancelled && !self.close_requested {
132            self.window.as_ref().unwrap().request_redraw();
133        }
134
135        match self.mode {
136            Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
137            Mode::WaitUntil => {
138                if !self.wait_cancelled {
139                    event_loop.set_control_flow(ControlFlow::WaitUntil(
140                        time::Instant::now() + WAIT_TIME,
141                    ));
142                }
143            }
144            Mode::Poll => {
145                thread::sleep(POLL_SLEEP_TIME);
146                event_loop.set_control_flow(ControlFlow::Poll);
147            }
148        };
149
150        if self.close_requested {
151            event_loop.exit();
152        }
153    }
Source

pub fn control_flow(&self) -> ControlFlow

Gets the current ControlFlow.

Source

pub fn exit(&self)

This exits the event loop.

See LoopExiting.

Examples found in repository?
examples/window.rs (line 506)
503    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
504        if self.windows.is_empty() {
505            info!("No windows left, exiting...");
506            event_loop.exit();
507        }
508    }
More examples
Hide additional examples
examples/pump_events.rs (line 51)
37        fn window_event(
38            &mut self,
39            event_loop: &ActiveEventLoop,
40            _window_id: WindowId,
41            event: WindowEvent,
42        ) {
43            println!("{event:?}");
44
45            let window = match self.window.as_ref() {
46                Some(window) => window,
47                None => return,
48            };
49
50            match event {
51                WindowEvent::CloseRequested => event_loop.exit(),
52                WindowEvent::RedrawRequested => {
53                    fill::fill_window(window);
54                    window.request_redraw();
55                }
56                _ => (),
57            }
58        }
examples/control_flow.rs (line 151)
130    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
131        if self.request_redraw && !self.wait_cancelled && !self.close_requested {
132            self.window.as_ref().unwrap().request_redraw();
133        }
134
135        match self.mode {
136            Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
137            Mode::WaitUntil => {
138                if !self.wait_cancelled {
139                    event_loop.set_control_flow(ControlFlow::WaitUntil(
140                        time::Instant::now() + WAIT_TIME,
141                    ));
142                }
143            }
144            Mode::Poll => {
145                thread::sleep(POLL_SLEEP_TIME);
146                event_loop.set_control_flow(ControlFlow::Poll);
147            }
148        };
149
150        if self.close_requested {
151            event_loop.exit();
152        }
153    }
examples/run_on_demand.rs (line 52)
40        fn window_event(
41            &mut self,
42            event_loop: &ActiveEventLoop,
43            window_id: WindowId,
44            event: WindowEvent,
45        ) {
46            if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
47                println!(
48                    "--------------------------------------------------------- Window {} Destroyed",
49                    self.idx
50                );
51                self.window_id = None;
52                event_loop.exit();
53                return;
54            }
55
56            let window = match self.window.as_mut() {
57                Some(window) => window,
58                None => return,
59            };
60
61            match event {
62                WindowEvent::CloseRequested => {
63                    println!(
64                        "--------------------------------------------------------- Window {} \
65                         CloseRequested",
66                        self.idx
67                    );
68                    fill::cleanup_window(window);
69                    self.window = None;
70                }
71                WindowEvent::RedrawRequested => {
72                    fill::fill_window(window);
73                }
74                _ => (),
75            }
76        }
examples/child_window.rs (line 50)
3fn main() -> Result<(), impl std::error::Error> {
4    use std::collections::HashMap;
5
6    use rio_window::dpi::{LogicalPosition, LogicalSize, Position};
7    use rio_window::event::{ElementState, Event, KeyEvent, WindowEvent};
8    use rio_window::event_loop::{ActiveEventLoop, EventLoop};
9    use rio_window::raw_window_handle::HasRawWindowHandle;
10    use rio_window::window::Window;
11
12    #[path = "util/fill.rs"]
13    mod fill;
14
15    fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
16        let parent = parent.raw_window_handle().unwrap();
17        let mut window_attributes = Window::default_attributes()
18            .with_title("child window")
19            .with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
20            .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
21            .with_visible(true);
22        // `with_parent_window` is unsafe. Parent window must be a valid window.
23        window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
24
25        event_loop.create_window(window_attributes).unwrap()
26    }
27
28    let mut windows = HashMap::new();
29
30    let event_loop: EventLoop<()> = EventLoop::new().unwrap();
31    let mut parent_window_id = None;
32
33    event_loop.run(move |event: Event<()>, event_loop| {
34        match event {
35            Event::Resumed => {
36                let attributes = Window::default_attributes()
37                    .with_title("parent window")
38                    .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
39                    .with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
40                let window = event_loop.create_window(attributes).unwrap();
41
42                parent_window_id = Some(window.id());
43
44                println!("Parent window id: {parent_window_id:?})");
45                windows.insert(window.id(), window);
46            }
47            Event::WindowEvent { window_id, event } => match event {
48                WindowEvent::CloseRequested => {
49                    windows.clear();
50                    event_loop.exit();
51                }
52                WindowEvent::CursorEntered { device_id: _ } => {
53                    // On x11, println when the cursor entered in a window even if the child window
54                    // is created by some key inputs.
55                    // the child windows are always placed at (0, 0) with size (200, 200) in the
56                    // parent window, so we also can see this log when we move
57                    // the cursor around (200, 200) in parent window.
58                    println!("cursor entered in the window {window_id:?}");
59                }
60                WindowEvent::KeyboardInput {
61                    event:
62                        KeyEvent {
63                            state: ElementState::Pressed,
64                            ..
65                        },
66                    ..
67                } => {
68                    let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
69                    let child_window = spawn_child_window(parent_window, event_loop);
70                    let child_id = child_window.id();
71                    println!("Child window created with id: {child_id:?}");
72                    windows.insert(child_id, child_window);
73                }
74                WindowEvent::RedrawRequested => {
75                    if let Some(window) = windows.get(&window_id) {
76                        fill::fill_window(window);
77                    }
78                }
79                _ => (),
80            },
81            _ => (),
82        }
83    })
84}
Source

pub fn exiting(&self) -> bool

Returns if the EventLoop is about to stop.

See exit().

Source

pub fn owned_display_handle(&self) -> OwnedDisplayHandle

Gets a persistent reference to the underlying platform display.

See the OwnedDisplayHandle type for more information.

Trait Implementations§

Source§

impl ActiveEventLoopExtMacOS for ActiveEventLoop

Source§

fn hide_application(&self)

Hide the entire application. In most applications this is typically triggered with Command-H.
Source§

fn hide_other_applications(&self)

Hide the other applications. In most applications this is typically triggered with Command+Option-H.
Source§

fn set_allows_automatic_window_tabbing(&self, enabled: bool)

Set whether the system can automatically organize windows into tabs. Read more
Source§

fn allows_automatic_window_tabbing(&self) -> bool

Returns whether the system can automatically organize windows into tabs.
Source§

impl ActiveEventLoopExtWayland for ActiveEventLoop

Source§

fn is_wayland(&self) -> bool

True if the ActiveEventLoop uses Wayland.
Source§

impl ActiveEventLoopExtWebSys for ActiveEventLoop

Source§

fn create_custom_cursor_async( &self, source: CustomCursorSource, ) -> CustomCursorFuture

Async version of ActiveEventLoop::create_custom_cursor() which waits until the cursor has completely finished loading.
Source§

fn set_poll_strategy(&self, strategy: PollStrategy)

Sets the strategy for ControlFlow::Poll. Read more
Source§

fn poll_strategy(&self) -> PollStrategy

Gets the strategy for ControlFlow::Poll. Read more
Source§

impl ActiveEventLoopExtX11 for ActiveEventLoop

Source§

fn is_x11(&self) -> bool

True if the ActiveEventLoop uses X11.
Source§

impl Debug for ActiveEventLoop

Source§

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

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

impl EventLoopExtStartupNotify for ActiveEventLoop

Source§

fn read_token_from_env(&self) -> Option<ActivationToken>

Read the token from the environment. Read more
Source§

impl HasDisplayHandle for ActiveEventLoop

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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, 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> AutoreleaseSafe for T
where T: ?Sized,