Debian Codegraph @

DisplayCAL/util_win.py

raw
1 """Windows utility functions for display, process, and color management."""
2
3 from __future__ import annotations
4
5 import _ctypes
6 import ctypes
7 import platform
8 import struct
9 import sys
10 import winreg
11 from ctypes import POINTER, byref, sizeof, windll, wintypes
12 from ctypes.wintypes import DWORD, HANDLE, LPWSTR
13 from typing import TYPE_CHECKING, Any
14
15 import pywintypes
16 import win32api
17 import win32con
18 import win32process
19 import winerror
20 from win32comext.shell import shell as win32com_shell
21
22 from DisplayCAL.mscms import WCSManagerProxy
23 from DisplayCAL.util_os import quote_args
24 from DisplayCAL.win_structs import UNICODE_STRING
25
26 mscms = WCSManagerProxy()
27
28 if TYPE_CHECKING:
29 from _win32typing import PyDISPLAY_DEVICE
30
31
32 if not hasattr(ctypes, "c_bool"):
33 # Python 2.5
34 ctypes.c_bool = ctypes.c_int
35
36 if sys.getwindowsversion() >= (6,):
37 LPDWORD = POINTER(DWORD)
38 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
39 kernel32 = windll.kernel32
40 QueryFullProcessImageNameW = kernel32.QueryFullProcessImageNameW
41 QueryFullProcessImageNameW.argtypes = [HANDLE, DWORD, LPWSTR, LPDWORD]
42 QueryFullProcessImageNameW.restype = bool
43
44 try:
45 psapi = ctypes.windll.psapi
46 except OSError:
47 psapi = None
48
49
50 # Access registry directly instead of Wcs* functions that leak handles
51 USE_REGISTRY = True
52
53
54 # DISPLAY_DEVICE structure, StateFlags member
55 # http://msdn.microsoft.com/en-us/library/dd183569%28v=vs.85%29.aspx
56
57 # wingdi.h
58
59 # Flags for parent devices
60 DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 0x1
61 DISPLAY_DEVICE_MIRRORING_DRIVER = 0x8
62 """Represents a pseudo device used to mirror application drawing for remoting or
63 other purposes.
64
65 An invisible pseudo monitor is associated with this device.
66
67 For example, NetMeeting uses it.
68 Note that GetSystemMetrics (SM_MONITORS) only accounts for visible display monitors.
69 """
70 DISPLAY_DEVICE_MODESPRUNED = (
71 0x8000000 # The device has more display modes than its output devices support.
72 )
73 DISPLAY_DEVICE_PRIMARY_DEVICE = 0x4
74 """The primary desktop is on the device.
75 For a system with a single display card, this is always set.
76 For a system with multiple display cards, only one device can have this set.
77 """
78 DISPLAY_DEVICE_REMOVABLE = (
79 0x20 # The device is removable; it cannot be the primary display.
80 )
81 DISPLAY_DEVICE_VGA_COMPATIBLE = 0x10 # The device is VGA compatible.
82 DISPLAY_DEVICE_DISCONNECT = 0x2000000
83 DISPLAY_DEVICE_MULTI_DRIVER = 0x2
84 DISPLAY_DEVICE_REMOTE = 0x4000000
85
86 # Flags for child devices
87 DISPLAY_DEVICE_ACTIVE = 0x1
88 """DISPLAY_DEVICE_ACTIVE specifies whether a monitor is presented as being "on"
89 by the respective GDI view.
90
91 Windows Vista:
92 EnumDisplayDevices will only enumerate monitors that can be presented as being "on."
93 """
94 DISPLAY_DEVICE_ATTACHED = 0x2
95
96
97 # MONITORINFO structure, dwFlags member
98 # https://msdn.microsoft.com/de-de/library/windows/desktop/dd145065(v=vs.85).aspx
99 MONITORINFOF_PRIMARY = 0x1
100
101 # Icm.h
102 CLASS_MONITOR = struct.unpack("!L", b"mntr")[0]
103 CLASS_PRINTER = struct.unpack("!L", b"prtr")[0]
104 CLASS_SCANNER = struct.unpack("!L", b"scnr")[0]
105
106 # ShellExecute
107 SEE_MASK_FLAG_NO_UI = 0x00000400
108 SEE_MASK_NOASYNC = 0x00000100
109 SEE_MASK_NOCLOSEPROCESS = 0x00000040
110 SEE_MASK_WAITFORINPUTIDLE = 0x02000000
111
112
113 def _get_icm_display_device_key(devicekey):
114 monkey = devicekey.split("\\")[-2:] # pun totally intended
115 subkey = "\\".join(
116 [
117 "Software",
118 "Microsoft",
119 "Windows NT",
120 "CurrentVersion",
121 "ICM",
122 "ProfileAssociations",
123 "Display",
124 *monkey,
125 ]
126 )
127 return winreg.CreateKey(winreg.HKEY_CURRENT_USER, subkey)
128
129
130 class MSCMSLoader:
131 """Loader class for MSCMS."""
132
133 _windll = None
134
135 @classmethod
136 def get_mscms_windll(cls) -> MSCMS:
137 """Get the MSCMS windll instance.
138
139 Returns:
140 MSCMS: The MSCMS windll instance.
141 """
142 if not cls._windll:
143 cls._windll = MSCMS()
144 return cls._windll
145
146
147 def _get_mscms_windll():
148 return MSCMSLoader.get_mscms_windll()
149
150
151 def calibration_management_isenabled() -> bool:
152 """Check if calibration is enabled under Windows 7.
153
154 Returns:
155 bool: True if calibration is enabled, False otherwise.
156 """
157 if sys.getwindowsversion() < (6, 1):
158 # Windows XP and Vista don't have calibration management
159 return False
160 return mscms.get_calibration_management_state()
161
162
163 def disable_calibration_management():
164 """Disable calibration loading under Windows 7."""
165 enable_calibration_management(False)
166
167
168 def disable_per_user_profiles(display_no: int = 0) -> None:
169 """Disable per user profiles under Vista/Windows 7.
170
171 Args:
172 display_no (int): The display number.
173 """
174 enable_per_user_profiles(False, display_no)
175
176
177 def enable_calibration_management(enable: bool = True) -> bool:
178 """Enable calibration loading under Windows 7.
179
180 Args:
181 enable (bool): Whether to enable calibration management.
182
183 Raises:
184 NotImplementedError: If the OS version is less than Windows 7.
185 get_windows_error: If an error occurs while setting the calibration
186 management state.
187
188 Returns:
189 bool: True if successful, False otherwise.
190 """
191 if sys.getwindowsversion() < (6, 1):
192 raise NotImplementedError(
193 "Calibration Management is only available in Windows 7 or later"
194 )
195 mscms.set_calibration_management_state(enable)
196 return True
197
198
199 def enable_per_user_profiles(
200 enable: bool = True, display_no: int = 0, devicekey: None | str = None
201 ) -> bool:
202 """Enable per user profiles under Vista/Windows 7.
203
204 Args:
205 enable (bool): Whether to enable per user profiles.
206 display_no (int): The display number.
207 devicekey (str): The device key.
208
209 Raises:
210 NotImplementedError: If the OS version is less than Windows Vista.
211 get_windows_error: If an error occurs while setting the per user
212 profiles state.
213
214 Returns:
215 bool: True if successful, False otherwise.
216 """
217 if sys.getwindowsversion() < (6,):
218 # Windows XP doesn't have per-user profiles
219 raise NotImplementedError(
220 "Per-user profiles are only available in Windows Vista, 7 or later"
221 )
222 if not devicekey:
223 device = get_display_device(display_no)
224 if device:
225 devicekey = device.DeviceKey
226 if devicekey:
227 mscms.set_use_per_user_profiles(devicekey, enable)
228 return True
229 return False
230
231
232 def get_display_devices(devicename: str) -> list[PyDISPLAY_DEVICE]:
233 r"""Get all display devices of an output (there can be several).
234
235 Example usage:
236 get_display_devices('\\\\.\\DISPLAY1')
237 devicename = '\\\\.\\DISPLAYn' where n is a positive integer starting at 1.
238
239 Args:
240 devicename (str): The device name.
241
242 Returns:
243 list[PyDISPLAY_DEVICE]: List of display devices.
244 """
245 devices = []
246 n = 0
247 while True:
248 try:
249 devices.append(win32api.EnumDisplayDevices(devicename, n))
250 except pywintypes.error:
251 break
252 n += 1
253 return devices
254
255
256 def get_first_display_device(
257 devicename: str, exception_cls: Exception = pywintypes.error
258 ) -> PyDISPLAY_DEVICE:
259 """Get the first display of device <devicename>.
260
261 Args:
262 devicename (str): The device name.
263 exception_cls (Exception): The exception class to catch.
264
265 Returns:
266 PyDISPLAY_DEVICE: The first display device.
267 """
268 try:
269 return win32api.EnumDisplayDevices(devicename, 0)
270 except exception_cls:
271 pass
272
273
274 def get_active_display_device(
275 devicename: str, devices: None | list[PyDISPLAY_DEVICE] = None
276 ) -> PyDISPLAY_DEVICE:
277 r"""Get active display device of an output (there can only be one per output).
278
279 Return value: display device object or None.
280
281 Example usage:
282 get_active_display_device('\\\\.\\DISPLAY1')
283 devicename = '\\\\.\\DISPLAYn' where n is a positive integer starting at 1.
284
285 Args:
286 devicename (str): The device name.
287 devices (None | list[PyDISPLAY_DEVICE]): List of devices.
288
289 Returns:
290 PyDISPLAY_DEVICE: The active display device (display device object) or None.
291 """
292 if not devices:
293 devices = get_display_devices(devicename)
294 for device in devices:
295 if device.StateFlags & DISPLAY_DEVICE_ACTIVE and (
296 len(devices) == 1 or device.StateFlags & DISPLAY_DEVICE_ATTACHED
297 ):
298 return device
299 return None
300
301
302 def get_active_display_devices(
303 attrname: None | str = None,
304 ) -> list[PyDISPLAY_DEVICE]:
305 """Return active display devices.
306
307 Args:
308 attrname (None | str): The attribute name to get from the display device.
309
310 Returns:
311 list[PyDISPLAY_DEVICE]: List of active display devices.
312 """
313 devices = []
314 for moninfo in get_real_display_devices_info():
315 device = get_active_display_device(moninfo["Device"])
316 if device:
317 if attrname:
318 device = getattr(device, attrname)
319 devices.append(device)
320 return devices
321
322
323 def get_display_device(
324 display_no: int = 0,
325 use_active_display_device: bool = False,
326 exception_cls: Exception = pywintypes.error,
327 ) -> PyDISPLAY_DEVICE:
328 """Get the display device for a given display number.
329
330 Args:
331 display_no (int): The display number.
332 use_active_display_device (bool): Whether to use the active display device.
333 exception_cls (Exception): The exception class to catch.
334
335 Returns:
336 DisplayDevice: The display device.
337 """
338 # The ordering will work as long as Argyll continues using EnumDisplayMonitors
339 monitors = get_real_display_devices_info()
340 moninfo = monitors[display_no]
341 if use_active_display_device:
342 return get_active_display_device(moninfo["Device"])
343 return get_first_display_device(moninfo["Device"], exception_cls)
344
345
346 def get_process_filename(pid: int, handle: int = 0) -> str:
347 """Get the filename of a process.
348
349 Args:
350 pid (int): The process ID.
351 handle (int): The process handle.
352
353 Raises:
354 WinError: If an error occurs while querying the process filename.
355
356 Returns:
357 str: The filename of the process.
358 """
359 if sys.getwindowsversion() >= (6,):
360 flags = PROCESS_QUERY_LIMITED_INFORMATION
361 else:
362 flags = win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ
363 if not handle:
364 handle = win32api.OpenProcess(flags, False, pid)
365 try:
366 if sys.getwindowsversion() >= (6,):
367 dwSize = win32con.MAX_PATH
368 while True:
369 dwFlags = 0 # The name should use the Win32 path format
370 lpdwSize = DWORD(dwSize)
371 lpExeName = ctypes.create_unicode_buffer("", lpdwSize.value + 1)
372 success = QueryFullProcessImageNameW(
373 int(handle), dwFlags, lpExeName, byref(lpdwSize)
374 )
375 if success and 0 < lpdwSize.value < dwSize:
376 break
377 error = kernel32.GetLastError()
378 if error != winerror.ERROR_INSUFFICIENT_BUFFER:
379 raise ctypes.WinError(error)
380 dwSize = dwSize + 256
381 if dwSize > 0x1000:
382 # This prevents an infinite loop under Windows Server 2008
383 # if the path contains spaces, see
384 # http://msdn.microsoft.com/en-us/library/ms684919(VS.85).aspx#4
385 raise ctypes.WinError(error)
386 filename = lpExeName.value
387 else:
388 filename = win32process.GetModuleFileNameEx(handle, 0)
389 finally:
390 win32api.CloseHandle(handle)
391 return filename
392
393
394 def get_file_info(filename: str) -> dict:
395 """Get exe/dll file information.
396
397 Args:
398 filename (str): The filename.
399
400 Returns:
401 dict: The file information.
402 """
403 info = {"FileInfo": None, "StringFileInfo": {}, "FileVersion": None}
404
405 finfo = win32api.GetFileVersionInfo(filename, "\\")
406 info["FileInfo"] = finfo
407 info["FileVersion"] = "{:d}.{:d}.{:d}.{:d}".format(
408 finfo["FileVersionMS"] / 65536,
409 finfo["FileVersionMS"] % 65536,
410 finfo["FileVersionLS"] / 65536,
411 finfo["FileVersionLS"] % 65536,
412 )
413 for lcid, codepage in win32api.GetFileVersionInfo(
414 filename, "\\VarFileInfo\\Translation"
415 ):
416 info["StringFileInfo"][lcid, codepage] = {}
417 for name in [
418 "Comments",
419 "CompanyName",
420 "FileDescription",
421 "FileVersion",
422 "InternalName",
423 "LegalCopyright",
424 "LegalTrademarks",
425 "OriginalFilename",
426 "PrivateBuild",
427 "ProductName",
428 "ProductVersion",
429 "SpecialBuild",
430 ]:
431 value = win32api.GetFileVersionInfo(
432 filename, f"\\StringFileInfo\\{lcid:04X}{codepage:04X}\\{name}"
433 )
434 if value is not None:
435 info["StringFileInfo"][lcid, codepage][name] = value
436
437 return info
438
439
440 def get_pids() -> list[int]:
441 """Get PIDs of all running processes.
442
443 Raises:
444 ImportError: If the psapi module is not available.
445 get_windows_error: If an error occurs while enumerating processes.
446
447 Returns:
448 list[int]: List of PIDs.
449 """
450 if psapi is None:
451 raise ImportError(
452 "psapi module is not available. "
453 "Please ensure it is installed and accessible."
454 )
455 pids_count = 1024
456 while True:
457 pids = (DWORD * pids_count)()
458 pids_size = sizeof(pids)
459 byte_words = DWORD()
460 if not psapi.EnumProcesses(byref(pids), pids_size, byref(byte_words)):
461 raise get_windows_error(ctypes.windll.kernel32.GetLastError())
462 if byte_words.value >= pids_size:
463 pids_count *= 2
464 continue
465 count = byte_words.value / (pids_size / pids_count)
466 return [_f for _f in pids[:count] if _f]
467
468
469 def get_real_display_devices_info() -> list[dict]:
470 """Return info for real (non-virtual) devices.
471
472 Returns:
473 list[dict]: List of monitor info.
474 """
475 # See Argyll source spectro/dispwin.c MonitorEnumProc, get_displays
476 monitors = []
477 try:
478 monitor_list = win32api.EnumDisplayMonitors(None, None)
479 except Exception:
480 return monitors
481 for monitor in monitor_list:
482 try:
483 # Convert PyHANDLE to int using the .handle attribute
484 hMonitor = monitor[0].handle
485 moninfo = win32api.GetMonitorInfo(hMonitor)
486 except Exception:
487 pass
488 else:
489 if moninfo and not moninfo["Device"].startswith("\\\\.\\DISPLAYV"):
490 monitors.append(moninfo)
491 return monitors
492
493
494 def get_windows_error(errorcode: int) -> ctypes.WinError:
495 """Get a Windows error message.
496
497 Args:
498 errorcode (int): The error code.
499
500 Returns:
501 ctypes.WinError: The Windows error message.
502 """
503 return ctypes.WinError(errorcode)
504
505
506 def per_user_profiles_isenabled(
507 display_no: int = 0, devicekey: None | str = None
508 ) -> bool:
509 """Check if per user profiles is enabled under Vista/Windows 7.
510
511 Args:
512 display_no (int): The display number.
513 devicekey (str): The device key.
514
515 Raises:
516 WindowsError: If an error occurs while querying the registry.
517
518 Returns:
519 bool: True if per user profiles is enabled, False otherwise.
520 """
521 if sys.getwindowsversion() < (6,):
522 # Windows XP doesn't have per-user profiles
523 return False
524 if not devicekey:
525 device = get_display_device(display_no)
526 if device:
527 devicekey = device.DeviceKey
528 if not devicekey:
529 return None
530 return mscms.get_use_per_user_profiles(devicekey)
531
532
533 def run_as_admin(
534 cmd: str,
535 args: list[Any],
536 close_process: bool = True,
537 async_: bool = False,
538 wait_for_idle: bool = False,
539 show: bool = True,
540 ) -> dict:
541 """Run command with elevated privileges.
542
543 This is a wrapper around ShellExecuteEx.
544
545 Args:
546 cmd (str): The command to run.
547 args (list[Any]): The arguments for the command.
548 close_process (bool): Whether to close the process after execution.
549 async_ (bool): Whether to run the command asynchronously.
550 wait_for_idle (bool): Whether to wait for the process to be idle.
551 show (bool): Whether to show the command window.
552
553 Returns:
554 dict: A dictionary with hInstApp and hProcess members.
555 """
556 return shell_exec(cmd, args, "runas", close_process, async_, wait_for_idle, show)
557
558
559 def shell_exec(
560 filename: str,
561 args: list[Any],
562 operation: str = "open",
563 close_process: bool = True,
564 async_: bool = False,
565 wait_for_idle: bool = False,
566 show: bool = True,
567 ) -> dict:
568 """Run command.
569
570 This is a wrapper around ShellExecuteEx.
571
572 Args:
573 filename (str): The filename to execute.
574 args (list): The arguments for the command.
575 operation (str): The operation to perform.
576 close_process (bool): Whether to close the process after execution.
577 async_ (bool): Whether to run the command asynchronously.
578 wait_for_idle (bool): Whether to wait for the process to be idle.
579 show (bool): Whether to show the command window.
580
581 Returns:
582 dict: A dictionary with hInstApp and hProcess members.
583 """
584 flags = SEE_MASK_FLAG_NO_UI
585 if not close_process:
586 flags |= SEE_MASK_NOCLOSEPROCESS
587 if not async_:
588 flags |= SEE_MASK_NOASYNC
589 if wait_for_idle:
590 flags |= SEE_MASK_WAITFORINPUTIDLE
591 params = " ".join(quote_args(args))
592 show = win32con.SW_SHOWNORMAL if show else win32con.SW_HIDE
593 return win32com_shell.ShellExecuteEx(
594 fMask=flags, lpVerb=operation, lpFile=filename, lpParameters=params, nShow=show
595 )
596
597
598 def win_ver() -> tuple[str, int, str, str]:
599 """Get Windows version info.
600
601 Returns:
602 tuple[str, int, str, str]: A tuple containing the product name, CSD
603 version, release, and build.
604 """
605 csd = sys.getwindowsversion()[-1]
606 # Use the registry to get product name, e.g. 'Windows 7 Ultimate'.
607 # Not recommended, but we don't care.
608 pname = "Windows"
609 release = ""
610 build = ""
611 key = None
612 sam = winreg.KEY_READ
613 if platform.machine() == "AMD64":
614 sam |= winreg.KEY_WOW64_64KEY
615 try:
616 key = winreg.OpenKeyEx(
617 winreg.HKEY_LOCAL_MACHINE,
618 r"SOFTWARE\Microsoft\Windows NT\CurrentVersion",
619 0,
620 sam,
621 )
622 pname = winreg.QueryValueEx(key, "ProductName")[0]
623 build = f"Build {winreg.QueryValueEx(key, 'CurrentBuildNumber')[0]}"
624 # Since Windows 10
625 release = f"Version {winreg.QueryValueEx(key, 'ReleaseId')[0]}"
626 build += f".{winreg.QueryValueEx(key, 'UBR')[0]}"
627 except Exception:
628 pass
629 finally:
630 if key:
631 winreg.CloseKey(key)
632 return pname, csd, release, build
633
634
635 def is_advanced_color_enabled(gdi_device_name: str) -> bool | None:
636 """Check if Advanced Color (HDR) is enabled for a GDI display device.
637
638 Uses the Windows QueryDisplayConfig API to determine whether the named
639 display device has Advanced Color mode active. Returns None if the state
640 cannot be determined (older drivers, pre-Win8.1, or API error).
641
642 Args:
643 gdi_device_name (str): The GDI device name, e.g. '\\\\.\\DISPLAY1'.
644
645 Returns:
646 bool | None: True if Advanced Color is enabled, False if not,
647 None if the state could not be determined.
648 """
649 if sys.getwindowsversion() < (6, 2):
650 return None
651
652 try:
653 QDC_ONLY_ACTIVE_PATHS = 0x00000002
654 DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_GDI_DEVICE_NAME = 3
655 DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO = 9
656 DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO2 = 16
657 CCHDEVICENAME = 32
658 ADVANCED_COLOR_ENABLED_BIT = 0x2
659 DISPLAYCONFIG_ADVANCED_COLOR_MODE_HDR = 2
660
661 class _LUID(ctypes.Structure):
662 _fields_ = [
663 ("LowPart", wintypes.DWORD),
664 ("HighPart", wintypes.LONG),
665 ]
666
667 class _RATIONAL(ctypes.Structure):
668 _fields_ = [
669 ("Numerator", wintypes.UINT),
670 ("Denominator", wintypes.UINT),
671 ]
672
673 class _PATH_SOURCE_INFO(ctypes.Structure):
674 _fields_ = [
675 ("adapterId", _LUID),
676 ("id", wintypes.UINT),
677 ("modeInfoIdx", wintypes.UINT),
678 ("statusFlags", wintypes.UINT),
679 ]
680
681 class _PATH_TARGET_INFO(ctypes.Structure):
682 _fields_ = [
683 ("adapterId", _LUID),
684 ("id", wintypes.UINT),
685 ("modeInfoIdx", wintypes.UINT),
686 ("outputTechnology", wintypes.UINT),
687 ("rotation", wintypes.UINT),
688 ("scaling", wintypes.UINT),
689 ("refreshRate", _RATIONAL),
690 ("scanLineOrdering", wintypes.UINT),
691 ("targetAvailable", wintypes.BOOL),
692 ("statusFlags", wintypes.UINT),
693 ]
694
695 class _PATH_INFO(ctypes.Structure):
696 _fields_ = [
697 ("sourceInfo", _PATH_SOURCE_INFO),
698 ("targetInfo", _PATH_TARGET_INFO),
699 ("flags", wintypes.UINT),
700 ]
701
702 class _DEVICE_INFO_HEADER(ctypes.Structure):
703 _fields_ = [
704 ("type", wintypes.UINT),
705 ("size", wintypes.UINT),
706 ("adapterId", _LUID),
707 ("id", wintypes.UINT),
708 ]
709
710 class _SOURCE_DEVICE_NAME(ctypes.Structure):
711 _fields_ = [
712 ("header", _DEVICE_INFO_HEADER),
713 ("viewGdiDeviceName", ctypes.c_wchar * CCHDEVICENAME),
714 ]
715
716 class _ADVANCED_COLOR_INFO(ctypes.Structure):
717 _fields_ = [
718 ("header", _DEVICE_INFO_HEADER),
719 ("value", wintypes.UINT),
720 ("colorEncoding", wintypes.UINT),
721 ("bitsPerColorChannel", wintypes.UINT),
722 ]
723
724 # DISPLAYCONFIG_ADVANCED_COLOR_INFO2 — introduced in Windows 11 22H2
725 # (build 22621). activeColorMode == 2 means HDR is active.
726 class _ADVANCED_COLOR_INFO2(ctypes.Structure):
727 _fields_ = [
728 ("header", _DEVICE_INFO_HEADER),
729 ("activeColorMode", wintypes.UINT),
730 ("value", wintypes.UINT),
731 ("sdrWhiteLevel", wintypes.UINT),
732 ]
733
734 # DISPLAYCONFIG_MODE_INFO is a union-containing struct; its size is
735 # 64 bytes on both 32-bit and 64-bit Windows.
736 class _MODE_INFO(ctypes.Structure):
737 _fields_ = [("_data", ctypes.c_uint8 * 64)]
738
739 user32 = ctypes.windll.user32
740 num_paths = wintypes.UINT(0)
741 num_modes = wintypes.UINT(0)
742
743 if user32.GetDisplayConfigBufferSizes(
744 QDC_ONLY_ACTIVE_PATHS,
745 ctypes.byref(num_paths),
746 ctypes.byref(num_modes),
747 ) != 0:
748 return None
749
750 paths = (_PATH_INFO * num_paths.value)()
751 modes = (_MODE_INFO * num_modes.value)()
752
753 if user32.QueryDisplayConfig(
754 QDC_ONLY_ACTIVE_PATHS,
755 ctypes.byref(num_paths),
756 paths,
757 ctypes.byref(num_modes),
758 modes,
759 None,
760 ) != 0:
761 return None
762
763 gdi_name_lower = gdi_device_name.lower()
764 for i in range(num_paths.value):
765 path = paths[i]
766
767 src_name = _SOURCE_DEVICE_NAME()
768 src_name.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_GDI_DEVICE_NAME
769 src_name.header.size = ctypes.sizeof(_SOURCE_DEVICE_NAME)
770 src_name.header.adapterId = path.sourceInfo.adapterId
771 src_name.header.id = path.sourceInfo.id
772
773 if user32.DisplayConfigGetDeviceInfo(ctypes.byref(src_name)) != 0:
774 continue
775
776 if src_name.viewGdiDeviceName.lower() != gdi_name_lower:
777 continue
778
779 # Try the newer type-16 API first (Windows 11 22H2+, build
780 # 22621+). On those builds the "Use HDR" toggle no longer sets
781 # advancedColorEnabled in the type-9 struct, so the old check
782 # incorrectly returns False when HDR is active (issue #627).
783 adv_color2 = _ADVANCED_COLOR_INFO2()
784 adv_color2.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO2
785 adv_color2.header.size = ctypes.sizeof(_ADVANCED_COLOR_INFO2)
786 adv_color2.header.adapterId = path.targetInfo.adapterId
787 adv_color2.header.id = path.targetInfo.id
788
789 if user32.DisplayConfigGetDeviceInfo(ctypes.byref(adv_color2)) == 0:
790 return adv_color2.activeColorMode == DISPLAYCONFIG_ADVANCED_COLOR_MODE_HDR
791
792 # Fall back to the older type-9 API (pre-Win11 22H2).
793 adv_color = _ADVANCED_COLOR_INFO()
794 adv_color.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO
795 adv_color.header.size = ctypes.sizeof(_ADVANCED_COLOR_INFO)
796 adv_color.header.adapterId = path.targetInfo.adapterId
797 adv_color.header.id = path.targetInfo.id
798
799 if user32.DisplayConfigGetDeviceInfo(ctypes.byref(adv_color)) != 0:
800 return None
801
802 return bool(adv_color.value & ADVANCED_COLOR_ENABLED_BIT)
803
804 return None
805
806 except Exception:
807 return None
808
809
810 def get_gdi_device_name_for_devicekey(devicekey: str) -> str | None:
811 """Return the GDI device name (e.g. '\\\\.\\DISPLAY1') for a device key.
812
813 Args:
814 devicekey (str): The registry device key.
815
816 Returns:
817 str | None: The GDI device name, or None if not found.
818 """
819 for moninfo in get_real_display_devices_info():
820 device = get_active_display_device(moninfo["Device"])
821 if device and device.DeviceKey == devicekey:
822 return moninfo["Device"]
823 return None
824
825
826 USE_NTDLL_LDR = False
827
828
829 def _free_library(handle):
830 fn = ctypes.windll.ntdll.LdrUnloadDll if USE_NTDLL_LDR else _ctypes.FreeLibrary
831 fn(handle)
832
833
834 class UnloadableWinDLL:
835 """WinDLL wrapper that allows unloading."""
836
837 def __init__(self, dllname):
838 self.dllname = dllname
839 self._windll = None
840 self.load()
841
842 def __getattr__(self, name: str) -> Any: # noqa: ANN401
843 """Get an attribute from the loaded DLL.
844
845 Args:
846 name (str): The name of the attribute.
847
848 Returns:
849 The attribute from the loaded DLL.
850 """
851 self.load()
852 return getattr(self._windll, name)
853
854 def __bool__(self) -> bool:
855 """Check if the DLL is loaded.
856
857 Returns:
858 bool: True if the DLL is loaded, False otherwise.
859 """
860 self.load()
861 return bool(self._windll)
862
863 def load(self) -> None:
864 """Load the DLL."""
865 if not self._windll:
866 if USE_NTDLL_LDR:
867 mod = byref(UNICODE_STRING(len(self.dllname) * 2, 256, self.dllname))
868 handle = wintypes.HANDLE()
869 ctypes.windll.ntdll.LdrLoadDll(None, 0, mod, byref(handle))
870 windll = ctypes.WinDLL(self.dllname, handle=handle.value)
871 else:
872 windll = ctypes.WinDLL(self.dllname)
873 self._windll = windll
874
875 def unload(self) -> None:
876 """Unload the DLL."""
877 if self._windll:
878 handle = self._windll._handle
879 self._windll = None
880 _free_library(handle)
881
882
883 class MSCMS(UnloadableWinDLL):
884 """MSCMS wrapper (optionally) allowing unloading."""
885
886 def __init__(self, bootstrap_icm32=False) -> None:
887 self._icm32_handle = None
888 UnloadableWinDLL.__init__(self, "mscms.dll")
889 if bootstrap_icm32:
890 # Need to load & unload icm32 once before unloading of mscms can
891 # work in every situation (some calls to mscms methods pull in
892 # icm32, if we haven't loaded/unloaded it before, we won't be able
893 # to unload then)
894 self._icm32_handle = ctypes.WinDLL("icm32")._handle
895 _free_library(self._icm32_handle)
896
897 def load(self) -> None:
898 """Load the MSCMS DLL."""
899 mscms = self._windll
900 UnloadableWinDLL.load(self)
901 if self._windll is not mscms:
902 mscms = self._windll
903 if mscms: # Ensure mscms is not None
904 mscms.WcsGetDefaultColorProfileSize.restype = ctypes.c_bool
905 mscms.WcsGetDefaultColorProfile.restype = ctypes.c_bool
906 mscms.WcsAssociateColorProfileWithDevice.restype = ctypes.c_bool
907 mscms.WcsDisassociateColorProfileFromDevice.restype = ctypes.c_bool
908
909 def unload(self) -> None:
910 """Unload the MSCMS DLL.
911
912 Raises:
913 WindowsError: If an error occurs while unloading the DLL.
914 """
915 if self._windll:
916 if self._icm32_handle:
917 # Need to free icm32 first, otherwise mscms won't unload
918 try:
919 _free_library(self._icm32_handle)
920 except OSError as exception:
921 if exception.args[0] != winerror.ERROR_MOD_NOT_FOUND:
922 raise
923 UnloadableWinDLL.unload(self)
924
925
926 if __name__ == "__main__":
927 if "calibration" in sys.argv[1:]:
928 if "enable" in sys.argv[1:] or "disable" in sys.argv[1:]:
929 enable_calibration_management(sys.argv[1:][-1] != "disable")
930 print(calibration_management_isenabled())
931 elif "per_user_profiles" in sys.argv[1:]:
932 if "enable" in sys.argv[1:] or "disable" in sys.argv[1:]:
933 enable_per_user_profiles(sys.argv[1:][-1] != "disable")
934 print(per_user_profiles_isenabled())