|
| 1 | +//! Handles focus / input conflicts between `bevy_egui` and this crate. |
| 2 | +//! |
| 3 | +//! ## Usage |
| 4 | +//! |
| 5 | +//! Enable the `bevy_egui` feature of this crate. |
| 6 | +//! |
| 7 | +//! Ensure [`bevy_egui::EguiPlugin`] is added to your app. |
| 8 | +//! |
| 9 | +//! *Note: this may be automatically done by `bevy_inspector_egui` plugins for example.* |
| 10 | +
|
| 11 | +use bevy::prelude::*; |
| 12 | +use bevy_egui::{EguiContexts, EguiPlugin, EguiSet}; |
| 13 | + |
| 14 | +/// A `Resource` for determining whether [`crate::Spectator`]s should handle input. |
| 15 | +/// |
| 16 | +/// To check focus state it is recommended to call |
| 17 | +/// |
| 18 | +/// [`EguiFocusState::wants_focus`] |
| 19 | +/// |
| 20 | +/// which only returns true if egui wanted focus in both this frame and the previous frame. |
| 21 | +/// |
| 22 | +#[derive(Resource, PartialEq, Eq, Default)] |
| 23 | +pub struct EguiFocusState { |
| 24 | + /// Whether egui wants focus this frame |
| 25 | + pub current_frame_wants_focus: bool, |
| 26 | + /// Whether egui wanted focus in the previous frame |
| 27 | + pub previous_frame_wanted_focus: bool, |
| 28 | +} |
| 29 | + |
| 30 | +impl EguiFocusState { |
| 31 | + /// The default method for checking focus. |
| 32 | + pub fn wants_focus(&self) -> bool { |
| 33 | + self.previous_frame_wanted_focus && self.current_frame_wants_focus |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +pub(crate) struct EguiFocusPlugin; |
| 38 | + |
| 39 | +impl Plugin for EguiFocusPlugin { |
| 40 | + fn build(&self, app: &mut App) { |
| 41 | + app.init_resource::<EguiFocusState>(); |
| 42 | + } |
| 43 | + |
| 44 | + fn finish(&self, app: &mut App) { |
| 45 | + if app.is_plugin_added::<EguiPlugin>() { |
| 46 | + app.add_systems( |
| 47 | + PostUpdate, |
| 48 | + check_egui_wants_focus.after(EguiSet::InitContexts), |
| 49 | + ); |
| 50 | + } else { |
| 51 | + warn!("EguiPlugin not added, no focus checking will occur."); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +fn check_egui_wants_focus( |
| 57 | + mut contexts: EguiContexts, |
| 58 | + mut focus_state: ResMut<EguiFocusState>, |
| 59 | + windows: Query<Entity, With<Window>>, |
| 60 | +) { |
| 61 | + let egui_wants_focus_this_frame = windows.iter().any(|window| { |
| 62 | + let ctx = contexts.ctx_for_entity_mut(window); |
| 63 | + ctx.wants_pointer_input() || ctx.wants_keyboard_input() || ctx.is_pointer_over_area() |
| 64 | + }); |
| 65 | + |
| 66 | + focus_state.set_if_neq(EguiFocusState { |
| 67 | + previous_frame_wanted_focus: focus_state.current_frame_wants_focus, |
| 68 | + current_frame_wants_focus: egui_wants_focus_this_frame, |
| 69 | + }); |
| 70 | +} |
0 commit comments