use objc2_core_foundation::{
CFArray, CFDictionary, CFNumber, CFRetained, CFString, CFType, CGPoint, CGRect,
};
use objc2_core_graphics::{
CGDisplayBounds, CGError, CGGetDisplaysWithPoint, CGRectMakeWithDictionaryRepresentation,
CGWindowListCopyWindowInfo, CGWindowListOption, kCGWindowBounds, kCGWindowLayer,
kCGWindowOwnerName,
};
pub(super) fn focused_fullscreen_at(x: i32, y: i32) -> Option<bool> {
let bounds = display_bounds_at(x, y)?;
let windows = CGWindowListCopyWindowInfo(CGWindowListOption::OptionOnScreenOnly, 0)?;
let windows = unsafe { CFRetained::cast_unchecked::<CFArray<CFType>>(windows) };
for window in windows.iter() {
let Ok(window) = window.downcast::<CFDictionary>() else {
continue;
};
let window =
unsafe { CFRetained::cast_unchecked::<CFDictionary<CFString, CFType>>(window) };
let (owner, layer, rect) = unsafe { (kCGWindowOwnerName, kCGWindowLayer, kCGWindowBounds) };
let Some(layer) = window
.get(layer)
.and_then(|v| v.downcast::<CFNumber>().ok())
.and_then(|v| v.as_i32())
else {
continue;
};
if layer != 0 {
continue;
}
let Some(owner) = window
.get(owner)
.and_then(|v| v.downcast::<CFString>().ok())
else {
continue;
};
let Some(rect) = window
.get(rect)
.and_then(|v| v.downcast::<CFDictionary>().ok())
else {
continue;
};
let mut window_bounds = CGRect::default();
if !unsafe { CGRectMakeWithDictionaryRepresentation(Some(&rect), &raw mut window_bounds) } {
continue;
}
return Some(owner.to_string() != super::GUI_NAME && window_bounds == bounds);
}
Some(false)
}
fn display_bounds_at(x: i32, y: i32) -> Option<CGRect> {
let mut display = 0;
let mut count = 0;
let error = unsafe {
CGGetDisplaysWithPoint(
CGPoint::new(f64::from(x), f64::from(y)),
1,
&raw mut display,
&raw mut count,
)
};
(error == CGError::Success && count != 0).then(|| CGDisplayBounds(display))
}