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
3fn main() -> Result<(), impl std::error::Error> {
4 use std::collections::HashMap;
5
6 use winit::dpi::{LogicalPosition, LogicalSize, Position};
7 use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
8 use winit::event_loop::{ActiveEventLoop, EventLoop};
9 use winit::raw_window_handle::HasRawWindowHandle;
10 use winit::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: KeyEvent { state: ElementState::Pressed, .. },
62 ..
63 } => {
64 let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
65 let child_window = spawn_child_window(parent_window, event_loop);
66 let child_id = child_window.id();
67 println!("Child window created with id: {child_id:?}");
68 windows.insert(child_id, child_window);
69 },
70 WindowEvent::RedrawRequested => {
71 if let Some(window) = windows.get(&window_id) {
72 fill::fill_window(window);
73 }
74 },
75 _ => (),
76 },
77 _ => (),
78 }
79 })
80}125 fn create_window(
126 &mut self,
127 event_loop: &ActiveEventLoop,
128 _tab_id: Option<String>,
129 ) -> Result<WindowId, Box<dyn Error>> {
130 // TODO read-out activation token.
131
132 #[allow(unused_mut)]
133 let mut window_attributes = Window::default_attributes()
134 .with_title("Winit window")
135 .with_transparent(true)
136 .with_window_icon(Some(self.icon.clone()));
137
138 #[cfg(any(x11_platform, wayland_platform))]
139 if let Some(token) = event_loop.read_token_from_env() {
140 startup_notify::reset_activation_token_env();
141 info!("Using token {:?} to activate a window", token);
142 window_attributes = window_attributes.with_activation_token(token);
143 }
144
145 #[cfg(x11_platform)]
146 match std::env::var("X11_VISUAL_ID") {
147 Ok(visual_id_str) => {
148 info!("Using X11 visual id {visual_id_str}");
149 let visual_id = visual_id_str.parse()?;
150 window_attributes = window_attributes.with_x11_visual(visual_id);
151 },
152 Err(_) => info!("Set the X11_VISUAL_ID env variable to request specific X11 visual"),
153 }
154
155 #[cfg(x11_platform)]
156 match std::env::var("X11_SCREEN_ID") {
157 Ok(screen_id_str) => {
158 info!("Placing the window on X11 screen {screen_id_str}");
159 let screen_id = screen_id_str.parse()?;
160 window_attributes = window_attributes.with_x11_screen(screen_id);
161 },
162 Err(_) => info!(
163 "Set the X11_SCREEN_ID env variable to place the window on non-default screen"
164 ),
165 }
166
167 #[cfg(macos_platform)]
168 if let Some(tab_id) = _tab_id {
169 window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
170 }
171
172 #[cfg(web_platform)]
173 {
174 use winit::platform::web::WindowAttributesExtWebSys;
175 window_attributes = window_attributes.with_append(true);
176 }
177
178 let window = event_loop.create_window(window_attributes)?;
179
180 #[cfg(ios_platform)]
181 {
182 use winit::platform::ios::WindowExtIOS;
183 window.recognize_doubletap_gesture(true);
184 window.recognize_pinch_gesture(true);
185 window.recognize_rotation_gesture(true);
186 window.recognize_pan_gesture(true, 2, 2);
187 }
188
189 let window_state = WindowState::new(self, window)?;
190 let window_id = window_state.window.id();
191 info!("Created new window with id={window_id:?}");
192 self.windows.insert(window_id, window_state);
193 Ok(window_id)
194 }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?
256 fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
257 info!("Monitors information");
258 let primary_monitor = event_loop.primary_monitor();
259 for monitor in event_loop.available_monitors() {
260 let intro = if primary_monitor.as_ref() == Some(&monitor) {
261 "Primary monitor"
262 } else {
263 "Monitor"
264 };
265
266 if let Some(name) = monitor.name() {
267 info!("{intro}: {name}");
268 } else {
269 info!("{intro}: [no name]");
270 }
271
272 let PhysicalSize { width, height } = monitor.size();
273 info!(
274 " Current mode: {width}x{height}{}",
275 if let Some(m_hz) = monitor.refresh_rate_millihertz() {
276 format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
277 } else {
278 String::new()
279 }
280 );
281
282 let PhysicalPosition { x, y } = monitor.position();
283 info!(" Position: {x},{y}");
284
285 info!(" Scale factor: {}", monitor.scale_factor());
286
287 info!(" Available modes (width x height x bit-depth):");
288 for mode in monitor.video_modes() {
289 let PhysicalSize { width, height } = mode.size();
290 let bits = mode.bit_depth();
291 let m_hz = mode.refresh_rate_millihertz();
292 info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
293 }
294 }
295 }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?
256 fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
257 info!("Monitors information");
258 let primary_monitor = event_loop.primary_monitor();
259 for monitor in event_loop.available_monitors() {
260 let intro = if primary_monitor.as_ref() == Some(&monitor) {
261 "Primary monitor"
262 } else {
263 "Monitor"
264 };
265
266 if let Some(name) = monitor.name() {
267 info!("{intro}: {name}");
268 } else {
269 info!("{intro}: [no name]");
270 }
271
272 let PhysicalSize { width, height } = monitor.size();
273 info!(
274 " Current mode: {width}x{height}{}",
275 if let Some(m_hz) = monitor.refresh_rate_millihertz() {
276 format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
277 } else {
278 String::new()
279 }
280 );
281
282 let PhysicalPosition { x, y } = monitor.position();
283 info!(" Position: {x},{y}");
284
285 info!(" Scale factor: {}", monitor.scale_factor());
286
287 info!(" Available modes (width x height x bit-depth):");
288 for mode in monitor.video_modes() {
289 let PhysicalSize { width, height } = mode.size();
290 let bits = mode.bit_depth();
291 let m_hz = mode.refresh_rate_millihertz();
292 info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
293 }
294 }
295 }Sourcepub fn listen_device_events(&self, allowed: DeviceEvents)
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.
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 fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
126 if self.request_redraw && !self.wait_cancelled && !self.close_requested {
127 self.window.as_ref().unwrap().request_redraw();
128 }
129
130 match self.mode {
131 Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
132 Mode::WaitUntil => {
133 if !self.wait_cancelled {
134 event_loop
135 .set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
136 }
137 },
138 Mode::Poll => {
139 thread::sleep(POLL_SLEEP_TIME);
140 event_loop.set_control_flow(ControlFlow::Poll);
141 },
142 };
143
144 if self.close_requested {
145 event_loop.exit();
146 }
147 }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 fn window_event(
31 &mut self,
32 event_loop: &ActiveEventLoop,
33 _window_id: WindowId,
34 event: WindowEvent,
35 ) {
36 let window = self.window.as_ref().unwrap();
37 match event {
38 WindowEvent::CloseRequested => event_loop.exit(),
39 WindowEvent::RedrawRequested => {
40 window.pre_present_notify();
41 fill::fill_window(window);
42 },
43 _ => (),
44 }
45 }30 fn window_event(
31 &mut self,
32 event_loop: &ActiveEventLoop,
33 _window_id: WindowId,
34 event: WindowEvent,
35 ) {
36 println!("{event:?}");
37
38 let window = match self.window.as_ref() {
39 Some(window) => window,
40 None => return,
41 };
42
43 match event {
44 WindowEvent::CloseRequested => event_loop.exit(),
45 WindowEvent::RedrawRequested => {
46 fill::fill_window(window);
47 window.request_redraw();
48 },
49 _ => (),
50 }
51 }125 fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
126 if self.request_redraw && !self.wait_cancelled && !self.close_requested {
127 self.window.as_ref().unwrap().request_redraw();
128 }
129
130 match self.mode {
131 Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
132 Mode::WaitUntil => {
133 if !self.wait_cancelled {
134 event_loop
135 .set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
136 }
137 },
138 Mode::Poll => {
139 thread::sleep(POLL_SLEEP_TIME);
140 event_loop.set_control_flow(ControlFlow::Poll);
141 },
142 };
143
144 if self.close_requested {
145 event_loop.exit();
146 }
147 }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 }3fn main() -> Result<(), impl std::error::Error> {
4 use std::collections::HashMap;
5
6 use winit::dpi::{LogicalPosition, LogicalSize, Position};
7 use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
8 use winit::event_loop::{ActiveEventLoop, EventLoop};
9 use winit::raw_window_handle::HasRawWindowHandle;
10 use winit::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: KeyEvent { state: ElementState::Pressed, .. },
62 ..
63 } => {
64 let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
65 let child_window = spawn_child_window(parent_window, event_loop);
66 let child_id = child_window.id();
67 println!("Child window created with id: {child_id:?}");
68 windows.insert(child_id, child_window);
69 },
70 WindowEvent::RedrawRequested => {
71 if let Some(window) = windows.get(&window_id) {
72 fill::fill_window(window);
73 }
74 },
75 _ => (),
76 },
77 _ => (),
78 }
79 })
80}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> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&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> 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