-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_watch.py
More file actions
95 lines (75 loc) · 2.52 KB
/
agent_watch.py
File metadata and controls
95 lines (75 loc) · 2.52 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
import threading
import time
import win32con
import win32gui
import win32ts
from app.agent_once import run_agent_once
TRIGGER_COOLDOWN_SECONDS = 8.0
class AgentWatch:
def __init__(self):
self._last_trigger_time = 0.0
self._class_name = "DisplayMapperWakeWatcher"
self._hwnd = None
def _can_trigger(self):
now = time.time()
if now - self._last_trigger_time < TRIGGER_COOLDOWN_SECONDS:
return False
self._last_trigger_time = now
return True
def _start_retry_worker(self):
if not self._can_trigger():
return
threading.Thread(target=run_agent_once, daemon=True).start()
def _wnd_proc(self, hwnd, msg, wparam, lparam):
if msg == win32con.WM_POWERBROADCAST:
if wparam in (
getattr(win32con, "PBT_APMRESUMEAUTOMATIC", -1),
getattr(win32con, "PBT_APMRESUMESUSPEND", -1),
):
self._start_retry_worker()
return 1
if msg == getattr(win32con, "WM_WTSSESSION_CHANGE", 0x02B1):
if wparam == getattr(win32ts, "WTS_SESSION_UNLOCK", -1):
self._start_retry_worker()
return 0
if msg == win32con.WM_CLOSE:
win32gui.DestroyWindow(hwnd)
return 0
if msg == win32con.WM_DESTROY:
try:
win32ts.WTSUnRegisterSessionNotification(hwnd)
except Exception:
pass
win32gui.PostQuitMessage(0)
return 0
return win32gui.DefWindowProc(hwnd, msg, wparam, lparam)
def start(self):
wc = win32gui.WNDCLASS()
wc.lpfnWndProc = self._wnd_proc
wc.lpszClassName = self._class_name
wc.hInstance = win32gui.GetModuleHandle(None)
try:
class_atom = win32gui.RegisterClass(wc)
except win32gui.error:
class_atom = self._class_name
self._hwnd = win32gui.CreateWindow(
class_atom,
self._class_name,
0,
0,
0,
0,
0,
0,
0,
wc.hInstance,
None,
)
win32ts.WTSRegisterSessionNotification(
self._hwnd,
win32ts.NOTIFY_FOR_THIS_SESSION,
)
threading.Thread(target=run_agent_once, daemon=True).start()
win32gui.PumpMessages()
def run_agent_watch():
AgentWatch().start()