Skip to content

Commit

Permalink
Deprecate window creation with stale event loop
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 deprecate the window creation when event loop is not running,
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 Feb 1, 2024
1 parent 4d4d6e5 commit 32e0f77
Show file tree
Hide file tree
Showing 90 changed files with 1,540 additions and 3,441 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ Unreleased` header.

# Unreleased

- **Breaking:** Deprecate `EventLoop::create_window`.
- **Breaking:** Move `Window::new` to `ActiveEventLoop::create_window` and `EventLoop::create_window`
- **Breaking:** Rename `EventLoopWindowTarget` to `ActiveEventLoop`.
- **Breaking:** Remove `Deref` implementation for `EventLoop` that gave `EventLoopWindowTarget`.
- **Breaking**: Remove `WindowBuilder` in favor of `WindowAttributes`.
- 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 Expand Up @@ -42,7 +47,7 @@ Unreleased` header.
- Added `EventLoop::builder`, which is intended to replace the (now deprecated) `EventLoopBuilder::new`.
- **Breaking:** Changed the signature of `EventLoop::with_user_event` to return a builder.
- **Breaking:** Removed `EventLoopBuilder::with_user_event`, the functionality is now available in `EventLoop::with_user_event`.
- Add `Window::builder`, which is intended to replace the (now deprecated) `WindowBuilder::new`.
- Add `Window::attributes` to get default `WindowAttributes`.
- On X11, reload dpi on `_XSETTINGS_SETTINGS` update.
- On X11, fix deadlock when adjusting DPI and resizing at the same time.
- On Wayland, fix `Focused(false)` being send when other seats still have window focused.
Expand Down
69 changes: 34 additions & 35 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,52 +6,53 @@ 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()
let mut window_attributes = Window::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.
builder = unsafe { builder.with_parent_window(Some(parent)) };
let child_window = builder.build(event_loop).unwrap();
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };

let id = child_window.id();
windows.insert(id, child_window);
println!("child window created with id: {id:?}");
event_loop.create_window(window_attributes).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 attributes = Window::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();

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 +69,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 => {
let window_attributes = Window::attributes().with_title(
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
);
window = Some(event_loop.create_window(window_attributes).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 32e0f77

Please sign in to comment.