Browse Source

eframe: Correctly identify if browser tab has focus (#4280)

`input.focus` was often wrong on web
pull/4282/head
Emil Ernerfeldt 7 months ago
committed by GitHub
parent
commit
d3c6895443
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 4
      crates/eframe/src/web/backend.rs
  2. 25
      crates/eframe/src/web/events.rs

4
crates/eframe/src/web/backend.rs

@ -36,8 +36,10 @@ impl WebInput {
raw_input
}
/// On alt-tab and similar.
pub fn on_web_page_focus_change(&mut self, focused: bool) {
self.raw.modifiers = egui::Modifiers::default();
// log::debug!("on_web_page_focus_change: {focused}");
self.raw.modifiers = egui::Modifiers::default(); // Avoid sticky modifier keys on alt-tab:
self.raw.focused = focused;
self.raw.events.push(egui::Event::WindowFocused(focused));
self.latest_touch_pos = None;

25
crates/eframe/src/web/events.rs

@ -50,10 +50,9 @@ fn paint_if_needed(runner: &mut AppRunner) {
pub(crate) fn install_document_events(runner_ref: &WebRunner) -> Result<(), JsValue> {
let document = web_sys::window().unwrap().document().unwrap();
{
// Avoid sticky modifier keys on alt-tab:
for event_name in ["blur", "focus"] {
let closure = move |_event: web_sys::MouseEvent, runner: &mut AppRunner| {
// log::debug!("{event_name:?}");
let has_focus = event_name == "focus";
if !has_focus {
@ -63,12 +62,10 @@ pub(crate) fn install_document_events(runner_ref: &WebRunner) -> Result<(), JsVa
runner.input.on_web_page_focus_change(has_focus);
runner.egui_ctx().request_repaint();
// log::debug!("{event_name:?}");
};
runner_ref.add_event_listener(&document, event_name, closure)?;
}
}
runner_ref.add_event_listener(
&document,
@ -228,13 +225,31 @@ pub(crate) fn install_document_events(runner_ref: &WebRunner) -> Result<(), JsVa
pub(crate) fn install_window_events(runner_ref: &WebRunner) -> Result<(), JsValue> {
let window = web_sys::window().unwrap();
for event_name in ["blur", "focus"] {
let closure = move |_event: web_sys::MouseEvent, runner: &mut AppRunner| {
// log::debug!("{event_name:?}");
let has_focus = event_name == "focus";
if !has_focus {
// We lost focus - good idea to save
runner.save();
}
runner.input.on_web_page_focus_change(has_focus);
runner.egui_ctx().request_repaint();
};
runner_ref.add_event_listener(&window, event_name, closure)?;
}
// Save-on-close
runner_ref.add_event_listener(&window, "onbeforeunload", |_: web_sys::Event, runner| {
runner.save();
})?;
for event_name in &["load", "pagehide", "pageshow", "resize"] {
runner_ref.add_event_listener(&window, event_name, |_: web_sys::Event, runner| {
runner_ref.add_event_listener(&window, event_name, move |_: web_sys::Event, runner| {
// log::debug!("{event_name:?}");
runner.needs_repaint.repaint_asap();
})?;
}

Loading…
Cancel
Save