main.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // 输出「系统设置」主窗口的屏幕几何,供 CUA 权限浮窗吸附定位。
  2. //
  3. // 为什么需要这个独立二进制:吸附只需要一个数据 —— 系统设置窗口的 bounds。取它的正确 API 是
  4. // CGWindowListCopyWindowInfo,而它**不需要任何 TCC 权限**(只有取窗口*图像*才需要 Screen
  5. // Recording)。这一点是整个方案成立的前提:授权引导运行时恰恰还没有辅助功能/录屏权限。
  6. // Electron 侧没有这个 API 的绑定,其余途径都不通 —— osascript + System Events 需要辅助功能
  7. // 权限(死结),desktopCapturer 只给窗口名不给 bounds,koffi 这类 FFI 自身是 native addon
  8. // 需要 electron-rebuild。所以用一个不到 100KB、无 bundle 的命令行程序。
  9. //
  10. // 常驻设计:每 interval 输出一行 JSON。父进程只 spawn 一次并读 stdout —— 每帧起一个进程的
  11. // 开销(~10ms × 每秒 7 次)完全不可接受。
  12. //
  13. // 用法:zcode-window-bounds [intervalMs] 默认 150ms
  14. import CoreGraphics
  15. import Foundation
  16. let intervalMs = UInt32(CommandLine.arguments.dropFirst().first.flatMap { UInt32($0) } ?? 150)
  17. // 系统设置在不同 macOS 版本/语言下的进程名不同;13+ 是 "System Settings",更早是
  18. // "System Preferences",中文系统则是本地化名称。
  19. let settingsOwners = ["System Settings", "System Preferences", "系统设置", "系統設定"]
  20. // 行缓冲:父进程逐行读取,默认的全缓冲会让数据卡在 stdio 缓冲区里直到写满 4KB。
  21. setvbuf(stdout, nil, _IOLBF, 0)
  22. while true {
  23. var windows: [[String: Any]] = []
  24. if let list = CGWindowListCopyWindowInfo(
  25. [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID
  26. ) as? [[String: Any]] {
  27. for window in list {
  28. guard let owner = window[kCGWindowOwnerName as String] as? String,
  29. settingsOwners.contains(where: { owner.contains($0) }),
  30. let boundsDict = window[kCGWindowBounds as String] as? [String: Any],
  31. let rect = CGRect(dictionaryRepresentation: boundsDict as CFDictionary)
  32. else { continue }
  33. windows.append([
  34. "x": rect.origin.x,
  35. "y": rect.origin.y,
  36. "w": rect.size.width,
  37. "h": rect.size.height,
  38. // 消费方只认 layer 0(普通窗口)。设置页还会带出 layer > 0 的辅助层
  39. // (工具提示、弹出选择器),吸附到它们会把面板扔到屏幕角落。
  40. "layer": window[kCGWindowLayer as String] as? Int ?? -1,
  41. ])
  42. }
  43. }
  44. // 即使没有匹配窗口也输出空数组:父进程据此知道「设置页已关闭」而不是「探测挂了」。
  45. if let data = try? JSONSerialization.data(withJSONObject: windows),
  46. let line = String(data: data, encoding: .utf8)
  47. {
  48. print(line)
  49. }
  50. usleep(intervalMs * 1000)
  51. }