Remove CanvasParentResizePlugin (#11057)

Improves #11052

# Changelog
- Remove `Window::fit_canvas_to_parent`, as its resizing on wasm now
respects its CSS configuration.

## Migration Guide
- Remove uses of `Window::fit_canvas_to_parent` in favor of CSS
properties, for example:
  ```css
  canvas {
    width: 100%;
    height: 100%;
  }
  ```
This commit is contained in:
Thierry Berger 2023-12-21 21:01:22 +01:00 committed by GitHub
parent b27f74911a
commit 80f15e0dbb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 1 additions and 166 deletions

View file

@ -191,14 +191,6 @@ pub struct Window {
/// ///
/// This value has no effect on non-web platforms. /// This value has no effect on non-web platforms.
pub canvas: Option<String>, pub canvas: Option<String>,
/// Whether or not to fit the canvas element's size to its parent element's size.
///
/// **Warning**: this will not behave as expected for parents that set their size according to the size of their
/// children. This creates a "feedback loop" that will result in the canvas growing on each resize. When using this
/// feature, ensure the parent's size is not affected by its children.
///
/// This value has no effect on non-web platforms.
pub fit_canvas_to_parent: bool,
/// Whether or not to stop events from propagating out of the canvas element /// Whether or not to stop events from propagating out of the canvas element
/// ///
/// When `true`, this will prevent common browser hotkeys like F5, F12, Ctrl+R, tab, etc. /// When `true`, this will prevent common browser hotkeys like F5, F12, Ctrl+R, tab, etc.
@ -266,7 +258,6 @@ impl Default for Window {
transparent: false, transparent: false,
focused: true, focused: true,
window_level: Default::default(), window_level: Default::default(),
fit_canvas_to_parent: false,
prevent_default_event_handling: true, prevent_default_event_handling: true,
canvas: None, canvas: None,
window_theme: None, window_theme: None,

View file

@ -9,8 +9,6 @@
pub mod accessibility; pub mod accessibility;
mod converters; mod converters;
mod system; mod system;
#[cfg(target_arch = "wasm32")]
mod web_resize;
mod winit_config; mod winit_config;
mod winit_windows; mod winit_windows;
@ -55,8 +53,6 @@ use winit::{
use crate::accessibility::{AccessKitAdapters, AccessKitPlugin, WinitActionHandlers}; use crate::accessibility::{AccessKitAdapters, AccessKitPlugin, WinitActionHandlers};
use crate::converters::convert_winit_theme; use crate::converters::convert_winit_theme;
#[cfg(target_arch = "wasm32")]
use crate::web_resize::{CanvasParentResizeEventChannel, CanvasParentResizePlugin};
/// [`AndroidApp`] provides an interface to query the application state as well as monitor events /// [`AndroidApp`] provides an interface to query the application state as well as monitor events
/// (for example lifecycle and input events). /// (for example lifecycle and input events).
@ -143,9 +139,6 @@ impl Plugin for WinitPlugin {
app.add_plugins(AccessKitPlugin); app.add_plugins(AccessKitPlugin);
#[cfg(target_arch = "wasm32")]
app.add_plugins(CanvasParentResizePlugin);
let event_loop = event_loop_builder let event_loop = event_loop_builder
.build() .build()
.expect("Failed to build event loop"); .expect("Failed to build event loop");
@ -181,7 +174,6 @@ impl Plugin for WinitPlugin {
NonSendMut<AccessKitAdapters>, NonSendMut<AccessKitAdapters>,
ResMut<WinitActionHandlers>, ResMut<WinitActionHandlers>,
ResMut<AccessibilityRequested>, ResMut<AccessibilityRequested>,
ResMut<CanvasParentResizeEventChannel>,
)> = SystemState::from_world(&mut app.world); )> = SystemState::from_world(&mut app.world);
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
@ -204,7 +196,6 @@ impl Plugin for WinitPlugin {
adapters, adapters,
handlers, handlers,
accessibility_requested, accessibility_requested,
event_channel,
) = create_window_system_state.get_mut(&mut app.world); ) = create_window_system_state.get_mut(&mut app.world);
create_windows( create_windows(
@ -216,8 +207,6 @@ impl Plugin for WinitPlugin {
adapters, adapters,
handlers, handlers,
accessibility_requested, accessibility_requested,
#[cfg(target_arch = "wasm32")]
event_channel,
); );
create_window_system_state.apply(&mut app.world); create_window_system_state.apply(&mut app.world);
@ -340,7 +329,6 @@ pub fn winit_runner(mut app: App) {
NonSend<AccessKitAdapters>, NonSend<AccessKitAdapters>,
)> = SystemState::new(&mut app.world); )> = SystemState::new(&mut app.world);
#[cfg(not(target_arch = "wasm32"))]
let mut create_window_system_state: SystemState<( let mut create_window_system_state: SystemState<(
Commands, Commands,
Query<(Entity, &mut Window), Added<Window>>, Query<(Entity, &mut Window), Added<Window>>,
@ -351,18 +339,6 @@ pub fn winit_runner(mut app: App) {
ResMut<AccessibilityRequested>, ResMut<AccessibilityRequested>,
)> = SystemState::from_world(&mut app.world); )> = SystemState::from_world(&mut app.world);
#[cfg(target_arch = "wasm32")]
let mut create_window_system_state: SystemState<(
Commands,
Query<(Entity, &mut Window), Added<Window>>,
EventWriter<WindowCreated>,
NonSendMut<WinitWindows>,
NonSendMut<AccessKitAdapters>,
ResMut<WinitActionHandlers>,
ResMut<AccessibilityRequested>,
ResMut<CanvasParentResizeEventChannel>,
)> = SystemState::from_world(&mut app.world);
// setup up the event loop // setup up the event loop
let event_handler = move |event: Event<()>, event_loop: &EventLoopWindowTarget<()>| { let event_handler = move |event: Event<()>, event_loop: &EventLoopWindowTarget<()>| {
#[cfg(feature = "trace")] #[cfg(feature = "trace")]
@ -390,7 +366,6 @@ pub fn winit_runner(mut app: App) {
StartCause::Init => { StartCause::Init => {
#[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg(any(target_os = "ios", target_os = "macos"))]
{ {
#[cfg(not(target_arch = "wasm32"))]
let ( let (
commands, commands,
mut windows, mut windows,
@ -401,18 +376,6 @@ pub fn winit_runner(mut app: App) {
accessibility_requested, accessibility_requested,
) = create_window_system_state.get_mut(&mut app.world); ) = create_window_system_state.get_mut(&mut app.world);
#[cfg(target_arch = "wasm32")]
let (
commands,
mut windows,
event_writer,
winit_windows,
adapters,
handlers,
accessibility_requested,
event_channel,
) = create_window_system_state.get_mut(&mut app.world);
create_windows( create_windows(
event_loop, event_loop,
commands, commands,
@ -422,8 +385,6 @@ pub fn winit_runner(mut app: App) {
adapters, adapters,
handlers, handlers,
accessibility_requested, accessibility_requested,
#[cfg(target_arch = "wasm32")]
event_channel,
); );
create_window_system_state.apply(&mut app.world); create_window_system_state.apply(&mut app.world);
@ -842,7 +803,6 @@ pub fn winit_runner(mut app: App) {
// create any new windows // create any new windows
// (even if app did not update, some may have been created by plugin setup) // (even if app did not update, some may have been created by plugin setup)
#[cfg(not(target_arch = "wasm32"))]
let ( let (
commands, commands,
mut windows, mut windows,
@ -853,18 +813,6 @@ pub fn winit_runner(mut app: App) {
accessibility_requested, accessibility_requested,
) = create_window_system_state.get_mut(&mut app.world); ) = create_window_system_state.get_mut(&mut app.world);
#[cfg(target_arch = "wasm32")]
let (
commands,
mut windows,
event_writer,
winit_windows,
adapters,
handlers,
accessibility_requested,
event_channel,
) = create_window_system_state.get_mut(&mut app.world);
create_windows( create_windows(
event_loop, event_loop,
commands, commands,
@ -874,8 +822,6 @@ pub fn winit_runner(mut app: App) {
adapters, adapters,
handlers, handlers,
accessibility_requested, accessibility_requested,
#[cfg(target_arch = "wasm32")]
event_channel,
); );
create_window_system_state.apply(&mut app.world); create_window_system_state.apply(&mut app.world);

View file

@ -19,8 +19,6 @@ use winit::{
event_loop::EventLoopWindowTarget, event_loop::EventLoopWindowTarget,
}; };
#[cfg(target_arch = "wasm32")]
use crate::web_resize::{CanvasParentResizeEventChannel, WINIT_CANVAS_SELECTOR};
use crate::{ use crate::{
accessibility::{AccessKitAdapters, WinitActionHandlers}, accessibility::{AccessKitAdapters, WinitActionHandlers},
converters::{ converters::{
@ -45,7 +43,6 @@ pub(crate) fn create_windows<'a>(
mut adapters: NonSendMut<AccessKitAdapters>, mut adapters: NonSendMut<AccessKitAdapters>,
mut handlers: ResMut<WinitActionHandlers>, mut handlers: ResMut<WinitActionHandlers>,
accessibility_requested: ResMut<AccessibilityRequested>, accessibility_requested: ResMut<AccessibilityRequested>,
#[cfg(target_arch = "wasm32")] event_channel: ResMut<CanvasParentResizeEventChannel>,
) { ) {
for (entity, mut window) in created_windows { for (entity, mut window) in created_windows {
if winit_windows.get_window(entity).is_some() { if winit_windows.get_window(entity).is_some() {
@ -84,18 +81,6 @@ pub(crate) fn create_windows<'a>(
window: window.clone(), window: window.clone(),
}); });
#[cfg(target_arch = "wasm32")]
{
if window.fit_canvas_to_parent {
let selector = if let Some(selector) = &window.canvas {
selector
} else {
WINIT_CANVAS_SELECTOR
};
event_channel.listen_to_selector(entity, selector);
}
}
event_writer.send(WindowCreated { window: entity }); event_writer.send(WindowCreated { window: entity });
} }
} }

View file

@ -1,83 +0,0 @@
use crate::WinitWindows;
use bevy_app::{App, Plugin, Update};
use bevy_ecs::prelude::*;
use crossbeam_channel::{Receiver, Sender};
use wasm_bindgen::JsCast;
use winit::dpi::LogicalSize;
pub(crate) struct CanvasParentResizePlugin;
impl Plugin for CanvasParentResizePlugin {
fn build(&self, app: &mut App) {
app.init_resource::<CanvasParentResizeEventChannel>()
.add_systems(Update, canvas_parent_resize_event_handler);
}
}
struct ResizeEvent {
size: LogicalSize<f32>,
window: Entity,
}
#[derive(Resource)]
pub(crate) struct CanvasParentResizeEventChannel {
sender: Sender<ResizeEvent>,
receiver: Receiver<ResizeEvent>,
}
fn canvas_parent_resize_event_handler(
winit_windows: NonSend<WinitWindows>,
resize_events: Res<CanvasParentResizeEventChannel>,
) {
for event in resize_events.receiver.try_iter() {
if let Some(window) = winit_windows.get_window(event.window) {
let _ = window.request_inner_size(event.size);
}
}
}
fn get_size(selector: &str) -> Option<LogicalSize<f32>> {
let win = web_sys::window().unwrap();
let doc = win.document().unwrap();
let element = doc.query_selector(selector).ok()??;
let parent_element = element.parent_element()?;
let rect = parent_element.get_bounding_client_rect();
return Some(winit::dpi::LogicalSize::new(
rect.width() as f32,
rect.height() as f32,
));
}
pub(crate) const WINIT_CANVAS_SELECTOR: &str = "canvas[data-raw-handle]";
impl Default for CanvasParentResizeEventChannel {
fn default() -> Self {
let (sender, receiver) = crossbeam_channel::unbounded();
return Self { sender, receiver };
}
}
impl CanvasParentResizeEventChannel {
pub(crate) fn listen_to_selector(&self, window: Entity, selector: &str) {
let sender = self.sender.clone();
let owned_selector = selector.to_string();
let resize = move || {
if let Some(size) = get_size(&owned_selector) {
sender.send(ResizeEvent { size, window }).unwrap();
}
};
// ensure resize happens on startup
resize();
let closure = wasm_bindgen::closure::Closure::wrap(Box::new(move |_: web_sys::Event| {
resize();
}) as Box<dyn FnMut(_)>);
let window = web_sys::window().unwrap();
window
.add_event_listener_with_callback("resize", closure.as_ref().unchecked_ref())
.unwrap();
closure.forget();
}
}

View file

@ -16,8 +16,6 @@ fn main() {
title: "I am a window!".into(), title: "I am a window!".into(),
resolution: (500., 300.).into(), resolution: (500., 300.).into(),
present_mode: PresentMode::AutoVsync, present_mode: PresentMode::AutoVsync,
// Tells wasm to resize the window according to the available canvas
fit_canvas_to_parent: true,
// Tells wasm not to override default event handling, like F5, Ctrl+R etc. // Tells wasm not to override default event handling, like F5, Ctrl+R etc.
prevent_default_event_handling: false, prevent_default_event_handling: false,
window_theme: Some(WindowTheme::Dark), window_theme: Some(WindowTheme::Dark),

View file

@ -2,12 +2,10 @@ diff --git a/crates/bevy_window/src/window.rs b/crates/bevy_window/src/window.rs
index 7b5c75d38..8e9404b93 100644 index 7b5c75d38..8e9404b93 100644
--- a/crates/bevy_window/src/window.rs --- a/crates/bevy_window/src/window.rs
+++ b/crates/bevy_window/src/window.rs +++ b/crates/bevy_window/src/window.rs
@@ -245,9 +245,9 @@ impl Default for Window { @@ -245,8 +245,8 @@ impl Default for Window {
transparent: false, transparent: false,
focused: true, focused: true,
window_level: Default::default(), window_level: Default::default(),
- fit_canvas_to_parent: false,
+ fit_canvas_to_parent: true,
prevent_default_event_handling: true, prevent_default_event_handling: true,
- canvas: None, - canvas: None,
+ canvas: Some("#bevy".to_string()), + canvas: Some("#bevy".to_string()),