-
Notifications
You must be signed in to change notification settings - Fork 0
/
active_window_checker.py
284 lines (228 loc) · 7.6 KB
/
active_window_checker.py
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
"""Log window focus and appearance.
Written to try to debug some window popping up and stealing focus from my
Spelunky game for a split second.
Developed with 32-bit python on Windows 7. Might work in other environments,
but some of these APIs might not exist before Vista.
Much credit to Eric Blade for this:
https://mail.python.org/pipermail/python-win32/2009-July/009381.html
and David Heffernan:
http://stackoverflow.com/a/15898768/9585
"""
import ctypes
import ctypes.wintypes
import sys
from asyncio import to_thread
from dataclasses import dataclass
from enum import Enum, auto
from functools import cached_property
import inject
import win32con
import win32gui
import win32process
from app_close import AppCloseManager
from color_filter import ColorFilter
from commented_config import CommentsHolder
from inversion_rules import InversionRulesController
from utils import show_exceptions
user32 = ctypes.windll.user32
ole32 = ctypes.windll.ole32
kernel32 = ctypes.windll.kernel32
WinEventProcType = ctypes.WINFUNCTYPE(
None,
ctypes.wintypes.HANDLE,
ctypes.wintypes.DWORD,
ctypes.wintypes.HWND,
ctypes.wintypes.LONG,
ctypes.wintypes.LONG,
ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD
)
# The types of events we want to listen for, and the names we'll use for
# them in the log output. Pick from
# http://msdn.microsoft.com/en-us/library/windows/desktop/dd318066(v=vs.85).aspx
eventTypes = {
win32con.EVENT_SYSTEM_FOREGROUND: "Foreground",
win32con.EVENT_OBJECT_FOCUS: "Focus",
#win32con.EVENT_OBJECT_SHOW: "Show",
win32con.EVENT_SYSTEM_DIALOGSTART: "Dialog",
win32con.EVENT_SYSTEM_CAPTURESTART: "Capture",
win32con.EVENT_SYSTEM_MINIMIZEEND: "UnMinimize"
}
# limited information would be sufficient, but our platform doesn't have it.
processFlag = getattr(win32con, 'PROCESS_QUERY_LIMITED_INFORMATION',
win32con.PROCESS_QUERY_INFORMATION)
threadFlag = getattr(win32con, 'THREAD_QUERY_LIMITED_INFORMATION',
win32con.THREAD_QUERY_INFORMATION)
@dataclass
class WindowInfo:
hwnd: int
title: str = ""
path: str = ""
pid: int = None
root_title: str = ""
@property
def name(self) -> str:
return self.path.split('\\')[-1]
@cached_property
def titles(self):
return {*filter(
None, titles(parents(self.hwnd))
), self.root_title}
def getProcessFilename(processID):
hProcess = kernel32.OpenProcess(processFlag, 0, processID)
if not hProcess:
raise ProcessLookupError(f"OpenProcess({processID}) failed: {ctypes.WinError()}")
try:
filenameBufferSize = ctypes.wintypes.DWORD(4096)
filename = ctypes.create_unicode_buffer(filenameBufferSize.value)
kernel32.QueryFullProcessImageNameW(hProcess, 0, ctypes.byref(filename),
ctypes.byref(filenameBufferSize))
return filename.value
finally:
kernel32.CloseHandle(hProcess)
def get_window_info(hwnd) -> WindowInfo:
try:
winfo = WindowInfo(
hwnd,
win32gui.GetWindowText(hwnd),
pid=win32process.GetWindowThreadProcessId(hwnd)[1]
)
if winfo.pid:
winfo.path = getProcessFilename(winfo.pid)
except ProcessLookupError:
return None
root_hwnd = get_root(hwnd)
if root_hwnd != 0:
winfo.root_title = win32gui.GetWindowText(root_hwnd)
if not winfo.title:
winfo.title = winfo.root_title
return winfo
def is_root(hwnd: int, candidate_hwnd: int):
return (candidate_hwnd != 0
and (hwnd == candidate_hwnd
or win32gui.IsChild(candidate_hwnd, hwnd)))
def get_root(hwnd: int):
active = (win32gui.GetForegroundWindow() or
win32gui.GetFocus())
if is_root(hwnd, active):
return active
try:
owner = win32gui.GetWindow(hwnd, win32con.GW_OWNER)
if is_root(hwnd, owner):
return owner
except win32gui.error:
pass
start = hwnd
last_hwnd = 0
for last_hwnd in parents(hwnd):
pass
return last_hwnd if start != last_hwnd else 0
def setHook(WinEventProc, eventType):
return user32.SetWinEventHook(
eventType,
eventType,
0,
WinEventProc,
0,
0,
win32con.WINEVENT_OUTOFCONTEXT
)
def parents(hwnd):
if not hwnd:
return
try:
while True:
hwnd = win32gui.GetParent(hwnd)
if not hwnd:
break
yield hwnd
except win32gui.error:
pass
def titles(iterable):
for hwnd in iterable:
yield win32gui.GetWindowText(hwnd)
@show_exceptions()
@inject.autoparams()
def listen_switch_events(callback, close_manager: AppCloseManager):
ole32.CoInitialize(0)
try:
WinEventProc = WinEventProcType(callback)
user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
hookIDs = [setHook(WinEventProc, et) for et in eventTypes.keys()]
if not any(hookIDs):
print('SetWinEventHook failed')
sys.exit(1)
close_manager.append_blocked_thread()
win32gui.PumpMessages()
for hookID in hookIDs:
try:
user32.UnhookWinEvent(hookID)
except:
pass
finally:
ole32.CoUninitialize()
class AppMode(Enum):
DISABLE = auto()
RULES = auto()
@dataclass
class WinTrackerSettings:
"""
Specifies interaction with windows events
"""
_comments_ = CommentsHolder()
show_events: bool = False
_comments_.add("""
[{default!r}] Display all window switch events
""", locals())
mode: AppMode = AppMode.RULES
_comments_.add(f"""
[{{default.name}}] How to process events: {' | '.join(e.name for e in AppMode)}
\t{AppMode.DISABLE.name} - Ignore all events
\t{AppMode.RULES.name} - Use rules to determine what to do
""", locals())
class FilterStateController:
config = inject.attr(WinTrackerSettings)
rules = inject.attr(InversionRulesController)
color_filter = inject.attr(ColorFilter)
def __init__(self):
from collections import deque
self.last_active_windows = deque(maxlen=10)
self.last_active_window = None
def setup(self):
self.rules.on_rules_changed = self.update_filter_state
self.color_filter.setup()
async def run(self):
await to_thread(
listen_switch_events,
self.on_active_window_switched
)
def on_active_window_switched(self,
hWinEventHook,
event,
hwnd,
idObject,
idChild,
dwEventThread,
dwmsEventTime):
if idObject != 0:
return
result = get_window_info(hwnd)
if not result:
return
winfo = self.last_active_window = result
self.last_active_windows.append(winfo)
if self.config.show_events:
print(winfo.path,
eventTypes.get(event, hex(event)),
hwnd)
self.update_filter_state()
def update_filter_state(self, winfo: WindowInfo = None):
if winfo is None:
winfo = self.last_active_window
mode = self.config.mode
if mode == AppMode.RULES:
color_filter = self.rules.get_filter(winfo)
if color_filter is not None:
self.color_filter.set_filter(
*color_filter
)