@@ -257,6 +257,7 @@ fn get_front_window(own_pid: i32) -> u32 { |
| 257 | 257 | let layer_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowLayer\0".as_ptr(), kCFStringEncodingUTF8); |
| 258 | 258 | |
| 259 | 259 | let mut front_wid: u32 = 0; |
| 260 | + let mut fallback_wid: u32 = 0; |
| 260 | 261 | for i in 0..count { |
| 261 | 262 | let dict = CFArrayGetValueAtIndex(list, i); |
| 262 | 263 | if dict.is_null() { continue; } |
@@ -273,18 +274,32 @@ fn get_front_window(own_pid: i32) -> u32 { |
| 273 | 274 | if CFDictionaryGetValueIfPresent(dict, pid_key as CFTypeRef, &mut v) { |
| 274 | 275 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut pid as *mut _ as *mut _); |
| 275 | 276 | } |
| 276 | | - if pid != front_pid { continue; } |
| 277 | + if pid == own_pid { continue; } |
| 277 | 278 | |
| 278 | 279 | let mut wid: u32 = 0; |
| 279 | 280 | if CFDictionaryGetValueIfPresent(dict, wid_key as CFTypeRef, &mut v) { |
| 280 | 281 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut wid as *mut _ as *mut _); |
| 281 | 282 | } |
| 282 | | - if wid != 0 { |
| 283 | + if wid == 0 { continue; } |
| 284 | + |
| 285 | + // Track first non-self window as fallback (z-order based) |
| 286 | + if fallback_wid == 0 { |
| 287 | + fallback_wid = wid; |
| 288 | + } |
| 289 | + |
| 290 | + // Prefer a window from the front process |
| 291 | + if pid == front_pid { |
| 283 | 292 | front_wid = wid; |
| 284 | 293 | break; |
| 285 | 294 | } |
| 286 | 295 | } |
| 287 | 296 | |
| 297 | + // Fall back to z-order if front process has no visible windows |
| 298 | + // (e.g., switched to a workspace where the front app has no windows) |
| 299 | + if front_wid == 0 { |
| 300 | + front_wid = fallback_wid; |
| 301 | + } |
| 302 | + |
| 288 | 303 | CFRelease(wid_key as CFTypeRef); |
| 289 | 304 | CFRelease(pid_key as CFTypeRef); |
| 290 | 305 | CFRelease(layer_key as CFTypeRef); |