Struct winit::event_loop::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
impl ActiveEventLoop
sourcepub fn create_window(
&self,
window_attributes: WindowAttributes,
) -> Result<Window, OsError>
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?
More examples
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
fn main() -> Result<(), impl std::error::Error> {
use std::collections::HashMap;
use winit::dpi::{LogicalPosition, LogicalSize, Position};
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::raw_window_handle::HasRawWindowHandle;
use winit::window::Window;
#[path = "util/fill.rs"]
mod fill;
fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
let parent = parent.raw_window_handle().unwrap();
let mut window_attributes = Window::default_attributes()
.with_title("child window")
.with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
.with_visible(true);
// `with_parent_window` is unsafe. Parent window must be a valid window.
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
event_loop.create_window(window_attributes).unwrap()
}
let mut windows = HashMap::new();
let event_loop: EventLoop<()> = EventLoop::new().unwrap();
let mut parent_window_id = None;
event_loop.run(move |event: Event<()>, event_loop| {
match event {
Event::Resumed => {
let attributes = Window::default_attributes()
.with_title("parent window")
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
let window = event_loop.create_window(attributes).unwrap();
parent_window_id = Some(window.id());
println!("Parent window id: {parent_window_id:?})");
windows.insert(window.id(), window);
},
Event::WindowEvent { window_id, event } => match event {
WindowEvent::CloseRequested => {
windows.clear();
event_loop.exit();
},
WindowEvent::CursorEntered { device_id: _ } => {
// On x11, println when the cursor entered in a window even if the child window
// is created by some key inputs.
// the child windows are always placed at (0, 0) with size (200, 200) in the
// parent window, so we also can see this log when we move
// the cursor around (200, 200) in parent window.
println!("cursor entered in the window {window_id:?}");
},
WindowEvent::KeyboardInput {
event: KeyEvent { state: ElementState::Pressed, .. },
..
} => {
let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
let child_window = spawn_child_window(parent_window, event_loop);
let child_id = child_window.id();
println!("Child window created with id: {child_id:?}");
windows.insert(child_id, child_window);
},
WindowEvent::RedrawRequested => {
if let Some(window) = windows.get(&window_id) {
fill::fill_window(window);
}
},
_ => (),
},
_ => (),
}
})
}
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
fn create_window(
&mut self,
event_loop: &ActiveEventLoop,
_tab_id: Option<String>,
) -> Result<WindowId, Box<dyn Error>> {
// TODO read-out activation token.
#[allow(unused_mut)]
let mut window_attributes = Window::default_attributes()
.with_title("Winit window")
.with_transparent(true)
.with_window_icon(Some(self.icon.clone()));
#[cfg(any(x11_platform, wayland_platform))]
if let Some(token) = event_loop.read_token_from_env() {
startup_notify::reset_activation_token_env();
info!("Using token {:?} to activate a window", token);
window_attributes = window_attributes.with_activation_token(token);
}
#[cfg(macos_platform)]
if let Some(tab_id) = _tab_id {
window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
}
#[cfg(web_platform)]
{
use winit::platform::web::WindowAttributesExtWebSys;
window_attributes = window_attributes.with_append(true);
}
let window = event_loop.create_window(window_attributes)?;
#[cfg(ios_platform)]
{
use winit::platform::ios::WindowExtIOS;
window.recognize_doubletap_gesture(true);
window.recognize_pinch_gesture(true);
window.recognize_rotation_gesture(true);
window.recognize_pan_gesture(true, 2, 2);
}
let window_state = WindowState::new(self, window)?;
let window_id = window_state.window.id();
info!("Created new window with id={window_id:?}");
self.windows.insert(window_id, window_state);
Ok(window_id)
}
sourcepub fn create_custom_cursor(
&self,
custom_cursor: CustomCursorSource,
) -> CustomCursor
pub fn create_custom_cursor( &self, custom_cursor: CustomCursorSource, ) -> CustomCursor
Create custom cursor.
sourcepub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle>
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle>
Returns the list of all the monitors available on the system.
Examples found in repository?
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
info!("Monitors information");
let primary_monitor = event_loop.primary_monitor();
for monitor in event_loop.available_monitors() {
let intro = if primary_monitor.as_ref() == Some(&monitor) {
"Primary monitor"
} else {
"Monitor"
};
if let Some(name) = monitor.name() {
info!("{intro}: {name}");
} else {
info!("{intro}: [no name]");
}
let PhysicalSize { width, height } = monitor.size();
info!(
" Current mode: {width}x{height}{}",
if let Some(m_hz) = monitor.refresh_rate_millihertz() {
format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
} else {
String::new()
}
);
let PhysicalPosition { x, y } = monitor.position();
info!(" Position: {x},{y}");
info!(" Scale factor: {}", monitor.scale_factor());
info!(" Available modes (width x height x bit-depth):");
for mode in monitor.video_modes() {
let PhysicalSize { width, height } = mode.size();
let bits = mode.bit_depth();
let m_hz = mode.refresh_rate_millihertz();
info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
}
}
}
sourcepub fn primary_monitor(&self) -> Option<MonitorHandle>
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?
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
info!("Monitors information");
let primary_monitor = event_loop.primary_monitor();
for monitor in event_loop.available_monitors() {
let intro = if primary_monitor.as_ref() == Some(&monitor) {
"Primary monitor"
} else {
"Monitor"
};
if let Some(name) = monitor.name() {
info!("{intro}: {name}");
} else {
info!("{intro}: [no name]");
}
let PhysicalSize { width, height } = monitor.size();
info!(
" Current mode: {width}x{height}{}",
if let Some(m_hz) = monitor.refresh_rate_millihertz() {
format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
} else {
String::new()
}
);
let PhysicalPosition { x, y } = monitor.position();
info!(" Position: {x},{y}");
info!(" Scale factor: {}", monitor.scale_factor());
info!(" Available modes (width x height x bit-depth):");
for mode in monitor.video_modes() {
let PhysicalSize { width, height } = mode.size();
let bits = mode.bit_depth();
let m_hz = mode.refresh_rate_millihertz();
info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
}
}
}
sourcepub fn listen_device_events(&self, allowed: DeviceEvents)
pub fn listen_device_events(&self, allowed: DeviceEvents)
Change if or when DeviceEvent
s 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.
sourcepub fn system_theme(&self) -> Option<Theme>
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.
sourcepub fn set_control_flow(&self, control_flow: ControlFlow)
pub fn set_control_flow(&self, control_flow: ControlFlow)
Sets the ControlFlow
.
Examples found in repository?
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
if self.request_redraw && !self.wait_cancelled && !self.close_requested {
self.window.as_ref().unwrap().request_redraw();
}
match self.mode {
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
Mode::WaitUntil => {
if !self.wait_cancelled {
event_loop
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
}
},
Mode::Poll => {
thread::sleep(POLL_SLEEP_TIME);
event_loop.set_control_flow(ControlFlow::Poll);
},
};
if self.close_requested {
event_loop.exit();
}
}
sourcepub fn control_flow(&self) -> ControlFlow
pub fn control_flow(&self) -> ControlFlow
Gets the current ControlFlow
.
sourcepub fn exit(&self)
pub fn exit(&self)
This exits the event loop.
See LoopExiting
.
Examples found in repository?
More examples
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: WindowId,
event: WindowEvent,
) {
println!("{event:?}");
let window = match self.window.as_ref() {
Some(window) => window,
None => return,
};
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::RedrawRequested => {
fill::fill_window(window);
window.request_redraw();
},
_ => (),
}
}
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
if self.request_redraw && !self.wait_cancelled && !self.close_requested {
self.window.as_ref().unwrap().request_redraw();
}
match self.mode {
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
Mode::WaitUntil => {
if !self.wait_cancelled {
event_loop
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
}
},
Mode::Poll => {
thread::sleep(POLL_SLEEP_TIME);
event_loop.set_control_flow(ControlFlow::Poll);
},
};
if self.close_requested {
event_loop.exit();
}
}
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
window_id: WindowId,
event: WindowEvent,
) {
if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
println!(
"--------------------------------------------------------- Window {} Destroyed",
self.idx
);
self.window_id = None;
event_loop.exit();
return;
}
let window = match self.window.as_mut() {
Some(window) => window,
None => return,
};
match event {
WindowEvent::CloseRequested => {
println!(
"--------------------------------------------------------- Window {} \
CloseRequested",
self.idx
);
fill::cleanup_window(window);
self.window = None;
},
WindowEvent::RedrawRequested => {
fill::fill_window(window);
},
_ => (),
}
}
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
fn main() -> Result<(), impl std::error::Error> {
use std::collections::HashMap;
use winit::dpi::{LogicalPosition, LogicalSize, Position};
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::raw_window_handle::HasRawWindowHandle;
use winit::window::Window;
#[path = "util/fill.rs"]
mod fill;
fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
let parent = parent.raw_window_handle().unwrap();
let mut window_attributes = Window::default_attributes()
.with_title("child window")
.with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
.with_visible(true);
// `with_parent_window` is unsafe. Parent window must be a valid window.
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
event_loop.create_window(window_attributes).unwrap()
}
let mut windows = HashMap::new();
let event_loop: EventLoop<()> = EventLoop::new().unwrap();
let mut parent_window_id = None;
event_loop.run(move |event: Event<()>, event_loop| {
match event {
Event::Resumed => {
let attributes = Window::default_attributes()
.with_title("parent window")
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
let window = event_loop.create_window(attributes).unwrap();
parent_window_id = Some(window.id());
println!("Parent window id: {parent_window_id:?})");
windows.insert(window.id(), window);
},
Event::WindowEvent { window_id, event } => match event {
WindowEvent::CloseRequested => {
windows.clear();
event_loop.exit();
},
WindowEvent::CursorEntered { device_id: _ } => {
// On x11, println when the cursor entered in a window even if the child window
// is created by some key inputs.
// the child windows are always placed at (0, 0) with size (200, 200) in the
// parent window, so we also can see this log when we move
// the cursor around (200, 200) in parent window.
println!("cursor entered in the window {window_id:?}");
},
WindowEvent::KeyboardInput {
event: KeyEvent { state: ElementState::Pressed, .. },
..
} => {
let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
let child_window = spawn_child_window(parent_window, event_loop);
let child_id = child_window.id();
println!("Child window created with id: {child_id:?}");
windows.insert(child_id, child_window);
},
WindowEvent::RedrawRequested => {
if let Some(window) = windows.get(&window_id) {
fill::fill_window(window);
}
},
_ => (),
},
_ => (),
}
})
}
sourcepub fn owned_display_handle(&self) -> OwnedDisplayHandle
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 ActiveEventLoopExtAndroid for ActiveEventLoop
Available on android_platform
only.
impl ActiveEventLoopExtAndroid for ActiveEventLoop
android_platform
only.source§fn android_app(&self) -> &AndroidApp
fn android_app(&self) -> &AndroidApp
AndroidApp
] which was used to create this event loop.source§impl ActiveEventLoopExtMacOS for ActiveEventLoop
Available on macos_platform
only.
impl ActiveEventLoopExtMacOS for ActiveEventLoop
macos_platform
only.source§fn hide_application(&self)
fn hide_application(&self)
source§fn hide_other_applications(&self)
fn hide_other_applications(&self)
source§fn set_allows_automatic_window_tabbing(&self, enabled: bool)
fn set_allows_automatic_window_tabbing(&self, enabled: bool)
source§fn allows_automatic_window_tabbing(&self) -> bool
fn allows_automatic_window_tabbing(&self) -> bool
source§impl ActiveEventLoopExtWayland for ActiveEventLoop
Available on wayland_platform
only.
impl ActiveEventLoopExtWayland for ActiveEventLoop
wayland_platform
only.source§fn is_wayland(&self) -> bool
fn is_wayland(&self) -> bool
ActiveEventLoop
uses Wayland.source§impl ActiveEventLoopExtWebSys for ActiveEventLoop
Available on web_platform
only.
impl ActiveEventLoopExtWebSys for ActiveEventLoop
web_platform
only.source§fn create_custom_cursor_async(
&self,
source: CustomCursorSource,
) -> CustomCursorFuture ⓘ
fn create_custom_cursor_async( &self, source: CustomCursorSource, ) -> CustomCursorFuture ⓘ
ActiveEventLoop::create_custom_cursor()
which waits until the
cursor has completely finished loading.source§fn set_poll_strategy(&self, strategy: PollStrategy)
fn set_poll_strategy(&self, strategy: PollStrategy)
ControlFlow::Poll
. Read moresource§fn poll_strategy(&self) -> PollStrategy
fn poll_strategy(&self) -> PollStrategy
ControlFlow::Poll
. Read moresource§fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy)
fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy)
ControlFlow::WaitUntil
. Read moresource§fn wait_until_strategy(&self) -> WaitUntilStrategy
fn wait_until_strategy(&self) -> WaitUntilStrategy
ControlFlow::WaitUntil
. Read moresource§impl ActiveEventLoopExtX11 for ActiveEventLoop
Available on x11_platform
only.
impl ActiveEventLoopExtX11 for ActiveEventLoop
x11_platform
only.source§fn is_x11(&self) -> bool
fn is_x11(&self) -> bool
ActiveEventLoop
uses X11.source§impl Debug for ActiveEventLoop
impl Debug for ActiveEventLoop
source§impl EventLoopExtStartupNotify for ActiveEventLoop
Available on x11_platform
or wayland_platform
only.
impl EventLoopExtStartupNotify for ActiveEventLoop
x11_platform
or wayland_platform
only.source§fn read_token_from_env(&self) -> Option<ActivationToken>
fn read_token_from_env(&self) -> Option<ActivationToken>
source§impl HasDisplayHandle for ActiveEventLoop
Available on crate feature rwh_06
only.
impl HasDisplayHandle for ActiveEventLoop
rwh_06
only.source§fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError>
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError>
source§impl HasRawDisplayHandle for ActiveEventLoop
Available on crate feature rwh_05
only.
impl HasRawDisplayHandle for ActiveEventLoop
rwh_05
only.source§fn raw_display_handle(&self) -> RawDisplayHandle
fn raw_display_handle(&self) -> RawDisplayHandle
Returns a rwh_05::RawDisplayHandle
for the event loop.
Auto Trait Implementations§
impl Freeze for ActiveEventLoop
impl !RefUnwindSafe for ActiveEventLoop
impl !Send for ActiveEventLoop
impl !Sync for ActiveEventLoop
impl Unpin for ActiveEventLoop
impl !UnwindSafe for ActiveEventLoop
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> HasRawDisplayHandle for Twhere
T: HasDisplayHandle + ?Sized,
impl<T> HasRawDisplayHandle for Twhere
T: HasDisplayHandle + ?Sized,
source§fn raw_display_handle(&self) -> Result<RawDisplayHandle, HandleError>
fn raw_display_handle(&self) -> Result<RawDisplayHandle, HandleError>
HasDisplayHandle
instead