-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacOS_overlay.py
More file actions
299 lines (269 loc) · 9.08 KB
/
Copy pathmacOS_overlay.py
File metadata and controls
299 lines (269 loc) · 9.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import os
import objc
from Quartz import (
CGEventGetFlags,
CGEventGetIntegerValueField,
CGEventMaskBit,
CGEventTapCreate,
CGEventTapEnable,
kCGEventFlagMaskCommand,
kCGEventFlagMaskControl,
kCGEventFlagMaskAlternate,
kCGEventKeyDown,
kCGHeadInsertEventTap,
kCGKeyboardEventKeycode,
kCGSessionEventTap,
kCGEventTapOptionDefault,
CGWindowListCopyWindowInfo,
kCGWindowListOptionOnScreenOnly,
kCGWindowListExcludeDesktopElements,
kCGNullWindowID,
CGPoint,
CGSize,
)
from ApplicationServices import (
AXIsProcessTrusted,
AXUIElementCreateApplication,
AXUIElementCopyAttributeValue,
AXValueGetType,
AXValueGetValue,
kAXFocusedWindowAttribute,
kAXPositionAttribute,
kAXSizeAttribute,
kAXValueCGPointType,
kAXValueCGSizeType,
)
from AppKit import (
NSWorkspace,
NSApplication,
NSApplicationActivationPolicyAccessory,
NSApp,
NSWindow,
NSWindowStyleMaskBorderless,
NSBackingStoreBuffered,
NSStatusWindowLevel,
NSWindowCollectionBehaviorCanJoinAllSpaces,
NSWindowCollectionBehaviorFullScreenAuxiliary,
NSColor,
NSScreen,
NSTimer,
NSObject,
NSView,
)
from CoreFoundation import (
CFMachPortCreateRunLoopSource,
CFRunLoopAddSource,
CFRunLoopGetCurrent,
CFRunLoopRun,
kCFRunLoopCommonModes,
)
KEY_UP = 126
KEY_DOWN = 125
ALPHA_STEP = 15
ALPHA_MIN = 0
ALPHA_MAX = 255
REFRESH_INTERVAL = 1.0 / 120.0
CORNER_RADIUS = 12.0
SHADOW_PADDING = 36.0
SHADOW_PADDING_TOP = 18.0
SHADOW_PADDING_BOTTOM = 52.0
DEBUG = os.getenv("OPACITY_DEBUG", "0") == "1"
class OpacityController:
def __init__(self):
self.alpha_by_pid = {}
self.overlay_window = None
self.overlay_view = None
def adjust_frontmost(self, delta):
pid = self._frontmost_pid()
if pid is None:
if DEBUG:
print("[debug] No frontmost PID")
return
frame = self._frontmost_window_frame(pid)
if not frame:
if DEBUG:
print(f"[debug] No frontmost window frame for pid={pid}")
return
current = self.alpha_by_pid.get(pid, ALPHA_MIN)
new_alpha = max(ALPHA_MIN, min(ALPHA_MAX, current + delta))
self.alpha_by_pid[pid] = new_alpha
self.refresh_overlay()
if DEBUG:
x, y, w, h = frame
print(
f"[debug] Overlay frame=({x:.1f},{y:.1f},{w:.1f},{h:.1f}) alpha={new_alpha}"
)
def refresh_overlay(self):
pid = self._frontmost_pid()
if pid is None:
self._hide_overlay()
return
alpha = self.alpha_by_pid.get(pid, ALPHA_MIN)
if alpha <= 0:
self._hide_overlay()
return
frame = self._frontmost_window_frame(pid)
if not frame:
self._hide_overlay()
return
expanded = self._expand_frame(
frame,
SHADOW_PADDING,
SHADOW_PADDING_TOP,
SHADOW_PADDING_BOTTOM,
)
self._ensure_overlay(expanded, alpha)
def _ensure_overlay(self, frame, alpha_255):
x, y, w, h = frame
if not self.overlay_window:
rect = ((x, y), (w, h))
window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
rect,
NSWindowStyleMaskBorderless,
NSBackingStoreBuffered,
False,
)
window.setOpaque_(False)
window.setHasShadow_(False)
window.setIgnoresMouseEvents_(True)
window.setLevel_(NSStatusWindowLevel)
window.setBackgroundColor_(NSColor.clearColor())
behavior = (
NSWindowCollectionBehaviorCanJoinAllSpaces
| NSWindowCollectionBehaviorFullScreenAuxiliary
)
window.setCollectionBehavior_(behavior)
view = NSView.alloc().initWithFrame_(rect)
view.setWantsLayer_(True)
view.layer().setCornerRadius_(CORNER_RADIUS)
view.layer().setMasksToBounds_(True)
window.setContentView_(view)
self.overlay_window = window
self.overlay_view = view
self.overlay_window.setFrame_display_(((x, y), (w, h)), True)
alpha_float = float(alpha_255) / 255.0
color = NSColor.whiteColor().colorWithAlphaComponent_(alpha_float)
if self.overlay_view:
self.overlay_view.layer().setBackgroundColor_(color.CGColor())
self.overlay_window.orderFrontRegardless()
def _hide_overlay(self):
if self.overlay_window:
self.overlay_window.orderOut_(None)
def _expand_frame(self, frame, padding, padding_top, padding_bottom):
x, y, w, h = frame
return (
x - padding,
y - padding_bottom,
w + padding * 2,
h + padding_top + padding_bottom,
)
def _frontmost_pid(self):
app = NSWorkspace.sharedWorkspace().frontmostApplication()
if not app:
return None
return app.processIdentifier()
def _frontmost_window_frame(self, pid):
app_elem = AXUIElementCreateApplication(pid)
if not app_elem:
return None
window_ref, err = AXUIElementCopyAttributeValue(app_elem, kAXFocusedWindowAttribute, None)
if err != 0 or not window_ref:
return self._fallback_window_frame(pid)
pos_ref, pos_err = AXUIElementCopyAttributeValue(window_ref, kAXPositionAttribute, None)
size_ref, size_err = AXUIElementCopyAttributeValue(window_ref, kAXSizeAttribute, None)
if pos_err != 0 or size_err != 0:
return self._fallback_window_frame(pid)
if AXValueGetType(pos_ref) != kAXValueCGPointType:
return self._fallback_window_frame(pid)
if AXValueGetType(size_ref) != kAXValueCGSizeType:
return self._fallback_window_frame(pid)
pos = CGPoint()
size = CGSize()
AXValueGetValue(pos_ref, kAXValueCGPointType, pos)
AXValueGetValue(size_ref, kAXValueCGSizeType, size)
return (pos.x, pos.y, size.width, size.height)
def _fallback_window_frame(self, pid):
options = kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements
window_list = CGWindowListCopyWindowInfo(options, kCGNullWindowID)
for info in window_list:
if info.get("kCGWindowOwnerPID") != pid:
continue
if info.get("kCGWindowLayer") != 0:
continue
bounds = info.get("kCGWindowBounds")
if not bounds:
continue
x = bounds.get("X", 0.0)
y = bounds.get("Y", 0.0)
w = bounds.get("Width", 0.0)
h = bounds.get("Height", 0.0)
screen = NSScreen.mainScreen()
if screen:
screen_height = screen.frame().size.height
y = screen_height - y - h
return (x, y, w, h)
return None
class _OverlayRefresher(NSObject):
def initWithController_(self, controller):
self = objc.super(_OverlayRefresher, self).init()
if self is None:
return None
self.controller = controller
return self
def tick_(self, _timer):
self.controller.refresh_overlay()
_controller = None
def _event_callback(proxy, event_type, event, refcon):
if event_type != kCGEventKeyDown:
return event
flags = CGEventGetFlags(event)
if not (
flags & kCGEventFlagMaskCommand
and flags & kCGEventFlagMaskControl
and flags & kCGEventFlagMaskAlternate
):
return event
if DEBUG:
print("[debug] Hotkey matched")
keycode = CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode)
if keycode == KEY_UP:
_controller.adjust_frontmost(ALPHA_STEP)
elif keycode == KEY_DOWN:
_controller.adjust_frontmost(-ALPHA_STEP)
return event
def _create_event_tap():
mask = CGEventMaskBit(kCGEventKeyDown)
tap = CGEventTapCreate(
kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
mask,
_event_callback,
None,
)
if not tap:
raise RuntimeError("Failed to create event tap (check Accessibility permissions)")
if DEBUG:
print("[debug] Event tap created")
source = CFMachPortCreateRunLoopSource(None, tap, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes)
CGEventTapEnable(tap, True)
def main():
global _controller
if not AXIsProcessTrusted():
raise RuntimeError("Accessibility permission is required to read window info")
NSApplication.sharedApplication()
NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)
_controller = OpacityController()
refresher = _OverlayRefresher.alloc().initWithController_(_controller)
NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
REFRESH_INTERVAL,
refresher,
"tick:",
None,
True,
)
_create_event_tap()
CFRunLoopRun()
if __name__ == "__main__":
main()