use winit::window::Window;
#[cfg(windows)]
pub(super) fn position_in_window(window: &Window) -> Option<(f32, f32)> {
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use windows::Win32::{
Foundation::{HWND, POINT},
Graphics::Gdi::ScreenToClient,
UI::WindowsAndMessaging::GetCursorPos,
};
let handle = window.window_handle().ok()?;
let RawWindowHandle::Win32(handle) = handle.as_raw() else {
return None;
};
let hwnd = HWND(handle.hwnd.get() as *mut _);
if hwnd.is_invalid() {
return None;
}
let mut point = POINT::default();
unsafe {
GetCursorPos(&mut point).ok()?;
if !ScreenToClient(hwnd, &mut point).as_bool() {
return None;
}
}
Some((point.x as f32, point.y as f32))
}
#[cfg(target_os = "macos")]
pub(super) fn position_in_window(window: &Window) -> Option<(f32, f32)> {
let location = objc2_app_kit::NSEvent::mouseLocation();
let primary = window.primary_monitor()?;
let main_screen_height = f64::from(primary.size().height) / primary.scale_factor();
let scale = window.scale_factor();
let inner = window.inner_position().ok()?;
let inner_x = f64::from(inner.x) / scale;
let inner_y = f64::from(inner.y) / scale;
let x = (location.x - inner_x) * scale;
let y = (main_screen_height - location.y - inner_y) * scale;
Some((x as f32, y as f32))
}
#[cfg(not(any(windows, target_os = "macos")))]
pub(super) fn position_in_window(_window: &Window) -> Option<(f32, f32)> {
None
}
#[cfg(windows)]
pub(super) fn any_mouse_button_pressed() -> Option<bool> {
use windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_LBUTTON, VK_MBUTTON, VK_RBUTTON};
let pressed =
|key: windows::Win32::UI::Input::KeyboardAndMouse::VIRTUAL_KEY| unsafe { GetAsyncKeyState(i32::from(key.0)) < 0 };
Some(pressed(VK_LBUTTON) || pressed(VK_RBUTTON) || pressed(VK_MBUTTON))
}
#[cfg(target_os = "macos")]
pub(super) fn any_mouse_button_pressed() -> Option<bool> {
Some(objc2_app_kit::NSEvent::pressedMouseButtons() != 0)
}
#[cfg(not(any(windows, target_os = "macos")))]
pub(super) fn any_mouse_button_pressed() -> Option<bool> {
None
}