Files
javis_bot/scripts/m0/m0lib/winvdd.py
javis-bot e0b172e796 feat(m0): check a virtual monitor for the bot browser window
The user wants the bot window on no real screen at all. Add a vdisplay
stage that drives the Parsec Virtual Display Adapter already on the PC
(no install, the display dies with the script), moves the clock window
onto it as a normal and as a tool window, and asks about real monitors,
Alt+Tab, Discord's Screens tab and whether the cursor can wander there.

Record the M0 defaults the user confirmed in docs/v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:29:58 +09:00

270 lines
12 KiB
Python

"""Parsec Virtual Display Adapter control and display enumeration over ctypes. Windows only at run time.
The driver interface follows nomi-san/parsec-vdd (core/parsec-vdd.h): open the
device interface, then DeviceIoControl with a 32-byte input buffer and a DWORD
output. An added display stays only while UPDATE is sent at least every 100 ms,
so a display dies with the process that keeps it (no display is left behind
if the kit crashes).
The structures are defined at import time so their sizes can be checked on any
OS; the DLLs are loaded only when a function is called.
"""
from __future__ import annotations
import ctypes
import threading
import time
from ctypes import wintypes
GUID_VDD_ADAPTER = (0x00B41627, 0x04C4, 0x429E, (0xA2, 0x6E, 0x02, 0x65, 0xCF, 0x50, 0xC8, 0xFA))
IOCTL_ADD, IOCTL_REMOVE, IOCTL_UPDATE, IOCTL_VERSION = 0x0022E004, 0x0022A008, 0x0022A00C, 0x0022E010
DIGCF_PRESENT, DIGCF_DEVICEINTERFACE = 0x2, 0x10
DISPLAY_DEVICE_ATTACHED_TO_DESKTOP, DISPLAY_DEVICE_PRIMARY_DEVICE = 0x1, 0x4
ENUM_CURRENT_SETTINGS = -1
DM_POSITION = 0x20
CDS_UPDATEREGISTRY, CDS_NORESET = 0x1, 0x10000000
# UTF-16 code units, so the layout is the Windows one on every OS (c_wchar is 4 bytes on Linux).
# DWORD/LONG are fixed 32-bit for the same reason (wintypes.DWORD is 8 bytes on 64-bit Linux).
WCHAR, WORD, DWORD, LONG = ctypes.c_uint16, ctypes.c_uint16, ctypes.c_uint32, ctypes.c_int32
def wstr(units) -> str:
raw = bytes(memoryview(units).cast("B"))
return raw.decode("utf-16-le", errors="replace").split("\x00", 1)[0]
class GUID(ctypes.Structure):
_fields_ = [("Data1", DWORD), ("Data2", WORD), ("Data3", WORD),
("Data4", ctypes.c_ubyte * 8)]
class SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
_fields_ = [("cbSize", DWORD), ("InterfaceClassGuid", GUID), ("Flags", DWORD),
("Reserved", ctypes.c_size_t)]
class OVERLAPPED(ctypes.Structure):
_fields_ = [("Internal", ctypes.c_size_t), ("InternalHigh", ctypes.c_size_t), ("Offset", DWORD),
("OffsetHigh", DWORD), ("hEvent", ctypes.c_void_p)]
class DISPLAY_DEVICEW(ctypes.Structure):
_fields_ = [("cb", DWORD), ("DeviceName", WCHAR * 32), ("DeviceString", WCHAR * 128),
("StateFlags", DWORD), ("DeviceID", WCHAR * 128), ("DeviceKey", WCHAR * 128)]
class POINTL(ctypes.Structure):
_fields_ = [("x", LONG), ("y", LONG)]
class DEVMODEW(ctypes.Structure):
"""The display variant of DEVMODEW (220 bytes)."""
_fields_ = [("dmDeviceName", WCHAR * 32), ("dmSpecVersion", WORD),
("dmDriverVersion", WORD), ("dmSize", WORD), ("dmDriverExtra", WORD),
("dmFields", DWORD), ("dmPosition", POINTL), ("dmDisplayOrientation", DWORD),
("dmDisplayFixedOutput", DWORD), ("dmColor", ctypes.c_short), ("dmDuplex", ctypes.c_short),
("dmYResolution", ctypes.c_short), ("dmTTOption", ctypes.c_short), ("dmCollate", ctypes.c_short),
("dmFormName", WCHAR * 32), ("dmLogPixels", WORD), ("dmBitsPerPel", DWORD),
("dmPelsWidth", DWORD), ("dmPelsHeight", DWORD), ("dmDisplayFlags", DWORD),
("dmDisplayFrequency", DWORD), ("dmICMMethod", DWORD),
("dmICMIntent", DWORD), ("dmMediaType", DWORD), ("dmDitherType", DWORD),
("dmReserved1", DWORD), ("dmReserved2", DWORD),
("dmPanningWidth", DWORD), ("dmPanningHeight", DWORD)]
def _guid(parts) -> GUID:
return GUID(parts[0], parts[1], parts[2], (ctypes.c_ubyte * 8)(*parts[3]))
def _dlls():
setupapi = ctypes.WinDLL("setupapi", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
user32 = ctypes.WinDLL("user32", use_last_error=True)
vp, H, D, B = ctypes.c_void_p, wintypes.HANDLE, wintypes.DWORD, wintypes.BOOL
for fn, args, res in (
(setupapi.SetupDiGetClassDevsW, [ctypes.POINTER(GUID), wintypes.LPCWSTR, wintypes.HWND, D], vp),
(setupapi.SetupDiEnumDeviceInterfaces, [vp, vp, ctypes.POINTER(GUID), D,
ctypes.POINTER(SP_DEVICE_INTERFACE_DATA)], B),
(setupapi.SetupDiGetDeviceInterfaceDetailW, [vp, ctypes.POINTER(SP_DEVICE_INTERFACE_DATA), vp, D,
ctypes.POINTER(D), vp], B),
(setupapi.SetupDiDestroyDeviceInfoList, [vp], B),
(kernel32.CreateFileW, [wintypes.LPCWSTR, D, D, vp, D, D, H], H),
(kernel32.CreateEventW, [vp, B, B, wintypes.LPCWSTR], H),
(kernel32.DeviceIoControl, [H, D, vp, D, vp, D, ctypes.POINTER(D), ctypes.POINTER(OVERLAPPED)], B),
(kernel32.GetOverlappedResultEx, [H, ctypes.POINTER(OVERLAPPED), ctypes.POINTER(D), D, B], B),
(kernel32.CancelIoEx, [H, ctypes.POINTER(OVERLAPPED)], B),
(kernel32.GetOverlappedResult, [H, ctypes.POINTER(OVERLAPPED), ctypes.POINTER(D), B], B),
(kernel32.CloseHandle, [H], B),
(user32.EnumDisplayDevicesW, [wintypes.LPCWSTR, D, ctypes.POINTER(DISPLAY_DEVICEW), D], B),
(user32.EnumDisplaySettingsW, [wintypes.LPCWSTR, D, ctypes.POINTER(DEVMODEW)], B),
(user32.ChangeDisplaySettingsExW, [wintypes.LPCWSTR, ctypes.POINTER(DEVMODEW), wintypes.HWND, D, vp],
ctypes.c_long),
):
fn.argtypes, fn.restype = args, res
return setupapi, kernel32, user32
INVALID = ctypes.c_void_p(-1).value
class Vdd:
"""One open handle to the driver, with the keep-alive thread."""
def __init__(self):
self.setupapi, self.kernel32, self.user32 = _dlls()
self.handle = self._open()
self.lock = threading.Lock()
self._stop = threading.Event()
self._pinger: threading.Thread | None = None
self.added: list[int] = []
def _open(self):
guid = _guid(GUID_VDD_ADAPTER)
info = self.setupapi.SetupDiGetClassDevsW(ctypes.byref(guid), None, None,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)
if not info or info == INVALID:
raise OSError(ctypes.get_last_error(), "Parsec 가상 디스플레이 장치를 찾지 못했습니다")
try:
i = 0
data = SP_DEVICE_INTERFACE_DATA()
data.cbSize = ctypes.sizeof(SP_DEVICE_INTERFACE_DATA)
last_err = 0
while self.setupapi.SetupDiEnumDeviceInterfaces(info, None, ctypes.byref(guid), i, ctypes.byref(data)):
i += 1
size = wintypes.DWORD(0)
self.setupapi.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(data), None, 0, ctypes.byref(size),
None)
buf = ctypes.create_string_buffer(max(size.value, 16))
# cbSize is the fixed part of SP_DEVICE_INTERFACE_DETAIL_DATA_W: 8 on 64-bit, 6 on 32-bit.
ctypes.cast(buf, ctypes.POINTER(wintypes.DWORD))[0] = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6
if not self.setupapi.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(data), buf, size,
ctypes.byref(size), None):
last_err = ctypes.get_last_error()
continue
path = ctypes.wstring_at(ctypes.addressof(buf) + 4)
h = self.kernel32.CreateFileW(path, 0xC0000000, 0x3, None, 3,
0x80 | 0x20000000 | 0x40000000 | 0x80000000, None)
if h and h != INVALID:
return h
last_err = ctypes.get_last_error()
raise OSError(last_err or ctypes.get_last_error(), f"장치를 열지 못했습니다 (인터페이스 {i}개)")
finally:
self.setupapi.SetupDiDestroyDeviceInfoList(info)
def ioctl(self, code: int, data: bytes = b"") -> int:
inbuf = ctypes.create_string_buffer(data[:32], 32)
out = wintypes.DWORD(0)
ov = OVERLAPPED()
ov.hEvent = self.kernel32.CreateEventW(None, True, False, None)
n = wintypes.DWORD(0)
try:
with self.lock:
self.kernel32.DeviceIoControl(self.handle, code, inbuf, 32, ctypes.byref(out), 4, None,
ctypes.byref(ov))
if not self.kernel32.GetOverlappedResultEx(self.handle, ctypes.byref(ov), ctypes.byref(n), 5000,
False):
# The request may still be pending: cancel it and wait, or the driver
# could later write into these buffers after they are freed.
self.kernel32.CancelIoEx(self.handle, ctypes.byref(ov))
self.kernel32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(n), True)
return -1
return out.value
finally:
if ov.hEvent:
self.kernel32.CloseHandle(ov.hEvent)
def version(self) -> int:
return self.ioctl(IOCTL_VERSION)
def _ping(self) -> None:
while not self._stop.wait(0.05):
self.ioctl(IOCTL_UPDATE)
def add(self) -> int:
if self._pinger is None:
self._pinger = threading.Thread(target=self._ping, daemon=True)
self._pinger.start()
idx = self.ioctl(IOCTL_ADD)
self.ioctl(IOCTL_UPDATE)
if idx >= 0:
self.added.append(idx)
return idx
def remove(self, idx: int) -> None:
# The driver reads the index as a big-endian UINT16.
self.ioctl(IOCTL_REMOVE, (idx & 0xFFFF).to_bytes(2, "big"))
self.ioctl(IOCTL_UPDATE)
if idx in self.added:
self.added.remove(idx)
def close(self) -> None:
for idx in list(self.added):
self.remove(idx)
self._stop.set()
if self._pinger:
self._pinger.join(timeout=2)
self.kernel32.CloseHandle(self.handle)
def displays() -> list[dict]:
"""Displays attached to the desktop: device name, adapter, rect in desktop pixels, primary flag."""
_, _, user32 = _dlls()
out = []
i = 0
while True:
dd = DISPLAY_DEVICEW()
dd.cb = ctypes.sizeof(DISPLAY_DEVICEW)
if not user32.EnumDisplayDevicesW(None, i, ctypes.byref(dd), 0):
break
i += 1
if not dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP:
continue
dm = DEVMODEW()
dm.dmSize = ctypes.sizeof(DEVMODEW)
name, adapter = wstr(dd.DeviceName), wstr(dd.DeviceString)
if not user32.EnumDisplaySettingsW(name, ENUM_CURRENT_SETTINGS, ctypes.byref(dm)):
continue
x, y = dm.dmPosition.x, dm.dmPosition.y
out.append({"device": name, "adapter": adapter,
"rect": [x, y, x + dm.dmPelsWidth, y + dm.dmPelsHeight], "hz": dm.dmDisplayFrequency,
"primary": bool(dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE),
"virtual": "parsec" in adapter.lower()})
return out
def wait_for_displays(pred, timeout: float = 10.0) -> list[dict]:
end = time.time() + timeout
cur = displays()
while not pred(cur) and time.time() < end:
time.sleep(0.25)
cur = displays()
return cur
def corner_position(physical: list[dict]) -> tuple[int, int]:
"""Where a display only touches the others at the bottom-right corner of the desktop.
The cursor crosses from one display to another only along a shared edge, so a display that meets the
rest at a single point is the hardest one for the mouse to wander onto.
"""
right = max(d["rect"][2] for d in physical)
bottom = max(d["rect"][3] for d in physical if d["rect"][2] == right)
return right, bottom
def move_display(device: str, x: int, y: int) -> list[int]:
"""Move a display; returns the two ChangeDisplaySettingsEx results (0 = DISP_CHANGE_SUCCESSFUL)."""
_, _, user32 = _dlls()
dm = DEVMODEW()
dm.dmSize = ctypes.sizeof(DEVMODEW)
if not user32.EnumDisplaySettingsW(device, ENUM_CURRENT_SETTINGS, ctypes.byref(dm)):
return [-99]
dm.dmFields = DM_POSITION
dm.dmPosition.x, dm.dmPosition.y = x, y
a = user32.ChangeDisplaySettingsExW(device, ctypes.byref(dm), None, CDS_UPDATEREGISTRY | CDS_NORESET, None)
b = user32.ChangeDisplaySettingsExW(None, None, None, 0, None)
return [a, b]