@@ -2,20 +2,190 @@ |
| 2 | 2 | |
| 3 | 3 | mod events; |
| 4 | 4 | mod skylight; |
| 5 | +mod nswindow_overlay; |
| 5 | 6 | |
| 6 | 7 | use events::Event; |
| 7 | 8 | use skylight::*; |
| 8 | 9 | use std::collections::HashMap; |
| 9 | 10 | use std::ptr; |
| 11 | +use std::sync::Arc; |
| 10 | 12 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 11 | 13 | use std::sync::mpsc; |
| 12 | | -use std::sync::Arc; |
| 13 | 14 | use tracing::debug; |
| 14 | 15 | |
| 15 | | -/// Per-overlay state: the connection it was created on + its wid. |
| 16 | +static SIGNAL_STOP_REQUESTED: AtomicBool = AtomicBool::new(false); |
| 17 | +const MIN_TRACKED_WINDOW_SIZE: f64 = 4.0; |
| 18 | +const GEOMETRY_EPSILON: f64 = 0.5; |
| 19 | +const WINDOW_ATTRIBUTE_REAL: u64 = 1 << 1; |
| 20 | +const WINDOW_TAG_DOCUMENT: u64 = 1 << 0; |
| 21 | +const WINDOW_TAG_FLOATING: u64 = 1 << 1; |
| 22 | +const WINDOW_TAG_ATTACHED: u64 = 1 << 7; |
| 23 | +const WINDOW_TAG_IGNORES_CYCLE: u64 = 1 << 18; |
| 24 | +const WINDOW_TAG_MODAL: u64 = 1 << 31; |
| 25 | +const WINDOW_TAG_REAL_SURFACE: u64 = 1 << 58; |
| 26 | + |
| 27 | +/// Per-overlay state: an NSWindow drawing the rounded-rect border via |
| 28 | +/// CAShapeLayer. Replaces the old SLS-only overlay window — see |
| 29 | +/// nswindow_overlay.rs for the rationale (screencaptureui on Tahoe |
| 30 | +/// only honors NSWindow.sharingType, not SLS sharing-state nor tag |
| 31 | +/// bits, for raw SLS-only windows). |
| 16 | 32 | struct Overlay { |
| 17 | | - cid: CGSConnectionID, |
| 18 | | - wid: u32, |
| 33 | + window: nswindow_overlay::OverlayWindow, |
| 34 | +} |
| 35 | + |
| 36 | +impl Overlay { |
| 37 | + fn wid(&self) -> u32 { |
| 38 | + self.window.wid() |
| 39 | + } |
| 40 | + fn bounds(&self) -> CGRect { |
| 41 | + CGRect { |
| 42 | + origin: CGPoint { |
| 43 | + x: self.window.bounds_cg_x, |
| 44 | + y: self.window.bounds_cg_y, |
| 45 | + }, |
| 46 | + size: CGSize { |
| 47 | + width: self.window.bounds_cg_w, |
| 48 | + height: self.window.bounds_cg_h, |
| 49 | + }, |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +fn window_area(bounds: CGRect) -> f64 { |
| 55 | + bounds.size.width * bounds.size.height |
| 56 | +} |
| 57 | + |
| 58 | +fn intersection_area(a: CGRect, b: CGRect) -> f64 { |
| 59 | + let left = a.origin.x.max(b.origin.x); |
| 60 | + let top = a.origin.y.max(b.origin.y); |
| 61 | + let right = (a.origin.x + a.size.width).min(b.origin.x + b.size.width); |
| 62 | + let bottom = (a.origin.y + a.size.height).min(b.origin.y + b.size.height); |
| 63 | + let width = (right - left).max(0.0); |
| 64 | + let height = (bottom - top).max(0.0); |
| 65 | + width * height |
| 66 | +} |
| 67 | + |
| 68 | +fn is_same_window_surface(a: CGRect, b: CGRect) -> bool { |
| 69 | + let smaller = window_area(a).min(window_area(b)); |
| 70 | + smaller > 0.0 && intersection_area(a, b) / smaller >= 0.9 |
| 71 | +} |
| 72 | + |
| 73 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 74 | +enum SurfacePreference { |
| 75 | + KeepExisting, |
| 76 | + ReplaceExisting, |
| 77 | +} |
| 78 | + |
| 79 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 80 | +struct WindowMetadata { |
| 81 | + parent_wid: u32, |
| 82 | + tags: u64, |
| 83 | + attributes: u64, |
| 84 | +} |
| 85 | + |
| 86 | +fn surface_preference(existing: CGRect, candidate: CGRect) -> Option<SurfacePreference> { |
| 87 | + if !is_same_window_surface(existing, candidate) { |
| 88 | + return None; |
| 89 | + } |
| 90 | + |
| 91 | + if window_area(candidate) > window_area(existing) { |
| 92 | + Some(SurfacePreference::ReplaceExisting) |
| 93 | + } else { |
| 94 | + Some(SurfacePreference::KeepExisting) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +fn minimum_trackable_dimension(border_width: f64) -> f64 { |
| 99 | + border_width.max(MIN_TRACKED_WINDOW_SIZE) |
| 100 | +} |
| 101 | + |
| 102 | +fn is_trackable_window(bounds: CGRect, border_width: f64) -> bool { |
| 103 | + let min_dimension = minimum_trackable_dimension(border_width); |
| 104 | + bounds.size.width >= min_dimension && bounds.size.height >= min_dimension |
| 105 | +} |
| 106 | + |
| 107 | +fn origin_changed(a: CGRect, b: CGRect) -> bool { |
| 108 | + (a.origin.x - b.origin.x).abs() > GEOMETRY_EPSILON |
| 109 | + || (a.origin.y - b.origin.y).abs() > GEOMETRY_EPSILON |
| 110 | +} |
| 111 | + |
| 112 | +fn size_changed(a: CGRect, b: CGRect) -> bool { |
| 113 | + (a.size.width - b.size.width).abs() > GEOMETRY_EPSILON |
| 114 | + || (a.size.height - b.size.height).abs() > GEOMETRY_EPSILON |
| 115 | +} |
| 116 | + |
| 117 | +fn is_suitable_window_metadata(metadata: WindowMetadata) -> bool { |
| 118 | + metadata.parent_wid == 0 |
| 119 | + && ((metadata.attributes & WINDOW_ATTRIBUTE_REAL) != 0 |
| 120 | + || (metadata.tags & WINDOW_TAG_REAL_SURFACE) != 0) |
| 121 | + && (metadata.tags & WINDOW_TAG_ATTACHED) == 0 |
| 122 | + && (metadata.tags & WINDOW_TAG_IGNORES_CYCLE) == 0 |
| 123 | + && ((metadata.tags & WINDOW_TAG_DOCUMENT) != 0 |
| 124 | + || ((metadata.tags & WINDOW_TAG_FLOATING) != 0 |
| 125 | + && (metadata.tags & WINDOW_TAG_MODAL) != 0)) |
| 126 | +} |
| 127 | + |
| 128 | +fn query_window_metadata(cid: CGSConnectionID, wid: u32) -> Option<WindowMetadata> { |
| 129 | + unsafe { |
| 130 | + let window_ref = cfarray_of_cfnumbers( |
| 131 | + (&wid as *const u32).cast(), |
| 132 | + std::mem::size_of::<u32>(), |
| 133 | + 1, |
| 134 | + kCFNumberSInt32Type, |
| 135 | + ); |
| 136 | + if window_ref.is_null() { |
| 137 | + return None; |
| 138 | + } |
| 139 | + |
| 140 | + let query = SLSWindowQueryWindows(cid, window_ref, 0x0); |
| 141 | + CFRelease(window_ref); |
| 142 | + if query.is_null() { |
| 143 | + return None; |
| 144 | + } |
| 145 | + |
| 146 | + let iterator = SLSWindowQueryResultCopyWindows(query); |
| 147 | + CFRelease(query); |
| 148 | + if iterator.is_null() { |
| 149 | + return None; |
| 150 | + } |
| 151 | + |
| 152 | + let metadata = if SLSWindowIteratorAdvance(iterator) { |
| 153 | + Some(WindowMetadata { |
| 154 | + parent_wid: SLSWindowIteratorGetParentID(iterator), |
| 155 | + tags: SLSWindowIteratorGetTags(iterator), |
| 156 | + attributes: SLSWindowIteratorGetAttributes(iterator), |
| 157 | + }) |
| 158 | + } else { |
| 159 | + None |
| 160 | + }; |
| 161 | + |
| 162 | + CFRelease(iterator); |
| 163 | + metadata |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +fn is_suitable_window(cid: CGSConnectionID, wid: u32) -> bool { |
| 168 | + match query_window_metadata(cid, wid) { |
| 169 | + Some(metadata) => { |
| 170 | + let suitable = is_suitable_window_metadata(metadata); |
| 171 | + if !suitable { |
| 172 | + debug!( |
| 173 | + "[window_filter] rejecting wid={} parent={} tags={:#x} attributes={:#x}", |
| 174 | + wid, metadata.parent_wid, metadata.tags, metadata.attributes |
| 175 | + ); |
| 176 | + } |
| 177 | + suitable |
| 178 | + } |
| 179 | + None => false, |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +fn cf_string_from_static(name: &std::ffi::CStr) -> CFStringRef { |
| 184 | + unsafe { CFStringCreateWithCString(ptr::null(), name.as_ptr().cast(), kCFStringEncodingUTF8) } |
| 185 | +} |
| 186 | + |
| 187 | +unsafe extern "C" fn handle_sigint(_: libc::c_int) { |
| 188 | + SIGNAL_STOP_REQUESTED.store(true, Ordering::Relaxed); |
| 19 | 189 | } |
| 20 | 190 | |
| 21 | 191 | /// Tracks overlays for target windows. |
@@ -29,132 +199,277 @@ struct BorderMap { |
| 29 | 199 | active_color: (f64, f64, f64, f64), |
| 30 | 200 | inactive_color: (f64, f64, f64, f64), |
| 31 | 201 | active_only: bool, |
| 202 | + mtm: objc2::MainThreadMarker, |
| 32 | 203 | } |
| 33 | 204 | |
| 34 | 205 | impl BorderMap { |
| 35 | | - fn new(cid: CGSConnectionID, own_pid: i32, border_width: f64) -> Self { |
| 206 | + fn new( |
| 207 | + cid: CGSConnectionID, |
| 208 | + own_pid: i32, |
| 209 | + border_width: f64, |
| 210 | + mtm: objc2::MainThreadMarker, |
| 211 | + ) -> Self { |
| 36 | 212 | Self { |
| 37 | 213 | overlays: HashMap::new(), |
| 214 | + mtm, |
| 38 | 215 | main_cid: cid, |
| 39 | 216 | own_pid, |
| 40 | 217 | border_width, |
| 41 | 218 | radius: 10.0, |
| 42 | 219 | focused_wid: 0, |
| 43 | 220 | active_color: (0.32, 0.58, 0.89, 1.0), // #5294e2 |
| 44 | | - inactive_color: (0.35, 0.35, 0.35, 0.8), // dim gray |
| 221 | + inactive_color: (0.35, 0.35, 0.35, 0.8), // dim gray |
| 45 | 222 | active_only: false, |
| 46 | 223 | } |
| 47 | 224 | } |
| 48 | 225 | |
| 49 | 226 | fn color_for(&self, target_wid: u32) -> (f64, f64, f64, f64) { |
| 50 | | - if target_wid == self.focused_wid { self.active_color } else { self.inactive_color } |
| 227 | + if target_wid == self.focused_wid { |
| 228 | + self.active_color |
| 229 | + } else { |
| 230 | + self.inactive_color |
| 231 | + } |
| 51 | 232 | } |
| 52 | 233 | |
| 53 | 234 | fn is_overlay(&self, wid: u32) -> bool { |
| 54 | | - self.overlays.values().any(|o| o.wid == wid) |
| 235 | + self.overlays.values().any(|o| o.wid() == wid) |
| 55 | 236 | } |
| 56 | 237 | |
| 57 | | - /// Add border (batch mode, uses main cid). |
| 238 | + /// Add border using the standard filtering path. |
| 58 | 239 | fn add_batch(&mut self, target_wid: u32) { |
| 59 | | - if self.overlays.contains_key(&target_wid) { return; } |
| 60 | | - let color = self.color_for(target_wid); |
| 61 | | - if let Some((cid, wid)) = create_overlay(self.main_cid, target_wid, self.border_width, self.radius, color) { |
| 62 | | - self.overlays.insert(target_wid, Overlay { cid, wid }); |
| 240 | + self.add_fresh(target_wid); |
| 241 | + } |
| 242 | + |
| 243 | + fn surface_replacements(&self, target_wid: u32, bounds: CGRect) -> Option<Vec<u32>> { |
| 244 | + let mut replacements = Vec::new(); |
| 245 | + |
| 246 | + for &existing_wid in self.overlays.keys() { |
| 247 | + if existing_wid == target_wid { |
| 248 | + continue; |
| 249 | + } |
| 250 | + |
| 251 | + unsafe { |
| 252 | + let mut existing_bounds = CGRect::default(); |
| 253 | + if SLSGetWindowBounds(self.main_cid, existing_wid, &mut existing_bounds) |
| 254 | + != kCGErrorSuccess |
| 255 | + { |
| 256 | + continue; |
| 257 | + } |
| 258 | + |
| 259 | + match surface_preference(existing_bounds, bounds) { |
| 260 | + Some(SurfacePreference::KeepExisting) => return None, |
| 261 | + Some(SurfacePreference::ReplaceExisting) => replacements.push(existing_wid), |
| 262 | + None => {} |
| 263 | + } |
| 264 | + } |
| 63 | 265 | } |
| 266 | + |
| 267 | + Some(replacements) |
| 64 | 268 | } |
| 65 | 269 | |
| 66 | 270 | /// Add border (event mode). Uses main_cid — fresh connections create |
| 67 | 271 | /// invisible windows on Tahoe. |
| 68 | 272 | fn add_fresh(&mut self, target_wid: u32) { |
| 69 | | - if self.overlays.contains_key(&target_wid) { return; } |
| 273 | + if self.overlays.contains_key(&target_wid) { |
| 274 | + return; |
| 275 | + } |
| 70 | 276 | |
| 71 | 277 | // Filter: must be visible, owned by another process, not tiny |
| 72 | | - unsafe { |
| 278 | + let bounds = unsafe { |
| 73 | 279 | let mut shown = false; |
| 74 | 280 | SLSWindowIsOrderedIn(self.main_cid, target_wid, &mut shown); |
| 75 | | - if !shown { return; } |
| 281 | + if !shown { |
| 282 | + return; |
| 283 | + } |
| 76 | 284 | |
| 77 | 285 | let mut wid_cid: CGSConnectionID = 0; |
| 78 | 286 | SLSGetWindowOwner(self.main_cid, target_wid, &mut wid_cid); |
| 79 | 287 | let mut pid: i32 = 0; |
| 80 | 288 | SLSConnectionGetPID(wid_cid, &mut pid); |
| 81 | | - if pid == self.own_pid { return; } |
| 289 | + if pid == self.own_pid { |
| 290 | + return; |
| 291 | + } |
| 292 | + if !is_suitable_window(self.main_cid, target_wid) { |
| 293 | + return; |
| 294 | + } |
| 82 | 295 | |
| 83 | 296 | let mut bounds = CGRect::default(); |
| 84 | 297 | SLSGetWindowBounds(self.main_cid, target_wid, &mut bounds); |
| 85 | | - if bounds.size.width < 50.0 || bounds.size.height < 50.0 { return; } |
| 298 | + if !is_trackable_window(bounds, self.border_width) { |
| 299 | + return; |
| 300 | + } |
| 301 | + bounds |
| 302 | + }; |
| 303 | + |
| 304 | + let Some(replacements) = self.surface_replacements(target_wid, bounds) else { |
| 305 | + return; |
| 306 | + }; |
| 307 | + |
| 308 | + for wid in replacements { |
| 309 | + self.remove(wid); |
| 86 | 310 | } |
| 87 | 311 | |
| 88 | 312 | let color = self.color_for(target_wid); |
| 89 | | - if let Some((cid, wid)) = create_overlay(self.main_cid, target_wid, self.border_width, self.radius, color) { |
| 90 | | - self.overlays.insert(target_wid, Overlay { cid, wid }); |
| 313 | + if let Some(window) = nswindow_overlay::OverlayWindow::new( |
| 314 | + bounds.origin.x, |
| 315 | + bounds.origin.y, |
| 316 | + bounds.size.width, |
| 317 | + bounds.size.height, |
| 318 | + self.border_width, |
| 319 | + self.radius, |
| 320 | + color, |
| 321 | + self.mtm, |
| 322 | + ) { |
| 323 | + window.order_above(target_wid); |
| 324 | + self.overlays.insert(target_wid, Overlay { window }); |
| 91 | 325 | } |
| 92 | 326 | } |
| 93 | 327 | |
| 94 | | - fn remove_all(&mut self) { |
| 95 | | - let wids: Vec<u32> = self.overlays.keys().copied().collect(); |
| 96 | | - for wid in wids { |
| 97 | | - self.remove(wid); |
| 328 | + fn remove(&mut self, target_wid: u32) { |
| 329 | + if let Some(overlay) = self.overlays.remove(&target_wid) { |
| 330 | + debug!( |
| 331 | + "[remove] target={} overlay_wid={} dropping NSWindow", |
| 332 | + target_wid, |
| 333 | + overlay.wid() |
| 334 | + ); |
| 335 | + // OverlayWindow's Drop runs orderOut + close. |
| 336 | + drop(overlay); |
| 337 | + } else { |
| 338 | + debug!("[remove] target={} not tracked", target_wid); |
| 98 | 339 | } |
| 99 | 340 | } |
| 100 | 341 | |
| 101 | | - fn remove(&mut self, target_wid: u32) { |
| 102 | | - if let Some(overlay) = self.overlays.remove(&target_wid) { |
| 103 | | - unsafe { |
| 104 | | - // Move off-screen first (most reliable hide on Tahoe) |
| 105 | | - let offscreen = CGPoint { x: -99999.0, y: -99999.0 }; |
| 106 | | - SLSMoveWindow(overlay.cid, overlay.wid, &offscreen); |
| 107 | | - SLSSetWindowAlpha(overlay.cid, overlay.wid, 0.0); |
| 108 | | - SLSOrderWindow(overlay.cid, overlay.wid, 0, 0); |
| 109 | | - SLSReleaseWindow(overlay.cid, overlay.wid); |
| 110 | | - if overlay.cid != self.main_cid { |
| 111 | | - SLSReleaseConnection(overlay.cid); |
| 112 | | - } |
| 342 | + /// Reconcile a tracked overlay against its target window. |
| 343 | + fn sync_overlay(&mut self, target_wid: u32) -> bool { |
| 344 | + if !self.overlays.contains_key(&target_wid) { |
| 345 | + return false; |
| 346 | + } |
| 347 | + |
| 348 | + let mut bounds = CGRect::default(); |
| 349 | + unsafe { |
| 350 | + if SLSGetWindowBounds(self.main_cid, target_wid, &mut bounds) != kCGErrorSuccess { |
| 351 | + // Window is gone (destroyed). Reap the overlay. |
| 352 | + debug!( |
| 353 | + "[sync_overlay] target={} SLSGetWindowBounds failed — reaping overlay", |
| 354 | + target_wid |
| 355 | + ); |
| 356 | + self.remove(target_wid); |
| 357 | + return true; |
| 358 | + } |
| 359 | + |
| 360 | + if !is_suitable_window(self.main_cid, target_wid) { |
| 361 | + self.remove(target_wid); |
| 362 | + return true; |
| 363 | + } |
| 364 | + |
| 365 | + if !is_trackable_window(bounds, self.border_width) { |
| 366 | + self.remove(target_wid); |
| 367 | + return true; |
| 113 | 368 | } |
| 114 | 369 | } |
| 115 | | - } |
| 116 | 370 | |
| 117 | | - /// Move overlay to match target's current position (no recreate). |
| 118 | | - fn reposition(&self, target_wid: u32) { |
| 119 | | - if let Some(overlay) = self.overlays.get(&target_wid) { |
| 120 | | - unsafe { |
| 121 | | - let mut bounds = CGRect::default(); |
| 122 | | - if SLSGetWindowBounds(overlay.cid, target_wid, &mut bounds) != kCGErrorSuccess { |
| 123 | | - return; |
| 371 | + let active_only = self.active_only; |
| 372 | + let focused = self.focused_wid; |
| 373 | + |
| 374 | + if let Some(overlay) = self.overlays.get_mut(&target_wid) { |
| 375 | + let prev = overlay.bounds(); |
| 376 | + if size_changed(prev, bounds) || origin_changed(prev, bounds) { |
| 377 | + debug!( |
| 378 | + "[sync_overlay] target={} geometry ({:.1},{:.1},{:.1},{:.1}) -> ({:.1},{:.1},{:.1},{:.1})", |
| 379 | + target_wid, |
| 380 | + prev.origin.x, |
| 381 | + prev.origin.y, |
| 382 | + prev.size.width, |
| 383 | + prev.size.height, |
| 384 | + bounds.origin.x, |
| 385 | + bounds.origin.y, |
| 386 | + bounds.size.width, |
| 387 | + bounds.size.height |
| 388 | + ); |
| 389 | + overlay.window.set_bounds( |
| 390 | + bounds.origin.x, |
| 391 | + bounds.origin.y, |
| 392 | + bounds.size.width, |
| 393 | + bounds.size.height, |
| 394 | + ); |
| 395 | + // orderWindow:relativeTo: re-shows an off-screen window |
| 396 | + // as a side effect. In active_only mode, non-focused |
| 397 | + // overlays must remain hidden — otherwise stack peek |
| 398 | + // positions cause every stacked window's overlay to |
| 399 | + // pop onto the screen as their bounds shift. |
| 400 | + if !active_only || target_wid == focused { |
| 401 | + overlay.window.order_above(target_wid); |
| 124 | 402 | } |
| 125 | | - let bw = self.border_width; |
| 126 | | - let origin = CGPoint { |
| 127 | | - x: bounds.origin.x - bw, |
| 128 | | - y: bounds.origin.y - bw, |
| 129 | | - }; |
| 130 | | - SLSMoveWindow(overlay.cid, overlay.wid, &origin); |
| 131 | 403 | } |
| 132 | 404 | } |
| 405 | + |
| 406 | + false |
| 133 | 407 | } |
| 134 | 408 | |
| 135 | | - /// Recreate overlay at new size. |
| 136 | | - fn recreate(&mut self, target_wid: u32) { |
| 137 | | - if !self.overlays.contains_key(&target_wid) { return; } |
| 138 | | - self.remove(target_wid); |
| 139 | | - self.add_fresh(target_wid); |
| 140 | | - if self.active_only && target_wid != self.focused_wid { |
| 141 | | - self.hide(target_wid); |
| 409 | + fn reconcile_tracked(&mut self) -> bool { |
| 410 | + let tracked: Vec<u32> = self.overlays.keys().copied().collect(); |
| 411 | + let mut changed = false; |
| 412 | + |
| 413 | + for wid in tracked { |
| 414 | + changed |= self.sync_overlay(wid); |
| 415 | + } |
| 416 | + |
| 417 | + changed |
| 418 | + } |
| 419 | + |
| 420 | + /// Re-apply each overlay's CAShapeLayer geometry. Called on a slow |
| 421 | + /// periodic schedule (and on hotplug) to repair layer state that |
| 422 | + /// macOS occasionally resets during display sleep/wake without |
| 423 | + /// changing the NSWindow's frame — sync_overlay won't fix it on |
| 424 | + /// its own because the SLS bounds match what we already stored. |
| 425 | + fn refresh_all_layers(&self) { |
| 426 | + for overlay in self.overlays.values() { |
| 427 | + overlay.window.reapply_layer(); |
| 428 | + } |
| 429 | + } |
| 430 | + |
| 431 | + /// Re-apply set_bounds for every tracked overlay even when the |
| 432 | + /// stored CG bounds match the current SLS bounds. After a display |
| 433 | + /// reconfiguration the cocoa frame depends on the (possibly new) |
| 434 | + /// primary screen height, so unchanged CG bounds still need their |
| 435 | + /// cocoa frame recomputed. |
| 436 | + fn reconcile_all_force(&mut self) { |
| 437 | + let tracked: Vec<u32> = self.overlays.keys().copied().collect(); |
| 438 | + let active_only = self.active_only; |
| 439 | + let focused = self.focused_wid; |
| 440 | + for wid in tracked { |
| 441 | + let mut bounds = CGRect::default(); |
| 442 | + unsafe { |
| 443 | + if SLSGetWindowBounds(self.main_cid, wid, &mut bounds) != kCGErrorSuccess { |
| 444 | + self.remove(wid); |
| 445 | + continue; |
| 446 | + } |
| 447 | + } |
| 448 | + if let Some(overlay) = self.overlays.get_mut(&wid) { |
| 449 | + overlay.window.set_bounds( |
| 450 | + bounds.origin.x, |
| 451 | + bounds.origin.y, |
| 452 | + bounds.size.width, |
| 453 | + bounds.size.height, |
| 454 | + ); |
| 455 | + if !active_only || wid == focused { |
| 456 | + overlay.window.order_above(wid); |
| 457 | + } |
| 458 | + } |
| 142 | 459 | } |
| 143 | | - self.subscribe_target(target_wid); |
| 144 | 460 | } |
| 145 | 461 | |
| 146 | 462 | fn hide(&self, target_wid: u32) { |
| 147 | 463 | if let Some(o) = self.overlays.get(&target_wid) { |
| 148 | | - unsafe { SLSOrderWindow(o.cid, o.wid, 0, 0); } |
| 464 | + debug!("[hide] target={} overlay_wid={}", target_wid, o.wid()); |
| 465 | + o.window.order_out(); |
| 149 | 466 | } |
| 150 | 467 | } |
| 151 | 468 | |
| 152 | 469 | fn unhide(&self, target_wid: u32) { |
| 153 | 470 | if let Some(o) = self.overlays.get(&target_wid) { |
| 154 | | - unsafe { |
| 155 | | - SLSSetWindowLevel(o.cid, o.wid, 25); |
| 156 | | - SLSOrderWindow(o.cid, o.wid, 1, 0); |
| 157 | | - } |
| 471 | + debug!("[unhide] target={} overlay_wid={}", target_wid, o.wid()); |
| 472 | + o.window.order_above(target_wid); |
| 158 | 473 | } |
| 159 | 474 | } |
| 160 | 475 | |
@@ -166,7 +481,9 @@ impl BorderMap { |
| 166 | 481 | |
| 167 | 482 | fn subscribe_all(&self) { |
| 168 | 483 | let target_wids: Vec<u32> = self.overlays.keys().copied().collect(); |
| 169 | | - if target_wids.is_empty() { return; } |
| 484 | + if target_wids.is_empty() { |
| 485 | + return; |
| 486 | + } |
| 170 | 487 | unsafe { |
| 171 | 488 | SLSRequestNotificationsForWindows( |
| 172 | 489 | self.main_cid, |
@@ -179,34 +496,63 @@ impl BorderMap { |
| 179 | 496 | /// Redraw an existing overlay with a new color (no destroy/recreate). |
| 180 | 497 | fn redraw(&self, target_wid: u32) { |
| 181 | 498 | if let Some(overlay) = self.overlays.get(&target_wid) { |
| 182 | | - unsafe { |
| 183 | | - let mut bounds = CGRect::default(); |
| 184 | | - if SLSGetWindowBounds(overlay.cid, target_wid, &mut bounds) != kCGErrorSuccess { |
| 185 | | - return; |
| 186 | | - } |
| 187 | | - let bw = self.border_width; |
| 188 | | - let ow = bounds.size.width + 2.0 * bw; |
| 189 | | - let oh = bounds.size.height + 2.0 * bw; |
| 190 | | - |
| 191 | | - let ctx = SLWindowContextCreate(overlay.cid, overlay.wid, ptr::null()); |
| 192 | | - if ctx.is_null() { return; } |
| 193 | | - |
| 194 | | - let color = self.color_for(target_wid); |
| 195 | | - draw_border(ctx, ow, oh, bw, self.radius, color); |
| 196 | | - SLSFlushWindowContentRegion(overlay.cid, overlay.wid, ptr::null()); |
| 197 | | - CGContextRelease(ctx); |
| 198 | | - } |
| 499 | + overlay.window.set_color(self.color_for(target_wid)); |
| 199 | 500 | } |
| 200 | 501 | } |
| 201 | 502 | |
| 202 | 503 | /// Detect focused window and update border colors if focus changed. |
| 203 | 504 | fn update_focus(&mut self) { |
| 204 | 505 | let front = get_front_window(self.own_pid); |
| 205 | | - if front == 0 || front == self.focused_wid { return; } |
| 506 | + if front == 0 { |
| 507 | + return; |
| 508 | + } |
| 509 | + if front == self.focused_wid { |
| 510 | + // Same focus as last poll. But a freshly-spawned window may |
| 511 | + // have been focused before its SLS state was complete enough |
| 512 | + // to pass the add_fresh filter — retry on every poll until |
| 513 | + // it sticks. |
| 514 | + if !self.overlays.contains_key(&front) { |
| 515 | + self.add_fresh(front); |
| 516 | + if self.overlays.contains_key(&front) { |
| 517 | + debug!("[focus-retry] front={} now tracked", front); |
| 518 | + self.subscribe_target(front); |
| 519 | + if self.active_only { |
| 520 | + self.unhide(front); |
| 521 | + } |
| 522 | + } |
| 523 | + } |
| 524 | + return; |
| 525 | + } |
| 206 | 526 | |
| 207 | 527 | let old = self.focused_wid; |
| 208 | 528 | self.focused_wid = front; |
| 209 | | - debug!("[focus] {} -> {}", old, front); |
| 529 | + |
| 530 | + // tarmac-style workspace switching can swap focus to a window |
| 531 | + // that wasn't visible (and therefore not discovered) at ers |
| 532 | + // startup. Discover_windows only enumerates on-current-space |
| 533 | + // windows; tarmac stages other workspaces' windows in a hidden |
| 534 | + // state ers never picked up. If focus lands on such a wid, |
| 535 | + // create an overlay for it on demand. |
| 536 | + let new_target = !self.overlays.contains_key(&front); |
| 537 | + debug!( |
| 538 | + "[focus] {} -> {} {}(tracked targets: {:?})", |
| 539 | + old, |
| 540 | + front, |
| 541 | + if new_target { "[NEW] " } else { "" }, |
| 542 | + self.overlays.keys().collect::<Vec<_>>() |
| 543 | + ); |
| 544 | + if new_target { |
| 545 | + self.add_fresh(front); |
| 546 | + self.subscribe_target(front); |
| 547 | + } |
| 548 | + |
| 549 | + // Pull both overlays' positions to the targets' current SLS bounds |
| 550 | + // before un/hiding. AX-driven moves during a stack cycle frequently |
| 551 | + // don't fire SLS WINDOW_MOVE notifications, so a stored overlay |
| 552 | + // can be at stale coordinates. SLSGetWindowBounds (inside |
| 553 | + // sync_overlay) is real-time and doesn't wait for a notification. |
| 554 | + self.sync_overlay(old); |
| 555 | + self.sync_overlay(front); |
| 210 | 556 | |
| 211 | 557 | if self.active_only { |
| 212 | 558 | self.hide(old); |
@@ -216,17 +562,35 @@ impl BorderMap { |
| 216 | 562 | self.redraw(front); |
| 217 | 563 | } |
| 218 | 564 | |
| 565 | + /// Discover on-screen windows and create borders for any untracked ones. |
| 566 | + /// Called on space changes to pick up windows from workspaces we haven't visited. |
| 567 | + fn discover_untracked(&mut self) { |
| 568 | + let wids = discover_windows(self.main_cid, self.own_pid); |
| 569 | + let mut added = false; |
| 570 | + for wid in wids { |
| 571 | + if !self.overlays.contains_key(&wid) { |
| 572 | + self.add_fresh(wid); |
| 573 | + if self.active_only && wid != self.focused_wid { |
| 574 | + self.hide(wid); |
| 575 | + } |
| 576 | + added = true; |
| 577 | + } |
| 578 | + } |
| 579 | + if added { |
| 580 | + self.subscribe_all(); |
| 581 | + } |
| 582 | + } |
| 583 | + |
| 219 | 584 | /// In active-only mode, ensure only the focused overlay is visible. |
| 220 | 585 | fn enforce_active_only(&self) { |
| 221 | | - if !self.active_only { return; } |
| 586 | + if !self.active_only { |
| 587 | + return; |
| 588 | + } |
| 222 | 589 | for (&target_wid, o) in &self.overlays { |
| 223 | 590 | if target_wid == self.focused_wid { |
| 224 | | - unsafe { |
| 225 | | - SLSSetWindowLevel(o.cid, o.wid, 25); |
| 226 | | - SLSOrderWindow(o.cid, o.wid, 1, 0); |
| 227 | | - } |
| 591 | + o.window.order_above(target_wid); |
| 228 | 592 | } else { |
| 229 | | - unsafe { SLSOrderWindow(o.cid, o.wid, 0, 0); } |
| 593 | + o.window.order_out(); |
| 230 | 594 | } |
| 231 | 595 | } |
| 232 | 596 | } |
@@ -245,22 +609,30 @@ fn get_front_window(own_pid: i32) -> u32 { |
| 245 | 609 | SLSGetConnectionIDForPSN(SLSMainConnectionID(), &mut psn, &mut front_cid); |
| 246 | 610 | let mut front_pid: i32 = 0; |
| 247 | 611 | SLSConnectionGetPID(front_cid, &mut front_pid); |
| 248 | | - if front_pid == 0 || front_pid == own_pid { return 0; } |
| 612 | + if front_pid == 0 || front_pid == own_pid { |
| 613 | + return 0; |
| 614 | + } |
| 249 | 615 | |
| 250 | 616 | // Step 2: find the topmost layer-0 window belonging to that process |
| 251 | 617 | let list = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID); |
| 252 | | - if list.is_null() { return 0; } |
| 618 | + if list.is_null() { |
| 619 | + return 0; |
| 620 | + } |
| 253 | 621 | |
| 254 | 622 | let count = CFArrayGetCount(list); |
| 255 | | - let wid_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowNumber\0".as_ptr(), kCFStringEncodingUTF8); |
| 256 | | - let pid_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowOwnerPID\0".as_ptr(), kCFStringEncodingUTF8); |
| 257 | | - let layer_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowLayer\0".as_ptr(), kCFStringEncodingUTF8); |
| 623 | + let wid_key = cf_string_from_static(c"kCGWindowNumber"); |
| 624 | + let pid_key = cf_string_from_static(c"kCGWindowOwnerPID"); |
| 625 | + let layer_key = cf_string_from_static(c"kCGWindowLayer"); |
| 258 | 626 | |
| 259 | 627 | let mut front_wid: u32 = 0; |
| 628 | + let mut front_bounds = CGRect::default(); |
| 629 | + let mut have_front_bounds = false; |
| 260 | 630 | let mut fallback_wid: u32 = 0; |
| 261 | 631 | for i in 0..count { |
| 262 | 632 | let dict = CFArrayGetValueAtIndex(list, i); |
| 263 | | - if dict.is_null() { continue; } |
| 633 | + if dict.is_null() { |
| 634 | + continue; |
| 635 | + } |
| 264 | 636 | |
| 265 | 637 | let mut v: CFTypeRef = ptr::null(); |
| 266 | 638 | |
@@ -268,29 +640,62 @@ fn get_front_window(own_pid: i32) -> u32 { |
| 268 | 640 | if CFDictionaryGetValueIfPresent(dict, layer_key as CFTypeRef, &mut v) { |
| 269 | 641 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut layer as *mut _ as *mut _); |
| 270 | 642 | } |
| 271 | | - if layer != 0 { continue; } |
| 643 | + if layer != 0 { |
| 644 | + continue; |
| 645 | + } |
| 272 | 646 | |
| 273 | 647 | let mut pid: i32 = 0; |
| 274 | 648 | if CFDictionaryGetValueIfPresent(dict, pid_key as CFTypeRef, &mut v) { |
| 275 | 649 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut pid as *mut _ as *mut _); |
| 276 | 650 | } |
| 277 | | - if pid == own_pid { continue; } |
| 651 | + if pid == own_pid { |
| 652 | + continue; |
| 653 | + } |
| 278 | 654 | |
| 279 | 655 | let mut wid: u32 = 0; |
| 280 | 656 | if CFDictionaryGetValueIfPresent(dict, wid_key as CFTypeRef, &mut v) { |
| 281 | 657 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut wid as *mut _ as *mut _); |
| 282 | 658 | } |
| 283 | | - if wid == 0 { continue; } |
| 659 | + if wid == 0 { |
| 660 | + continue; |
| 661 | + } |
| 662 | + |
| 663 | + if !is_suitable_window(SLSMainConnectionID(), wid) { |
| 664 | + continue; |
| 665 | + } |
| 284 | 666 | |
| 285 | 667 | // Track first non-self window as fallback (z-order based) |
| 286 | 668 | if fallback_wid == 0 { |
| 287 | 669 | fallback_wid = wid; |
| 288 | 670 | } |
| 289 | 671 | |
| 290 | | - // Prefer a window from the front process |
| 672 | + // Prefer a window from the front process. If another layer-0 surface |
| 673 | + // from that app nearly fully contains the current one, treat the |
| 674 | + // larger surface as the real window. Firefox can surface a tab-strip |
| 675 | + // child ahead of the outer window after a tile. |
| 291 | 676 | if pid == front_pid { |
| 292 | | - front_wid = wid; |
| 293 | | - break; |
| 677 | + let mut bounds = CGRect::default(); |
| 678 | + if SLSGetWindowBounds(SLSMainConnectionID(), wid, &mut bounds) != kCGErrorSuccess { |
| 679 | + if front_wid == 0 { |
| 680 | + front_wid = wid; |
| 681 | + } |
| 682 | + continue; |
| 683 | + } |
| 684 | + |
| 685 | + if front_wid == 0 { |
| 686 | + front_wid = wid; |
| 687 | + front_bounds = bounds; |
| 688 | + have_front_bounds = true; |
| 689 | + continue; |
| 690 | + } |
| 691 | + |
| 692 | + if have_front_bounds |
| 693 | + && is_same_window_surface(front_bounds, bounds) |
| 694 | + && window_area(bounds) > window_area(front_bounds) |
| 695 | + { |
| 696 | + front_wid = wid; |
| 697 | + front_bounds = bounds; |
| 698 | + } |
| 294 | 699 | } |
| 295 | 700 | } |
| 296 | 701 | |
@@ -311,13 +716,17 @@ fn get_front_window(own_pid: i32) -> u32 { |
| 311 | 716 | /// Parse hex color string (#RRGGBB or #RRGGBBAA) to (r, g, b, a) floats. |
| 312 | 717 | fn parse_color(s: &str) -> Option<(f64, f64, f64, f64)> { |
| 313 | 718 | let hex = s.strip_prefix('#').unwrap_or(s); |
| 314 | | - if hex.len() != 6 && hex.len() != 8 { return None; } |
| 719 | + if hex.len() != 6 && hex.len() != 8 { |
| 720 | + return None; |
| 721 | + } |
| 315 | 722 | let r = u8::from_str_radix(&hex[0..2], 16).ok()? as f64 / 255.0; |
| 316 | 723 | let g = u8::from_str_radix(&hex[2..4], 16).ok()? as f64 / 255.0; |
| 317 | 724 | let b = u8::from_str_radix(&hex[4..6], 16).ok()? as f64 / 255.0; |
| 318 | 725 | let a = if hex.len() == 8 { |
| 319 | 726 | u8::from_str_radix(&hex[6..8], 16).ok()? as f64 / 255.0 |
| 320 | | - } else { 1.0 }; |
| 727 | + } else { |
| 728 | + 1.0 |
| 729 | + }; |
| 321 | 730 | Some((r, g, b, a)) |
| 322 | 731 | } |
| 323 | 732 | |
@@ -344,10 +753,13 @@ fn print_help() { |
| 344 | 753 | } |
| 345 | 754 | |
| 346 | 755 | fn main() { |
| 756 | + let env_filter = tracing_subscriber::EnvFilter::try_from_default_env() |
| 757 | + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("ers=info")); |
| 347 | 758 | tracing_subscriber::fmt() |
| 348 | | - .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) |
| 759 | + .with_env_filter(env_filter) |
| 349 | 760 | .with_writer(std::io::stderr) |
| 350 | 761 | .init(); |
| 762 | + debug!("[main] ers starting, pid={}", std::process::id()); |
| 351 | 763 | |
| 352 | 764 | let args: Vec<String> = std::env::args().collect(); |
| 353 | 765 | |
@@ -379,6 +791,13 @@ fn main() { |
| 379 | 791 | |
| 380 | 792 | let active_only = args.iter().any(|s| s == "--active-only"); |
| 381 | 793 | |
| 794 | + // Initialize NSApplication on the main thread before we touch any |
| 795 | + // AppKit APIs. NSWindow operations (used by nswindow_overlay) all |
| 796 | + // require a main-thread context. |
| 797 | + let mtm = nswindow_overlay::init_application(); |
| 798 | + nswindow_overlay::log_screens(mtm); |
| 799 | + register_display_hotplug_callback(); |
| 800 | + |
| 382 | 801 | let cid = unsafe { SLSMainConnectionID() }; |
| 383 | 802 | let own_pid = unsafe { |
| 384 | 803 | let mut pid: i32 = 0; |
@@ -393,7 +812,7 @@ fn main() { |
| 393 | 812 | setup_event_port(cid); |
| 394 | 813 | |
| 395 | 814 | // Discover and create borders |
| 396 | | - let mut borders = BorderMap::new(cid, own_pid, border_width); |
| 815 | + let mut borders = BorderMap::new(cid, own_pid, border_width, mtm); |
| 397 | 816 | borders.radius = radius; |
| 398 | 817 | borders.active_color = active_color; |
| 399 | 818 | borders.inactive_color = inactive_color; |
@@ -414,7 +833,9 @@ fn main() { |
| 414 | 833 | |
| 415 | 834 | if borders.active_only { |
| 416 | 835 | let focused = borders.focused_wid; |
| 417 | | - let to_hide: Vec<u32> = borders.overlays.keys() |
| 836 | + let to_hide: Vec<u32> = borders |
| 837 | + .overlays |
| 838 | + .keys() |
| 418 | 839 | .filter(|&&wid| wid != focused) |
| 419 | 840 | .copied() |
| 420 | 841 | .collect(); |
@@ -425,187 +846,354 @@ fn main() { |
| 425 | 846 | |
| 426 | 847 | debug!("{} overlays tracked", borders.overlays.len()); |
| 427 | 848 | |
| 428 | | - // SIGINT flag — background thread checks this to clean up |
| 849 | + SIGNAL_STOP_REQUESTED.store(false, Ordering::Relaxed); |
| 850 | + |
| 851 | + // Background watcher translates the signal-safe atomic into a normal |
| 852 | + // CoreFoundation shutdown request on a Rust thread. |
| 429 | 853 | let running = Arc::new(AtomicBool::new(true)); |
| 854 | + let signal_watcher = std::thread::spawn(|| { |
| 855 | + use std::time::Duration; |
| 856 | + |
| 857 | + while !SIGNAL_STOP_REQUESTED.load(Ordering::Relaxed) { |
| 858 | + std::thread::sleep(Duration::from_millis(10)); |
| 859 | + } |
| 860 | + |
| 861 | + unsafe { |
| 862 | + let run_loop = CFRunLoopGetMain(); |
| 863 | + CFRunLoopStop(run_loop); |
| 864 | + CFRunLoopWakeUp(run_loop); |
| 865 | + } |
| 866 | + }); |
| 867 | + |
| 430 | 868 | unsafe { |
| 431 | | - libc::signal(libc::SIGINT, { |
| 432 | | - unsafe extern "C" fn handler(_: libc::c_int) { |
| 433 | | - unsafe { |
| 434 | | - CFRunLoopStop(CFRunLoopGetMain()); |
| 435 | | - } |
| 436 | | - } |
| 437 | | - handler as *const () as libc::sighandler_t |
| 438 | | - }); |
| 869 | + libc::signal( |
| 870 | + libc::SIGINT, |
| 871 | + handle_sigint as *const () as libc::sighandler_t, |
| 872 | + ); |
| 873 | + libc::signal( |
| 874 | + libc::SIGTERM, |
| 875 | + handle_sigint as *const () as libc::sighandler_t, |
| 876 | + ); |
| 439 | 877 | } |
| 440 | 878 | |
| 441 | | - // Process events on background thread with coalescing |
| 442 | | - let running_bg = Arc::clone(&running); |
| 443 | | - let handle = std::thread::spawn(move || { |
| 444 | | - use std::collections::HashSet; |
| 445 | | - use std::time::Duration; |
| 879 | + // Process events on the main thread via a CFRunLoopTimer. |
| 880 | + // BorderMap holds Retained<NSWindow> handles, which are |
| 881 | + // !Send/!Sync — AppKit calls must originate from the main thread. |
| 882 | + // Stash state in thread_local for the C callback to access. |
| 883 | + MAIN_STATE.with(|cell| { |
| 884 | + *cell.borrow_mut() = Some(MainState { |
| 885 | + borders, |
| 886 | + rx, |
| 887 | + pending: HashMap::new(), |
| 888 | + batch_events: Vec::new(), |
| 889 | + batch_first_seen: None, |
| 890 | + }); |
| 891 | + }); |
| 446 | 892 | |
| 447 | | - // Persist across batches: windows we know about but haven't bordered yet |
| 448 | | - let mut pending: HashSet<u32> = HashSet::new(); |
| 893 | + unsafe { |
| 894 | + let mut ctx = CFRunLoopTimerContext { |
| 895 | + version: 0, |
| 896 | + info: ptr::null_mut(), |
| 897 | + retain: None, |
| 898 | + release: None, |
| 899 | + copy_description: None, |
| 900 | + }; |
| 901 | + let timer = CFRunLoopTimerCreate( |
| 902 | + ptr::null(), |
| 903 | + CFAbsoluteTimeGetCurrent() + 0.05, |
| 904 | + 0.016, |
| 905 | + 0u64, |
| 906 | + 0i64, |
| 907 | + timer_callback, |
| 908 | + &mut ctx, |
| 909 | + ); |
| 910 | + CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopDefaultMode); |
| 911 | + } |
| 449 | 912 | |
| 450 | | - while running_bg.load(Ordering::Relaxed) { |
| 451 | | - let first = match rx.recv_timeout(Duration::from_millis(100)) { |
| 452 | | - Ok(e) => e, |
| 453 | | - Err(mpsc::RecvTimeoutError::Timeout) => continue, |
| 454 | | - Err(mpsc::RecvTimeoutError::Disconnected) => break, |
| 455 | | - }; |
| 913 | + unsafe { CFRunLoopRun() }; |
| 456 | 914 | |
| 457 | | - std::thread::sleep(std::time::Duration::from_millis(16)); |
| 915 | + // Drop everything on the main thread (NSWindow.close in Drop). |
| 916 | + MAIN_STATE.with(|cell| cell.borrow_mut().take()); |
| 458 | 917 | |
| 459 | | - let mut events = vec![first]; |
| 460 | | - while let Ok(e) = rx.try_recv() { |
| 461 | | - events.push(e); |
| 462 | | - } |
| 918 | + SIGNAL_STOP_REQUESTED.store(true, Ordering::Relaxed); |
| 919 | + let _ = signal_watcher.join(); |
| 920 | + drop(running); |
| 921 | +} |
| 463 | 922 | |
| 464 | | - let mut moved: HashSet<u32> = HashSet::new(); |
| 465 | | - let mut resized: HashSet<u32> = HashSet::new(); |
| 466 | | - let mut destroyed: HashSet<u32> = HashSet::new(); |
| 467 | | - let mut needs_resubscribe = false; |
| 923 | +struct MainState { |
| 924 | + borders: BorderMap, |
| 925 | + rx: mpsc::Receiver<Event>, |
| 926 | + pending: HashMap<u32, std::time::Instant>, |
| 927 | + batch_events: Vec<Event>, |
| 928 | + batch_first_seen: Option<std::time::Instant>, |
| 929 | +} |
| 468 | 930 | |
| 469 | | - for event in events { |
| 470 | | - match event { |
| 471 | | - Event::Move(wid) => { |
| 472 | | - if !borders.is_overlay(wid) { |
| 473 | | - moved.insert(wid); |
| 474 | | - } |
| 475 | | - } |
| 476 | | - Event::Resize(wid) => { |
| 477 | | - if !borders.is_overlay(wid) { |
| 478 | | - resized.insert(wid); |
| 479 | | - } |
| 480 | | - } |
| 481 | | - Event::Close(wid) | Event::Destroy(wid) => { |
| 482 | | - if !borders.is_overlay(wid) { |
| 483 | | - destroyed.insert(wid); |
| 484 | | - pending.remove(&wid); |
| 485 | | - } |
| 486 | | - } |
| 487 | | - Event::Create(wid) => { |
| 488 | | - if !borders.is_overlay(wid) { |
| 489 | | - pending.insert(wid); |
| 490 | | - borders.subscribe_target(wid); |
| 491 | | - } |
| 492 | | - } |
| 493 | | - Event::Hide(wid) => borders.hide(wid), |
| 494 | | - Event::Unhide(wid) => { |
| 495 | | - if !borders.active_only || wid == borders.focused_wid { |
| 496 | | - borders.unhide(wid); |
| 497 | | - } |
| 498 | | - } |
| 499 | | - Event::FrontChange => { |
| 500 | | - needs_resubscribe = true; |
| 501 | | - } |
| 502 | | - Event::SpaceChange => { |
| 503 | | - needs_resubscribe = true; |
| 931 | +thread_local! { |
| 932 | + static MAIN_STATE: std::cell::RefCell<Option<MainState>> = const { std::cell::RefCell::new(None) }; |
| 933 | +} |
| 934 | + |
| 935 | +extern "C" fn timer_callback(_timer: *mut std::ffi::c_void, _info: *mut std::ffi::c_void) { |
| 936 | + use std::time::{Duration, Instant}; |
| 937 | + use std::sync::atomic::AtomicUsize; |
| 938 | + static TICK_COUNT: AtomicUsize = AtomicUsize::new(0); |
| 939 | + let tick = TICK_COUNT.fetch_add(1, Ordering::Relaxed); |
| 940 | + if tick == 0 { |
| 941 | + debug!("[timer] first fire — main-thread event loop is alive"); |
| 942 | + } else if tick % 600 == 0 { |
| 943 | + // every ~10s if interval is 16ms |
| 944 | + debug!("[timer] tick {}", tick); |
| 945 | + } |
| 946 | + MAIN_STATE.with(|cell| { |
| 947 | + let mut state_opt = cell.borrow_mut(); |
| 948 | + let s = match state_opt.as_mut() { |
| 949 | + Some(s) => s, |
| 950 | + None => return, |
| 951 | + }; |
| 952 | + let mut received = 0usize; |
| 953 | + loop { |
| 954 | + match s.rx.try_recv() { |
| 955 | + Ok(e) => { |
| 956 | + if s.batch_events.is_empty() { |
| 957 | + s.batch_first_seen = Some(Instant::now()); |
| 504 | 958 | } |
| 959 | + s.batch_events.push(e); |
| 960 | + received += 1; |
| 505 | 961 | } |
| 962 | + Err(mpsc::TryRecvError::Empty) => break, |
| 963 | + Err(mpsc::TryRecvError::Disconnected) => break, |
| 506 | 964 | } |
| 507 | | - |
| 508 | | - // Destroys |
| 509 | | - for wid in &destroyed { |
| 510 | | - borders.remove(*wid); |
| 511 | | - } |
| 512 | | - |
| 513 | | - // Promote ALL pending creates that weren't destroyed |
| 514 | | - // (the 150ms debounce is enough for tarmac to position them) |
| 515 | | - let ready: Vec<u32> = pending.iter() |
| 516 | | - .filter(|wid| !destroyed.contains(wid)) |
| 517 | | - .copied() |
| 518 | | - .collect(); |
| 519 | | - // Filter overlapping creates: if two windows overlap, keep smaller one |
| 520 | | - let mut bounds_map: Vec<(u32, CGRect)> = Vec::new(); |
| 521 | | - for &wid in &ready { |
| 522 | | - unsafe { |
| 523 | | - let mut b = CGRect::default(); |
| 524 | | - SLSGetWindowBounds(borders.main_cid, wid, &mut b); |
| 525 | | - bounds_map.push((wid, b)); |
| 965 | + } |
| 966 | + if received > 0 { |
| 967 | + debug!( |
| 968 | + "[timer] received {} new events; batch size now {}", |
| 969 | + received, |
| 970 | + s.batch_events.len() |
| 971 | + ); |
| 972 | + } |
| 973 | + // Process the accumulated batch after a 16ms quiet window |
| 974 | + // (matches the old bg-thread behavior where it slept 16ms after |
| 975 | + // the first event then drained). Events keep arriving, the batch |
| 976 | + // grows; once 16ms passes without new events we flush. |
| 977 | + let should_flush = s.batch_first_seen.is_some_and(|t| { |
| 978 | + t.elapsed() >= Duration::from_millis(16) && received == 0 |
| 979 | + }) || s |
| 980 | + .batch_first_seen |
| 981 | + .is_some_and(|t| t.elapsed() >= Duration::from_millis(120)); |
| 982 | + if should_flush { |
| 983 | + let events = std::mem::take(&mut s.batch_events); |
| 984 | + s.batch_first_seen = None; |
| 985 | + debug!("[timer] processing batch of {}", events.len()); |
| 986 | + process_event_batch(&mut s.borders, &mut s.pending, events); |
| 987 | + } else { |
| 988 | + // Even with no events, poll focus periodically so a missed |
| 989 | + // FrontChange notification doesn't strand the active border. |
| 990 | + // Cheap operation when focus hasn't changed. |
| 991 | + s.borders.update_focus(); |
| 992 | + // Once per second, reconcile tracked overlays against |
| 993 | + // current SLS state. Catches missed Close/Destroy events |
| 994 | + // that would otherwise leave a dead border on screen. |
| 995 | + if tick % 60 == 0 && tick > 0 { |
| 996 | + let removed = s.borders.reconcile_tracked(); |
| 997 | + if removed { |
| 998 | + debug!("[timer] periodic reconcile removed stale overlays"); |
| 526 | 999 | } |
| 1000 | + // Cheap: re-applies just the CAShapeLayer frame/path |
| 1001 | + // for every overlay. Recovers from layer state that |
| 1002 | + // macOS resets during display sleep/wake without |
| 1003 | + // touching the NSWindow frame. |
| 1004 | + s.borders.refresh_all_layers(); |
| 527 | 1005 | } |
| 1006 | + } |
| 1007 | + }); |
| 1008 | +} |
| 528 | 1009 | |
| 529 | | - // If two new windows overlap closely, skip the larger one (container) |
| 530 | | - let mut skip: std::collections::HashSet<u32> = HashSet::new(); |
| 531 | | - for i in 0..bounds_map.len() { |
| 532 | | - for j in (i+1)..bounds_map.len() { |
| 533 | | - let (wid_a, a) = &bounds_map[i]; |
| 534 | | - let (wid_b, b) = &bounds_map[j]; |
| 535 | | - // Check if centers are close (within 30px) |
| 536 | | - let cx_a = a.origin.x + a.size.width / 2.0; |
| 537 | | - let cy_a = a.origin.y + a.size.height / 2.0; |
| 538 | | - let cx_b = b.origin.x + b.size.width / 2.0; |
| 539 | | - let cy_b = b.origin.y + b.size.height / 2.0; |
| 540 | | - if (cx_a - cx_b).abs() < 30.0 && (cy_a - cy_b).abs() < 30.0 { |
| 541 | | - // Skip the larger one |
| 542 | | - let area_a = a.size.width * a.size.height; |
| 543 | | - let area_b = b.size.width * b.size.height; |
| 544 | | - if area_a > area_b { |
| 545 | | - skip.insert(*wid_a); |
| 546 | | - } else { |
| 547 | | - skip.insert(*wid_b); |
| 548 | | - } |
| 549 | | - } |
| 1010 | +fn process_event_batch( |
| 1011 | + borders: &mut BorderMap, |
| 1012 | + pending: &mut HashMap<u32, std::time::Instant>, |
| 1013 | + events: Vec<Event>, |
| 1014 | +) { |
| 1015 | + use std::collections::HashSet; |
| 1016 | + use std::time::{Duration, Instant}; |
| 1017 | + |
| 1018 | + let mut moved: HashSet<u32> = HashSet::new(); |
| 1019 | + let mut resized: HashSet<u32> = HashSet::new(); |
| 1020 | + let mut destroyed: HashSet<u32> = HashSet::new(); |
| 1021 | + let mut needs_resubscribe = false; |
| 1022 | + |
| 1023 | + for event in events { |
| 1024 | + match event { |
| 1025 | + Event::Move(wid) => { |
| 1026 | + if !borders.is_overlay(wid) { |
| 1027 | + moved.insert(wid); |
| 550 | 1028 | } |
| 551 | 1029 | } |
| 552 | | - |
| 553 | | - for &wid in &ready { |
| 554 | | - pending.remove(&wid); |
| 555 | | - if !skip.contains(&wid) { |
| 556 | | - borders.add_fresh(wid); |
| 557 | | - if borders.active_only && wid != borders.focused_wid { |
| 558 | | - borders.hide(wid); |
| 559 | | - } |
| 560 | | - needs_resubscribe = true; |
| 1030 | + Event::Resize(wid) => { |
| 1031 | + if !borders.is_overlay(wid) { |
| 1032 | + resized.insert(wid); |
| 561 | 1033 | } |
| 562 | 1034 | } |
| 563 | | - |
| 564 | | - // Moves: reposition overlay (no destroy/create) |
| 565 | | - for wid in &moved { |
| 566 | | - if !resized.contains(wid) && !ready.contains(wid) { |
| 567 | | - borders.reposition(*wid); |
| 1035 | + Event::Close(wid) | Event::Destroy(wid) => { |
| 1036 | + if !borders.is_overlay(wid) { |
| 1037 | + debug!("[event] Close/Destroy target_wid={}", wid); |
| 1038 | + destroyed.insert(wid); |
| 1039 | + pending.remove(&wid); |
| 568 | 1040 | } |
| 569 | 1041 | } |
| 570 | | - |
| 571 | | - // Resizes: must recreate (can't reshape windows on Tahoe) |
| 572 | | - // Skip windows just created this batch — already at correct size |
| 573 | | - for wid in &resized { |
| 574 | | - if !ready.contains(wid) && borders.overlays.contains_key(wid) { |
| 575 | | - borders.recreate(*wid); |
| 576 | | - needs_resubscribe = true; |
| 1042 | + Event::Create(wid) => { |
| 1043 | + if !borders.is_overlay(wid) { |
| 1044 | + pending.entry(wid).or_insert_with(Instant::now); |
| 1045 | + borders.subscribe_target(wid); |
| 1046 | + } |
| 1047 | + } |
| 1048 | + Event::Hide(wid) => borders.hide(wid), |
| 1049 | + Event::Unhide(wid) => { |
| 1050 | + if !borders.is_overlay(wid) { |
| 1051 | + if !borders.overlays.contains_key(&wid) { |
| 1052 | + borders.add_fresh(wid); |
| 1053 | + borders.subscribe_target(wid); |
| 1054 | + } |
| 1055 | + if !borders.active_only || wid == borders.focused_wid { |
| 1056 | + borders.unhide(wid); |
| 1057 | + } |
| 577 | 1058 | } |
| 578 | 1059 | } |
| 1060 | + Event::FrontChange => { |
| 1061 | + needs_resubscribe = true; |
| 1062 | + } |
| 1063 | + Event::SpaceChange => { |
| 1064 | + needs_resubscribe = true; |
| 1065 | + } |
| 1066 | + } |
| 1067 | + } |
| 579 | 1068 | |
| 580 | | - // Update focus (redraws borders in-place if changed) |
| 581 | | - borders.update_focus(); |
| 1069 | + for wid in &destroyed { |
| 1070 | + borders.remove(*wid); |
| 1071 | + } |
| 582 | 1072 | |
| 583 | | - // Re-subscribe ALL tracked windows (SLSRequestNotificationsForWindows replaces, not appends) |
| 584 | | - if needs_resubscribe || !destroyed.is_empty() { |
| 585 | | - borders.subscribe_all(); |
| 1073 | + let now = Instant::now(); |
| 1074 | + let ready: Vec<u32> = pending |
| 1075 | + .iter() |
| 1076 | + .filter(|(wid, seen_at)| { |
| 1077 | + !destroyed.contains(wid) && now.duration_since(**seen_at) >= Duration::from_millis(100) |
| 1078 | + }) |
| 1079 | + .map(|(wid, _)| *wid) |
| 1080 | + .collect(); |
| 1081 | + |
| 1082 | + let mut bounds_map: Vec<(u32, CGRect)> = Vec::new(); |
| 1083 | + for &wid in &ready { |
| 1084 | + unsafe { |
| 1085 | + let mut b = CGRect::default(); |
| 1086 | + SLSGetWindowBounds(borders.main_cid, wid, &mut b); |
| 1087 | + bounds_map.push((wid, b)); |
| 1088 | + } |
| 1089 | + } |
| 1090 | + |
| 1091 | + let mut skip: std::collections::HashSet<u32> = HashSet::new(); |
| 1092 | + for i in 0..bounds_map.len() { |
| 1093 | + for j in (i + 1)..bounds_map.len() { |
| 1094 | + let (wid_a, a) = &bounds_map[i]; |
| 1095 | + let (wid_b, b) = &bounds_map[j]; |
| 1096 | + if let Some(preference) = surface_preference(*a, *b) { |
| 1097 | + match preference { |
| 1098 | + SurfacePreference::KeepExisting => { |
| 1099 | + skip.insert(*wid_b); |
| 1100 | + } |
| 1101 | + SurfacePreference::ReplaceExisting => { |
| 1102 | + skip.insert(*wid_a); |
| 1103 | + } |
| 1104 | + } |
| 586 | 1105 | } |
| 1106 | + } |
| 1107 | + } |
| 587 | 1108 | |
| 588 | | - // After all processing, enforce active-only visibility |
| 589 | | - borders.enforce_active_only(); |
| 1109 | + for &wid in &ready { |
| 1110 | + pending.remove(&wid); |
| 1111 | + if !skip.contains(&wid) { |
| 1112 | + borders.add_fresh(wid); |
| 1113 | + if borders.active_only && wid != borders.focused_wid { |
| 1114 | + borders.hide(wid); |
| 1115 | + } |
| 1116 | + needs_resubscribe = true; |
| 590 | 1117 | } |
| 1118 | + } |
| 591 | 1119 | |
| 592 | | - // Clean up all overlays before exiting |
| 593 | | - borders.remove_all(); |
| 594 | | - }); |
| 1120 | + for wid in &moved { |
| 1121 | + if !resized.contains(wid) && !ready.contains(wid) && borders.sync_overlay(*wid) { |
| 1122 | + needs_resubscribe = true; |
| 1123 | + } |
| 1124 | + } |
| 595 | 1125 | |
| 596 | | - unsafe { CFRunLoopRun() }; |
| 1126 | + for wid in &resized { |
| 1127 | + if !ready.contains(wid) |
| 1128 | + && borders.overlays.contains_key(wid) |
| 1129 | + && borders.sync_overlay(*wid) |
| 1130 | + { |
| 1131 | + needs_resubscribe = true; |
| 1132 | + } |
| 1133 | + } |
| 1134 | + |
| 1135 | + if needs_resubscribe { |
| 1136 | + borders.discover_untracked(); |
| 1137 | + } |
| 1138 | + |
| 1139 | + needs_resubscribe |= borders.reconcile_tracked(); |
| 1140 | + |
| 1141 | + borders.update_focus(); |
| 597 | 1142 | |
| 598 | | - // SIGINT received — signal background thread to stop and wait |
| 599 | | - running.store(false, Ordering::Relaxed); |
| 600 | | - let _ = handle.join(); |
| 1143 | + if needs_resubscribe || !destroyed.is_empty() { |
| 1144 | + borders.subscribe_all(); |
| 1145 | + } |
| 1146 | + |
| 1147 | + borders.enforce_active_only(); |
| 1148 | +} |
| 1149 | + |
| 1150 | +/// Re-log the screen layout when the display configuration changes |
| 1151 | +/// (monitor plug/unplug, resolution change). The callback also nudges |
| 1152 | +/// every tracked overlay to re-fetch its bounds so any cached cocoa Y |
| 1153 | +/// computed against the old primary height gets refreshed. |
| 1154 | +unsafe extern "C" fn display_reconfig_callback( |
| 1155 | + display_id: u32, |
| 1156 | + flags: u32, |
| 1157 | + _user_info: *mut std::ffi::c_void, |
| 1158 | +) { |
| 1159 | + debug!(display_id, flags, "[hotplug] CGDisplay reconfiguration"); |
| 1160 | + if let Some(mtm) = objc2::MainThreadMarker::new() { |
| 1161 | + nswindow_overlay::log_screens(mtm); |
| 1162 | + } |
| 1163 | + MAIN_STATE.with(|cell| { |
| 1164 | + if let Some(s) = cell.borrow_mut().as_mut() { |
| 1165 | + s.borders.reconcile_all_force(); |
| 1166 | + s.borders.refresh_all_layers(); |
| 1167 | + } |
| 1168 | + }); |
| 1169 | +} |
| 1170 | + |
| 1171 | +fn register_display_hotplug_callback() { |
| 1172 | + unsafe { |
| 1173 | + let rc = CGDisplayRegisterReconfigurationCallback( |
| 1174 | + Some(display_reconfig_callback), |
| 1175 | + std::ptr::null_mut(), |
| 1176 | + ); |
| 1177 | + debug!("[hotplug] register CGDisplayReconfiguration rc={}", rc); |
| 1178 | + } |
| 601 | 1179 | } |
| 602 | 1180 | |
| 603 | 1181 | fn setup_event_port(cid: CGSConnectionID) { |
| 604 | 1182 | unsafe { |
| 605 | 1183 | let mut port: u32 = 0; |
| 606 | | - if SLSGetEventPort(cid, &mut port) != kCGErrorSuccess { return; } |
| 607 | | - let cf_port = CFMachPortCreateWithPort(ptr::null(), port, drain_events as *const _, ptr::null(), false); |
| 608 | | - if cf_port.is_null() { return; } |
| 1184 | + if SLSGetEventPort(cid, &mut port) != kCGErrorSuccess { |
| 1185 | + return; |
| 1186 | + } |
| 1187 | + let cf_port = CFMachPortCreateWithPort( |
| 1188 | + ptr::null(), |
| 1189 | + port, |
| 1190 | + drain_events as *const _, |
| 1191 | + ptr::null(), |
| 1192 | + false, |
| 1193 | + ); |
| 1194 | + if cf_port.is_null() { |
| 1195 | + return; |
| 1196 | + } |
| 609 | 1197 | _CFMachPortSetOptions(cf_port, 0x40); |
| 610 | 1198 | let source = CFMachPortCreateRunLoopSource(ptr::null(), cf_port, 0); |
| 611 | 1199 | if !source.is_null() { |
@@ -616,7 +1204,12 @@ fn setup_event_port(cid: CGSConnectionID) { |
| 616 | 1204 | } |
| 617 | 1205 | } |
| 618 | 1206 | |
| 619 | | -unsafe extern "C" fn drain_events(_: CFMachPortRef, _: *mut std::ffi::c_void, _: i64, _: *mut std::ffi::c_void) { |
| 1207 | +unsafe extern "C" fn drain_events( |
| 1208 | + _: CFMachPortRef, |
| 1209 | + _: *mut std::ffi::c_void, |
| 1210 | + _: i64, |
| 1211 | + _: *mut std::ffi::c_void, |
| 1212 | +) { |
| 620 | 1213 | unsafe { |
| 621 | 1214 | let cid = SLSMainConnectionID(); |
| 622 | 1215 | let mut ev = SLEventCreateNextEvent(cid); |
@@ -627,39 +1220,53 @@ unsafe extern "C" fn drain_events(_: CFMachPortRef, _: *mut std::ffi::c_void, _: |
| 627 | 1220 | } |
| 628 | 1221 | } |
| 629 | 1222 | |
| 630 | | -fn discover_windows(_cid: CGSConnectionID, own_pid: i32) -> Vec<u32> { |
| 1223 | +fn discover_windows(cid: CGSConnectionID, own_pid: i32) -> Vec<u32> { |
| 631 | 1224 | unsafe { |
| 632 | 1225 | let list = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID); |
| 633 | | - if list.is_null() { return vec![]; } |
| 1226 | + if list.is_null() { |
| 1227 | + return vec![]; |
| 1228 | + } |
| 634 | 1229 | |
| 635 | 1230 | let count = CFArrayGetCount(list); |
| 636 | | - let wid_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowNumber\0".as_ptr(), kCFStringEncodingUTF8); |
| 637 | | - let pid_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowOwnerPID\0".as_ptr(), kCFStringEncodingUTF8); |
| 638 | | - let layer_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowLayer\0".as_ptr(), kCFStringEncodingUTF8); |
| 1231 | + let wid_key = cf_string_from_static(c"kCGWindowNumber"); |
| 1232 | + let pid_key = cf_string_from_static(c"kCGWindowOwnerPID"); |
| 1233 | + let layer_key = cf_string_from_static(c"kCGWindowLayer"); |
| 639 | 1234 | |
| 640 | 1235 | let mut wids = Vec::new(); |
| 641 | 1236 | for i in 0..count { |
| 642 | 1237 | let dict = CFArrayGetValueAtIndex(list, i); |
| 643 | | - if dict.is_null() { continue; } |
| 1238 | + if dict.is_null() { |
| 1239 | + continue; |
| 1240 | + } |
| 644 | 1241 | |
| 645 | 1242 | let mut v: CFTypeRef = ptr::null(); |
| 646 | 1243 | let mut wid: u32 = 0; |
| 647 | 1244 | if CFDictionaryGetValueIfPresent(dict, wid_key as CFTypeRef, &mut v) { |
| 648 | 1245 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut wid as *mut _ as *mut _); |
| 649 | 1246 | } |
| 650 | | - if wid == 0 { continue; } |
| 1247 | + if wid == 0 { |
| 1248 | + continue; |
| 1249 | + } |
| 651 | 1250 | |
| 652 | 1251 | let mut pid: i32 = 0; |
| 653 | 1252 | if CFDictionaryGetValueIfPresent(dict, pid_key as CFTypeRef, &mut v) { |
| 654 | 1253 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut pid as *mut _ as *mut _); |
| 655 | 1254 | } |
| 656 | | - if pid == own_pid { continue; } |
| 1255 | + if pid == own_pid { |
| 1256 | + continue; |
| 1257 | + } |
| 1258 | + |
| 1259 | + if !is_suitable_window(cid, wid) { |
| 1260 | + continue; |
| 1261 | + } |
| 657 | 1262 | |
| 658 | 1263 | let mut layer: i32 = -1; |
| 659 | 1264 | if CFDictionaryGetValueIfPresent(dict, layer_key as CFTypeRef, &mut v) { |
| 660 | 1265 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut layer as *mut _ as *mut _); |
| 661 | 1266 | } |
| 662 | | - if layer != 0 { continue; } |
| 1267 | + if layer != 0 { |
| 1268 | + continue; |
| 1269 | + } |
| 663 | 1270 | |
| 664 | 1271 | wids.push(wid); |
| 665 | 1272 | } |
@@ -672,114 +1279,26 @@ fn discover_windows(_cid: CGSConnectionID, own_pid: i32) -> Vec<u32> { |
| 672 | 1279 | } |
| 673 | 1280 | } |
| 674 | 1281 | |
| 675 | | -/// Draw a border ring into an existing CGContext, clearing first. |
| 676 | | -fn draw_border( |
| 677 | | - ctx: CGContextRef, |
| 678 | | - width: f64, |
| 679 | | - height: f64, |
| 680 | | - border_width: f64, |
| 681 | | - radius: f64, |
| 682 | | - color: (f64, f64, f64, f64), |
| 683 | | -) { |
| 684 | | - unsafe { |
| 685 | | - let full = CGRect::new(0.0, 0.0, width, height); |
| 686 | | - CGContextClearRect(ctx, full); |
| 687 | | - |
| 688 | | - let bw = border_width; |
| 689 | | - let stroke_rect = CGRect::new(bw / 2.0, bw / 2.0, width - bw, height - bw); |
| 690 | | - let max_r = (stroke_rect.size.width.min(stroke_rect.size.height) / 2.0).max(0.0); |
| 691 | | - let r = radius.min(max_r); |
| 692 | | - |
| 693 | | - CGContextSetRGBStrokeColor(ctx, color.0, color.1, color.2, color.3); |
| 694 | | - CGContextSetLineWidth(ctx, bw); |
| 695 | | - let path = CGPathCreateWithRoundedRect(stroke_rect, r, r, ptr::null()); |
| 696 | | - if !path.is_null() { |
| 697 | | - CGContextAddPath(ctx, path); |
| 698 | | - CGContextStrokePath(ctx); |
| 699 | | - CGPathRelease(path); |
| 700 | | - } |
| 701 | | - CGContextFlush(ctx); |
| 702 | | - } |
| 703 | | -} |
| 704 | | - |
| 705 | | -fn create_overlay( |
| 706 | | - cid: CGSConnectionID, |
| 707 | | - target_wid: u32, |
| 708 | | - border_width: f64, |
| 709 | | - radius: f64, |
| 710 | | - color: (f64, f64, f64, f64), |
| 711 | | -) -> Option<(CGSConnectionID, u32)> { |
| 712 | | - unsafe { |
| 713 | | - let mut bounds = CGRect::default(); |
| 714 | | - let rc = SLSGetWindowBounds(cid, target_wid, &mut bounds); |
| 715 | | - if rc != kCGErrorSuccess { |
| 716 | | - debug!("[create_overlay] SLSGetWindowBounds failed for wid={target_wid} rc={rc}"); |
| 717 | | - return None; |
| 718 | | - } |
| 719 | | - if bounds.size.width < 10.0 || bounds.size.height < 10.0 { |
| 720 | | - debug!("[create_overlay] wid={target_wid} too small: {}x{}", bounds.size.width, bounds.size.height); |
| 721 | | - return None; |
| 722 | | - } |
| 723 | | - |
| 724 | | - let bw = border_width; |
| 725 | | - let ow = bounds.size.width + 2.0 * bw; |
| 726 | | - let oh = bounds.size.height + 2.0 * bw; |
| 727 | | - let ox = bounds.origin.x - bw; |
| 728 | | - let oy = bounds.origin.y - bw; |
| 729 | | - |
| 730 | | - let frame = CGRect::new(0.0, 0.0, ow, oh); |
| 731 | | - let mut region: CFTypeRef = ptr::null(); |
| 732 | | - CGSNewRegionWithRect(&frame, &mut region); |
| 733 | | - if region.is_null() { |
| 734 | | - debug!("[create_overlay] CGSNewRegionWithRect failed for wid={target_wid}"); |
| 735 | | - return None; |
| 736 | | - } |
| 737 | | - |
| 738 | | - let mut wid: u32 = 0; |
| 739 | | - SLSNewWindow(cid, 2, ox as f32, oy as f32, region, &mut wid); |
| 740 | | - CFRelease(region); |
| 741 | | - if wid == 0 { |
| 742 | | - debug!("[create_overlay] SLSNewWindow returned 0 for target={target_wid} cid={cid}"); |
| 743 | | - return None; |
| 744 | | - } |
| 745 | | - |
| 746 | | - debug!("[create_overlay] created overlay wid={wid} for target={target_wid} color=({:.2},{:.2},{:.2},{:.2})", |
| 747 | | - color.0, color.1, color.2, color.3); |
| 748 | | - |
| 749 | | - SLSSetWindowResolution(cid, wid, 2.0); |
| 750 | | - SLSSetWindowOpacity(cid, wid, false); |
| 751 | | - SLSSetWindowLevel(cid, wid, 25); |
| 752 | | - SLSOrderWindow(cid, wid, 1, 0); |
| 753 | | - |
| 754 | | - // Draw border (point coordinates) |
| 755 | | - let ctx = SLWindowContextCreate(cid, wid, ptr::null()); |
| 756 | | - if ctx.is_null() { |
| 757 | | - debug!("[create_overlay] SLWindowContextCreate returned null for overlay wid={wid}"); |
| 758 | | - SLSReleaseWindow(cid, wid); |
| 759 | | - return None; |
| 760 | | - } |
| 761 | | - |
| 762 | | - draw_border(ctx, ow, oh, bw, radius, color); |
| 763 | | - SLSFlushWindowContentRegion(cid, wid, ptr::null()); |
| 764 | | - CGContextRelease(ctx); |
| 765 | | - |
| 766 | | - Some((cid, wid)) |
| 767 | | - } |
| 768 | | -} |
| 769 | | - |
| 770 | 1282 | fn list_windows() { |
| 771 | 1283 | let cid = unsafe { SLSMainConnectionID() }; |
| 772 | 1284 | unsafe { |
| 773 | 1285 | let list = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID); |
| 774 | | - if list.is_null() { return; } |
| 1286 | + if list.is_null() { |
| 1287 | + return; |
| 1288 | + } |
| 775 | 1289 | let count = CFArrayGetCount(list); |
| 776 | | - let wid_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowNumber\0".as_ptr(), kCFStringEncodingUTF8); |
| 777 | | - let layer_key = CFStringCreateWithCString(ptr::null(), b"kCGWindowLayer\0".as_ptr(), kCFStringEncodingUTF8); |
| 1290 | + let wid_key = cf_string_from_static(c"kCGWindowNumber"); |
| 1291 | + let layer_key = cf_string_from_static(c"kCGWindowLayer"); |
| 778 | 1292 | |
| 779 | | - eprintln!("{:>6} {:>8} {:>8} {:>6} {:>6}", "wid", "x", "y", "w", "h"); |
| 1293 | + eprintln!( |
| 1294 | + "{:>6} {:>8} {:>8} {:>6} {:>6}", |
| 1295 | + "wid", "x", "y", "w", "h" |
| 1296 | + ); |
| 780 | 1297 | for i in 0..count { |
| 781 | 1298 | let dict = CFArrayGetValueAtIndex(list, i); |
| 782 | | - if dict.is_null() { continue; } |
| 1299 | + if dict.is_null() { |
| 1300 | + continue; |
| 1301 | + } |
| 783 | 1302 | |
| 784 | 1303 | let mut v: CFTypeRef = ptr::null(); |
| 785 | 1304 | let mut wid: u32 = 0; |
@@ -790,12 +1309,16 @@ fn list_windows() { |
| 790 | 1309 | if CFDictionaryGetValueIfPresent(dict, layer_key as CFTypeRef, &mut v) { |
| 791 | 1310 | CFNumberGetValue(v, kCFNumberSInt32Type, &mut layer as *mut _ as *mut _); |
| 792 | 1311 | } |
| 793 | | - if layer != 0 || wid == 0 { continue; } |
| 1312 | + if layer != 0 || wid == 0 { |
| 1313 | + continue; |
| 1314 | + } |
| 794 | 1315 | |
| 795 | 1316 | let mut bounds = CGRect::default(); |
| 796 | 1317 | SLSGetWindowBounds(cid, wid, &mut bounds); |
| 797 | | - eprintln!("{wid:>6} {:>8.0} {:>8.0} {:>6.0} {:>6.0}", |
| 798 | | - bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height); |
| 1318 | + eprintln!( |
| 1319 | + "{wid:>6} {:>8.0} {:>8.0} {:>6.0} {:>6.0}", |
| 1320 | + bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height |
| 1321 | + ); |
| 799 | 1322 | } |
| 800 | 1323 | CFRelease(wid_key as CFTypeRef); |
| 801 | 1324 | CFRelease(layer_key as CFTypeRef); |
@@ -803,3 +1326,67 @@ fn list_windows() { |
| 803 | 1326 | } |
| 804 | 1327 | } |
| 805 | 1328 | |
| 1329 | +#[cfg(test)] |
| 1330 | +mod tests { |
| 1331 | + use super::{ |
| 1332 | + CGRect, SurfacePreference, WindowMetadata, intersection_area, is_same_window_surface, |
| 1333 | + is_suitable_window_metadata, is_trackable_window, surface_preference, |
| 1334 | + }; |
| 1335 | + |
| 1336 | + #[test] |
| 1337 | + fn same_surface_detects_contained_strip() { |
| 1338 | + let outer = CGRect::new(100.0, 100.0, 1200.0, 900.0); |
| 1339 | + let strip = CGRect::new(114.0, 105.0, 1160.0, 140.0); |
| 1340 | + assert!(is_same_window_surface(outer, strip)); |
| 1341 | + } |
| 1342 | + |
| 1343 | + #[test] |
| 1344 | + fn different_windows_are_not_treated_as_one_surface() { |
| 1345 | + let a = CGRect::new(100.0, 100.0, 1200.0, 900.0); |
| 1346 | + let b = CGRect::new(300.0, 300.0, 1160.0, 140.0); |
| 1347 | + assert!(!is_same_window_surface(a, b)); |
| 1348 | + } |
| 1349 | + |
| 1350 | + #[test] |
| 1351 | + fn intersection_area_is_zero_without_overlap() { |
| 1352 | + let a = CGRect::new(100.0, 100.0, 200.0, 200.0); |
| 1353 | + let b = CGRect::new(400.0, 400.0, 200.0, 200.0); |
| 1354 | + assert_eq!(intersection_area(a, b), 0.0); |
| 1355 | + } |
| 1356 | + |
| 1357 | + #[test] |
| 1358 | + fn same_surface_prefers_larger_bounds() { |
| 1359 | + let strip = CGRect::new(114.0, 105.0, 1160.0, 140.0); |
| 1360 | + let outer = CGRect::new(100.0, 100.0, 1200.0, 900.0); |
| 1361 | + assert_eq!( |
| 1362 | + surface_preference(strip, outer), |
| 1363 | + Some(SurfacePreference::ReplaceExisting) |
| 1364 | + ); |
| 1365 | + } |
| 1366 | + |
| 1367 | + #[test] |
| 1368 | + fn small_windows_remain_trackable() { |
| 1369 | + let small = CGRect::new(100.0, 100.0, 12.0, 18.0); |
| 1370 | + assert!(is_trackable_window(small, 4.0)); |
| 1371 | + } |
| 1372 | + |
| 1373 | + #[test] |
| 1374 | + fn suitable_window_metadata_matches_document_windows() { |
| 1375 | + let metadata = WindowMetadata { |
| 1376 | + parent_wid: 0, |
| 1377 | + tags: super::WINDOW_TAG_DOCUMENT, |
| 1378 | + attributes: super::WINDOW_ATTRIBUTE_REAL, |
| 1379 | + }; |
| 1380 | + assert!(is_suitable_window_metadata(metadata)); |
| 1381 | + } |
| 1382 | + |
| 1383 | + #[test] |
| 1384 | + fn attached_windows_are_not_suitable_targets() { |
| 1385 | + let metadata = WindowMetadata { |
| 1386 | + parent_wid: 7, |
| 1387 | + tags: super::WINDOW_TAG_DOCUMENT | super::WINDOW_TAG_ATTACHED, |
| 1388 | + attributes: super::WINDOW_ATTRIBUTE_REAL, |
| 1389 | + }; |
| 1390 | + assert!(!is_suitable_window_metadata(metadata)); |
| 1391 | + } |
| 1392 | +} |