Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Add Windows::get_focused(_mut) #6571

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 5 additions & 17 deletions crates/bevy_window/src/system.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Window, WindowCloseRequested, WindowFocused, WindowId, Windows};
use crate::{Window, WindowCloseRequested, Windows};

use bevy_app::AppExit;
use bevy_ecs::prelude::*;
Expand Down Expand Up @@ -36,22 +36,10 @@ pub fn close_when_requested(
/// Close the focused window whenever the escape key (<kbd>Esc</kbd>) is pressed
///
/// This is useful for examples or prototyping.
pub fn close_on_esc(
mut focused: Local<Option<WindowId>>,
mut focused_events: EventReader<WindowFocused>,
mut windows: ResMut<Windows>,
input: Res<Input<KeyCode>>,
) {
// TODO: Track this in e.g. a resource to ensure consistent behaviour across similar systems
for event in focused_events.iter() {
*focused = event.focused.then_some(event.id);
}

if let Some(focused) = &*focused {
if input.just_pressed(KeyCode::Escape) {
if let Some(window) = windows.get_mut(*focused) {
window.close();
}
pub fn close_on_esc(mut windows: ResMut<Windows>, input: Res<Input<KeyCode>>) {
if input.just_pressed(KeyCode::Escape) {
if let Some(window) = windows.get_focused_mut() {
window.close();
}
}
}
10 changes: 10 additions & 0 deletions crates/bevy_window/src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ impl Windows {
.expect("Primary window does not exist")
}

/// Get a reference to the focused [`Window`].
pub fn get_focused(&self) -> Option<&Window> {
self.windows.values().find(|window| window.is_focused())
}

/// Get a mutable reference to the focused [`Window`].
pub fn get_focused_mut(&mut self) -> Option<&mut Window> {
self.windows.values_mut().find(|window| window.is_focused())
}

/// Returns the scale factor for the [`Window`] of `id`, or `1.0` if the window does not exist.
pub fn scale_factor(&self, id: WindowId) -> f64 {
if let Some(window) = self.get(id) {
Expand Down