From e1038c9106ac50f5e5c5947da1755e80a2cf1bfa Mon Sep 17 00:00:00 2001 From: Thierry Berger Date: Mon, 19 Feb 2024 21:38:55 +0100 Subject: [PATCH] retrieve user agent for better platform detection (#256) --- Cargo.toml | 3 +++ src/systems.rs | 29 ++++++++++++++++++++++------- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 48ddad8d6..5c9aaf63e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 = [ diff --git a/src/systems.rs b/src/systems.rs index 6dd1c7615..8de6f0cd9 100644 --- a/src/systems.rs +++ b/src/systems.rs @@ -85,6 +85,7 @@ pub struct ContextSystemParams<'w, 's> { pub focused_window: Local<'s, Option>, 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 ()>, } @@ -98,6 +99,24 @@ pub fn process_input_system( mut egui_mouse_position: ResMut, time: Res>, ) { + // 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() { @@ -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, @@ -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();