Skip to content

Commit

Permalink
retrieve user agent for better platform detection (#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vrixyz committed Feb 19, 2024
1 parent 003b060 commit e1038c9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ webbrowser = { version = "0.8.2", optional = true }
arboard = { version = "3.2.0", optional = true }
thread_local = { version = "1.1.0", optional = true }

[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3.63", features = ["Navigator"] }

[dev-dependencies]
version-sync = "0.9.4"
bevy = { version = "0.13", default-features = false, features = [
Expand Down
29 changes: 22 additions & 7 deletions src/systems.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ pub struct ContextSystemParams<'w, 's> {
pub focused_window: Local<'s, Option<Entity>>,
pub pointer_touch_id: Local<'s, TouchId>,
pub contexts: Query<'w, 's, EguiContextQuery>,
pub is_macos: Local<'s, bool>,
#[system_param(ignore)]
_marker: PhantomData<&'s ()>,
}
Expand All @@ -98,6 +99,24 @@ pub fn process_input_system(
mut egui_mouse_position: ResMut<EguiMousePosition>,
time: Res<Time<Real>>,
) {
// Test whether it's macOS or OS X.
use std::sync::Once;
static START: Once = Once::new();
START.call_once(|| {
// The default for WASM is `false` since the `target_os` is `unknown`.
*context_params.is_macos = cfg!(target_os = "macos");

#[cfg(target_arch = "wasm32")]
if let Some(window) = web_sys::window() {
let nav = window.navigator();
if let Ok(user_agent) = nav.user_agent() {
if user_agent.to_ascii_lowercase().contains("Mac") {
*context_params.is_macos = true;
}
}
}
});

// This is a workaround for Windows. For some reason, `WindowFocused` event isn't fired
// when a window is created.
if let Some(event) = input_events.ev_window_created.read().last() {
Expand Down Expand Up @@ -143,12 +162,8 @@ pub fn process_input_system(
alt,
win,
} = *input_resources.modifier_keys_state;
let mac_cmd = if cfg!(target_os = "macos") {
win
} else {
false
};
let command = if cfg!(target_os = "macos") { win } else { ctrl };
let mac_cmd = if *context_params.is_macos { win } else { false };
let command = if !*context_params.is_macos { win } else { ctrl };

let modifiers = egui::Modifiers {
alt,
Expand Down Expand Up @@ -251,7 +266,7 @@ pub fn process_input_system(
}
}

if !command || cfg!(target_os = "windows") && ctrl && alt {
if !command || !*context_params.is_macos && ctrl && alt {
for event in input_events.ev_received_character.read() {
if event.char.matches(char::is_control).count() == 0 {
let mut context = context_params.contexts.get_mut(event.window).unwrap();
Expand Down

0 comments on commit e1038c9

Please sign in to comment.