Skip to content

Commit

Permalink
Require event loop to run when creating Window
Browse files Browse the repository at this point in the history
Creating window when event loop is not running generally doesn't work,
since a bunch of events and sync OS requests can't be processed. This
is also an issue on e.g. Android, since window can't be created outside
event loop easily.

Thus restrict the window creation, as well as other resource creation
to running event loop.

Given that all the examples use the bad pattern of creating the window
when event loop is not running and also most example existence is
questionable, since they show single thing and the majority of their
code is window/event loop initialization, they wore merged into
a single example 'window.rs' example that showcases very simple
application using winit.

Fixes #3399.
  • Loading branch information
kchibisov committed Jan 31, 2024
1 parent 4d4d6e5 commit a612cc3
Show file tree
Hide file tree
Showing 85 changed files with 1,356 additions and 3,211 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Unreleased` header.

# Unreleased

- **Breaking:** Rename `EventLoopWindowTarget` to `ActiveEventLoop`.
- **Breaking:** Remove `Deref` implementation for `EventLoop` that gave `EventLoopWindowTarget`.
- On X11, fix swapped instance and general class names.
- **Breaking:** Removed unnecessary generic parameter `T` from `EventLoopWindowTarget`.
- On Windows, macOS, X11, Wayland and Web, implement setting images as cursors. See the `custom_cursors.rs` example.
Expand Down
66 changes: 33 additions & 33 deletions examples/child_window.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
#[cfg(all(
feature = "rwh_06",
any(x11_platform, macos_platform, windows_platform)
))]
#[path = "util/fill.rs"]
mod fill;

#[cfg(all(
feature = "rwh_06",
any(x11_platform, macos_platform, windows_platform)
Expand All @@ -13,19 +6,18 @@ mod fill;
fn main() -> Result<(), impl std::error::Error> {
use std::collections::HashMap;

#[path = "util/fill.rs"]
mod fill;

use winit::{
dpi::{LogicalPosition, LogicalSize, Position},
event::{ElementState, Event, KeyEvent, WindowEvent},
event_loop::{EventLoop, EventLoopWindowTarget},
event_loop::{ActiveEventLoop, EventLoop},
raw_window_handle::HasRawWindowHandle,
window::{Window, WindowId},
};

fn spawn_child_window(
parent: &Window,
event_loop: &EventLoopWindowTarget,
windows: &mut HashMap<WindowId, Window>,
) {
fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
let parent = parent.raw_window_handle().unwrap();
let mut builder = Window::builder()
.with_title("child window")
Expand All @@ -34,31 +26,34 @@ fn main() -> Result<(), impl std::error::Error> {
.with_visible(true);
// `with_parent_window` is unsafe. Parent window must be a valid window.
builder = unsafe { builder.with_parent_window(Some(parent)) };
let child_window = builder.build(event_loop).unwrap();

let id = child_window.id();
windows.insert(id, child_window);
println!("child window created with id: {id:?}");
builder.build(event_loop).unwrap()
}

let mut windows = HashMap::new();

let event_loop: EventLoop<()> = EventLoop::new().unwrap();
let parent_window = Window::builder()
.with_title("parent window")
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32))
.build(&event_loop)
.unwrap();
let mut parent_window_id = unsafe { WindowId::dummy() };

println!("parent window: {parent_window:?})");
event_loop.run(move |event: Event<()>, event_loop| {
match event {
Event::Resumed => {
let window = Window::builder()
.with_title("parent window")
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32))
.build(event_loop)
.unwrap();

event_loop.run(move |event: Event<()>, elwt| {
if let Event::WindowEvent { event, window_id } = event {
match event {
parent_window_id = window.id();

println!("Parent window id: {parent_window_id:?})");
windows.insert(parent_window_id, window);
}
Event::WindowEvent { window_id, event } => match event {
WindowEvent::CloseRequested => {
windows.clear();
elwt.exit();
event_loop.exit();
}
WindowEvent::CursorEntered { device_id: _ } => {
// On x11, println when the cursor entered in a window even if the child window is created
Expand All @@ -75,23 +70,28 @@ fn main() -> Result<(), impl std::error::Error> {
},
..
} => {
spawn_child_window(&parent_window, elwt, &mut windows);
let parent_window = windows.get(&parent_window_id).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);
}
}
_ => (),
}
},
_ => (),
}
})
}

#[cfg(not(all(
#[cfg(all(
feature = "rwh_06",
any(x11_platform, macos_platform, windows_platform)
)))]
not(any(x11_platform, macos_platform, windows_platform))
))]
fn main() {
panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled.");
}
27 changes: 16 additions & 11 deletions examples/control_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,14 @@ fn main() -> Result<(), impl std::error::Error> {
println!("Press 'Esc' to close the window.");

let event_loop = EventLoop::new().unwrap();
let window = Window::builder()
.with_title("Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.")
.build(&event_loop)
.unwrap();

let mut mode = Mode::Wait;
let mut request_redraw = false;
let mut wait_cancelled = false;
let mut close_requested = false;

event_loop.run(move |event, elwt| {
let mut window = None;
event_loop.run(move |event, event_loop| {
use winit::event::StartCause;
println!("{event:?}");
match event {
Expand All @@ -57,6 +54,12 @@ fn main() -> Result<(), impl std::error::Error> {
_ => false,
}
}
Event::Resumed => {
window = Some(Window::builder()
.with_title("Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.")
.build(event_loop)
.unwrap());
}
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => {
close_requested = true;
Expand Down Expand Up @@ -94,32 +97,34 @@ fn main() -> Result<(), impl std::error::Error> {
_ => (),
},
WindowEvent::RedrawRequested => {
fill::fill_window(&window);
let window = window.as_ref().unwrap();
window.pre_present_notify();
fill::fill_window(window);
}
_ => (),
},
Event::AboutToWait => {
if request_redraw && !wait_cancelled && !close_requested {
window.request_redraw();
window.as_ref().unwrap().request_redraw();
}

match mode {
Mode::Wait => elwt.set_control_flow(ControlFlow::Wait),
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
Mode::WaitUntil => {
if !wait_cancelled {
elwt.set_control_flow(ControlFlow::WaitUntil(
event_loop.set_control_flow(ControlFlow::WaitUntil(
time::Instant::now() + WAIT_TIME,
));
}
}
Mode::Poll => {
thread::sleep(POLL_SLEEP_TIME);
elwt.set_control_flow(ControlFlow::Poll);
event_loop.set_control_flow(ControlFlow::Poll);
}
};

if close_requested {
elwt.exit();
event_loop.exit();
}
}
_ => (),
Expand Down
88 changes: 0 additions & 88 deletions examples/cursor.rs

This file was deleted.

73 changes: 0 additions & 73 deletions examples/cursor_grab.rs

This file was deleted.

Loading

0 comments on commit a612cc3

Please sign in to comment.