fix(macOS): cursor_position returns incorrect position (#711)

* On macOS, fix `cursor_position` returns incorrect position

* Add proper error handling

* Restore example
This commit is contained in:
Ngo Iok Ui (Wu Yu Wei)
2023-03-07 20:19:03 +08:00
committed by GitHub
parent 76ae625bae
commit ea2e60d9df
2 changed files with 20 additions and 4 deletions

6
.changes/cursor.md Normal file
View File

@@ -0,0 +1,6 @@
---
"tao": patch
---
On macOS, Fix `cursor_position` return incorrect position.

View File

@@ -17,7 +17,11 @@ use cocoa::{
base::{id, nil},
foundation::{NSAutoreleasePool, NSPoint, NSRect, NSString, NSUInteger},
};
use core_graphics::display::CGDisplay;
use core_graphics::{
display::CGDisplay,
event::CGEvent,
event_source::{CGEventSource, CGEventSourceStateID},
};
use objc::runtime::{Class, Object, Sel, BOOL, YES};
use crate::{
@@ -124,11 +128,17 @@ pub fn window_position(position: LogicalPosition<f64>) -> NSPoint {
)
}
// FIXME: This is actually logical position.
pub fn cursor_position() -> Result<PhysicalPosition<f64>, ExternalError> {
unsafe {
let pt: NSPoint = msg_send![class!(NSEvent), mouseLocation];
Ok((pt.x, pt.y).into())
if let Ok(s) = CGEventSource::new(CGEventSourceStateID::CombinedSessionState) {
if let Ok(e) = CGEvent::new(s) {
let pt = e.location();
let pos = PhysicalPosition::new(pt.x, pt.y);
return Ok(pos);
}
}
return Err(ExternalError::Os(os_error!(super::OsError::CGError(0))));
}
pub unsafe fn ns_string_id_ref(s: &str) -> IdRef {