eframe: read the state of native window's input focus and request it (#2900)

* Add ability to read the native window's focus state

* Add `eframe::Frame::focus()` for requesting the native window's focus

* rename the output field `active` → `focused` for consistency
This commit is contained in:
TicClick 2023-04-18 15:03:06 +02:00 committed by GitHub
parent b80c0e6ff6
commit 6f1e66731e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View File

@ -814,6 +814,15 @@ impl Frame {
self.output.minimized = Some(minimized);
}
/// Bring the window into focus (native only). Has no effect on Wayland, or if the window is minimized or invisible.
///
/// This method puts the window on top of other applications and takes input focus away from them,
/// which, if unexpected, will disturb the user.
#[cfg(not(target_arch = "wasm32"))]
pub fn focus(&mut self) {
self.output.focus = Some(true);
}
/// Maximize or unmaximize window. (native only)
#[cfg(not(target_arch = "wasm32"))]
pub fn set_maximized(&mut self, maximized: bool) {
@ -938,6 +947,9 @@ pub struct WindowInfo {
/// Are we maximized?
pub maximized: bool,
/// Is the window focused and able to receive input?
pub focused: bool,
/// Window inner size in egui points (logical pixels).
pub size: egui::Vec2,
@ -1129,6 +1141,10 @@ pub(crate) mod backend {
#[cfg(not(target_arch = "wasm32"))]
pub maximized: Option<bool>,
/// Set to some bool to focus window.
#[cfg(not(target_arch = "wasm32"))]
pub focus: Option<bool>,
#[cfg(not(target_arch = "wasm32"))]
pub screenshot_requested: bool,
}

View File

@ -61,6 +61,7 @@ pub fn read_window_info(
fullscreen: window.fullscreen().is_some(),
minimized: window_state.minimized,
maximized: window_state.maximized,
focused: window.has_focus(),
size: egui::Vec2 {
x: size.width,
y: size.height,
@ -231,6 +232,7 @@ pub fn handle_app_output(
screenshot_requested: _, // handled by the rendering backend,
minimized,
maximized,
focus,
} = app_output;
if let Some(decorated) = decorated {
@ -284,6 +286,10 @@ pub fn handle_app_output(
window.set_maximized(maximized);
window_state.maximized = maximized;
}
if focus == Some(true) {
window.focus_window();
}
}
// ----------------------------------------------------------------------------