Debian Codegraph @

DisplayCAL/mscms.py

raw
1 """Provides a thread-safe interface for the Windows Color System API.
2
3 This isolates the actual communication with WinAPI to separate process.
4 Windows only.
5
6 References and useful info:
7
8 According to https://learn.microsoft.com/en-us/previous-versions/troubleshoot/windows/win32/geticmprofile-might-leak-one-more-handles-windows-10 and
9 https://learn.microsoft.com/en-us/troubleshoot/windows/win32/geticmprofile-might-leak-one-or-more-handles-on-windows10
10 (in case one of those breaks eventually) Microsoft couldn't be bothered to fix
11 leaking handles in mscms.dll in Windows 10. That causes issues for applications
12 which do frequent calls to the leaking API calls:
13
14 + GetICMProfile
15 + EnumICMProfiles
16 + WcsGetDefaultColorProfile
17 + WcsGetDefaultColorProfileSize
18 + WcsGetUsePerUserProfiles
19
20 Other mitigation tactics possible:
21
22 + closing suspicious reg handles to specific keys
23 (https://gist.github.com/AySz88/7a233d84632498a8de382c1199f859f2 and
24 DisplayCal has its own implementation in _win10_1903_close_leaked_regkey_handles()).
25 + using said APIs less (caching, etc)
26 + restarting once in a while (profile loader, according to the changelog 3.8.7,
27 restarts each day at 4.00 due to leaks in SetDeviceGammaRamp).
28 + calling such APIs in separate processes
29
30 """ # noqa: E501
31
32 from __future__ import annotations
33
34 import atexit
35 import builtins
36 import logging
37 import multiprocessing
38 import sys
39 import threading
40 import uuid
41 from functools import wraps
42 from logging.handlers import QueueHandler, QueueListener
43 from multiprocessing import Process, Queue
44 from queue import Empty
45 from threading import Lock, Thread
46 from time import sleep
47 from typing import (
48 Any,
49 Callable,
50 Literal,
51 TypeVar,
52 Union,
53 )
54
55 import psutil
56
57 if sys.version_info >= (3, 11):
58 from typing import NotRequired, ParamSpec, TypedDict
59 else:
60 from typing_extensions import NotRequired, ParamSpec, TypedDict
61
62
63 from DisplayCAL.mscms_types import (
64 COLORPROFILESUBTYPE,
65 COLORPROFILETYPE,
66 WCS_PROF_SCOPE,
67 dwDeviceClass,
68 )
69
70 if sys.platform == "win32":
71 from DisplayCAL.mscms_wrapper import WCS
72 else:
73
74 class WCS:
75 """Placeholder class for non-Windows platforms."""
76
77 def __getattribute__(self, name: str) -> None:
78 """Placeholder method."""
79 raise NotImplementedError("Windows only")
80
81 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
82 """Placeholder method."""
83 raise NotImplementedError("Windows only")
84
85 def __delattr__(self, name: str) -> None:
86 """Placeholder method."""
87 raise NotImplementedError("Windows only")
88
89 def __call__(self, *args, **kwargs) -> None:
90 """Placeholder method."""
91 raise NotImplementedError("Windows only")
92
93
94 default_logging_level = logging.INFO
95 logger = logging.getLogger(__name__ + ".manager")
96 logger.setLevel(default_logging_level)
97 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
98 # Only attach a real stderr handler when stderr is an interactive console.
99 # A frozen windowed exe (py2exe) replaces sys.stderr with a lazily-opening
100 # log-file shim that pops up an "Errors in ..." dialog on exit for ANY
101 # write, even plain INFO messages, so stay silent there (see #804).
102 if hasattr(sys.stderr, "isatty") and sys.stderr.isatty():
103 ch = logging.StreamHandler()
104 else:
105 ch = logging.NullHandler()
106 ch.setFormatter(formatter)
107 logger.addHandler(ch)
108 logger.propagate = False
109
110 check_handles_call_num = 100 # check leaking handles every <num> of calls
111 open_handles_threshold = 3000 # worker process open handle limit
112
113 FILE_NOT_FOUND_ERRNO = 2
114
115
116 class RequestType(TypedDict):
117 """Represents a request sent to the worker process."""
118
119 id: str
120 method: str
121 args: Any
122 kwargs: Any
123
124
125 class ErrorType(TypedDict):
126 """Represents an error response from the worker process."""
127
128 type: str
129 message: str
130 errno: NotRequired[Any]
131
132
133 class SuccessResponseType(TypedDict):
134 """Represents a successful response from the worker process."""
135
136 type: Literal["resp_success"]
137 id: str
138 result: Any
139
140
141 class FailureResponseType(TypedDict):
142 """Represents an error response from the worker process."""
143
144 type: Literal["resp_error"]
145 id: str
146 error: ErrorType
147
148
149 ResponseType = Union[SuccessResponseType, FailureResponseType]
150
151
152 class PendingType(TypedDict):
153 """Represents a pending request in the WCSManager."""
154
155 event: threading.Event
156 result: NotRequired[Any]
157 error: NotRequired[ErrorType]
158
159
160 class WCSError(Exception):
161 """Base class for WCS-related errors."""
162
163
164 class WCSManagerShutdownError(WCSError):
165 """Error type for operations attempted while WCSManager is shutting down."""
166
167
168 class WCSWorkerError(WCSError):
169 """Generic error type for exceptions raised during remote execution."""
170
171
172 F_Spec = ParamSpec("F_Spec")
173 F_Return = TypeVar("F_Return")
174
175
176 def retry(
177 retries: int = 5,
178 base_delay: float = 0.1,
179 retry_on: tuple[type[Exception], ...] = (Exception,),
180 ) -> Callable[[Callable[F_Spec, F_Return]], Callable[F_Spec, F_Return]]:
181 """A simple retry decorator with exponential backoff for specified exceptions."""
182
183 def real_retry(func: Callable[F_Spec, F_Return]) -> Callable[F_Spec, F_Return]:
184 @wraps(func)
185 def wrapper(*args: F_Spec.args, **kwargs: F_Spec.kwargs) -> F_Return:
186 if retries < 0:
187 raise ValueError("Retries must be non-negative")
188
189 if base_delay < 0:
190 raise ValueError("Base delay must be non-negative")
191
192 attempt = 0
193 last_exception: None | Exception = None
194 while attempt <= retries:
195 if attempt > 0: # logging as retry after first attempt
196 logger.debug(
197 f"Retrying {func.__name__}: "
198 f"attempt {attempt}/{retries} after {last_exception}"
199 )
200
201 try:
202 return func(*args, **kwargs)
203 except retry_on as e:
204 attempt += 1
205 last_exception = e
206
207 if attempt <= retries:
208 delay = base_delay * (
209 2 ** (attempt - 1)
210 ) # exponential backoff with no jitter
211 logger.debug(
212 f"Retryable error caught in {func.__name__}: {e}. "
213 f"Retrying in {delay:.3f}s..."
214 )
215 sleep(delay)
216 else:
217 raise last_exception from e
218 except Exception as e:
219 logger.debug(f"Stopping retry in {func.__name__} on exception: {e}")
220 raise
221 raise RuntimeError("General retry decorator error")
222
223 return wrapper
224
225 return real_retry
226
227
228 def _wcs_worker_process(
229 request_queue: Queue[RequestType | None],
230 response_queue: Queue[ResponseType],
231 log_queue: Queue[Any],
232 ) -> None:
233 wcs_instance = None
234
235 log_queue_handler = QueueHandler(log_queue)
236 logger = logging.getLogger(__name__ + ".wcsworker")
237 logger.setLevel(default_logging_level)
238 logger.addHandler(log_queue_handler)
239 logger.propagate = False
240
241 logger.info("WCSWorker process started")
242
243 try:
244 wcs_instance = WCS()
245 logger.debug("WCS instance initialized in worker")
246
247 while True:
248 try:
249 request: None | RequestType = request_queue.get(timeout=1.0)
250 except Empty:
251 continue
252
253 if request is None:
254 logger.info("WCSWorker received poison pill")
255 break
256
257 request_id = request.get("id")
258 method_name: str = request.get("method")
259 args = request.get("args", ())
260 kwargs = request.get("kwargs", {})
261
262 logger.debug(f"WCSWorker processing request ID {request_id}: {method_name}")
263
264 try:
265 method = getattr(wcs_instance, method_name)
266 result = method(*args, **kwargs)
267 response: ResponseType = {
268 "type": "resp_success",
269 "id": request_id,
270 "result": result,
271 }
272 except Exception as e:
273 response: ResponseType = {
274 "type": "resp_error",
275 "id": request_id,
276 "error": {
277 "type": type(e).__name__,
278 "message": str(e),
279 "errno": getattr(e, "errno", None), # if present
280 },
281 }
282
283 try:
284 response_queue.put(response)
285 logger.debug(f"WCSWorker sent response for request ID {request_id}")
286 except Exception as e:
287 logger.error(f"Failed to send response for request {request_id}: {e}")
288
289 except Exception as e:
290 logger.critical(f"Unexpected error in WCSWorker process: {e}", exc_info=True)
291 finally:
292 logger.info("WCSWorker process shutting down")
293 if wcs_instance:
294 del wcs_instance
295 # Potential logger reuse handling
296 for handler in logger.handlers[:]:
297 handler.close()
298 logger.removeHandler(handler)
299
300
301 class WCSManager:
302 """WCSManager class.
303
304 Note: can only be initialized once.
305
306 Args:
307 handle_threshold (int, optional): Maximum open handles limit.
308 Defaults to 10000.
309 request_timeout (float, optional): Timeout for an individual request
310 (note the retry logic and compound requests). Defaults to 10.0.
311 """
312
313 def __init__(
314 self,
315 handle_threshold: int = open_handles_threshold, # will restart once in a while
316 request_timeout: float = 10.0,
317 ) -> None:
318 if hasattr(self, "_initialized"):
319 return
320
321 self.handle_threshold = handle_threshold
322 self.request_timeout = request_timeout
323
324 self._lock = Lock()
325 self._worker_process: None | Process = None
326 self._request_queue: None | RequestType = Queue()
327 self._response_queue: None | ResponseType = Queue()
328 self._log_queue: Queue[Any] = Queue()
329 self._log_listener: None | QueueListener = None
330 self._pending_requests: dict[str, PendingType] = {}
331 self._shutdown_event = threading.Event()
332 self._wcs_calls_made = 0
333
334 self._response_listener_thread: None | Thread = None
335
336 handlers = logger.handlers if logger.handlers else [logging.StreamHandler()]
337 self._log_listener = QueueListener(
338 self._log_queue, *handlers, respect_handler_level=True
339 )
340 self._log_listener.start()
341 logger.debug("QueueListener for worker logs started")
342
343 self._start_worker()
344 self._initialized = True
345 atexit.register(self._atexit_shutdown)
346 logger.info("WCSManager initialized")
347
348 def _start_worker(self) -> None:
349 """Start the worker process and response listener thread."""
350 with self._lock:
351 if self._worker_process and self._worker_process.is_alive():
352 logger.warning("Worker is already running")
353 return
354
355 self._shutdown_event.clear()
356
357 self._worker_process = multiprocessing.Process(
358 target=_wcs_worker_process,
359 args=(self._request_queue, self._response_queue, self._log_queue),
360 )
361 self._worker_process.start()
362 logger.info(
363 f"WCSWorker process started with PID {self._worker_process.pid}"
364 )
365
366 self._response_listener_thread = Thread(
367 target=self._listen_for_responses, daemon=True
368 )
369 self._response_listener_thread.start()
370 logger.debug("Response listener thread started")
371
372 def _stop_worker(self) -> None:
373 """Stop the worker process with timeout and forceful termination if needed."""
374 with self._lock:
375 if not self._worker_process or not self._worker_process.is_alive():
376 logger.debug("Worker is not running")
377 return
378
379 logger.info("Sending shutdown signal to WCSWorker")
380 try:
381 # Poison Pill
382 self._request_queue.put(None)
383 except Exception as e:
384 logger.error(f"Failed to send shutdown signal: {e}")
385
386 # Waiting for process completion
387 self._worker_process.join(timeout=5.0)
388 if self._worker_process.is_alive():
389 logger.warning(
390 "WCSWorker did not terminate gracefully, terminating forcefully."
391 )
392 self._worker_process.terminate()
393 self._worker_process.join(timeout=2.0)
394
395 if self._worker_process.is_alive():
396 logger.error("Failed to terminate WCSWorker process")
397 else:
398 logger.info("WCSWorker process terminated")
399
400 self._shutdown_event.set() # Closing down listener and call functionality
401
402 def _handle_check_worker(self) -> None:
403 logger.info("Performing worker process open handle check")
404
405 p = None
406 num_handles = 0
407
408 try:
409 if self._worker_process:
410 p = psutil.Process(self._worker_process.pid)
411 num_handles = p.num_handles()
412 else:
413 logger.warning("No running worker process discovered")
414
415 except Exception as e:
416 logger.warning(
417 "Failed to get handle count for process "
418 f"{p.pid if p else 'unknown'}: {e}"
419 )
420 return
421
422 if num_handles > self.handle_threshold:
423 logger.debug(
424 "Open handle number exceeded: "
425 f"{num_handles}>{self.handle_threshold}. "
426 "Restarting worker process"
427 )
428 self._stop_worker()
429 self._start_worker()
430 logger.info("WCSWorker restarted successfully")
431 else:
432 logger.debug(f"Current child process open handles: {num_handles}")
433
434 def _listen_for_responses(self) -> None:
435 logger.debug("Response listener thread main loop started")
436 while not self._shutdown_event.is_set():
437 try:
438 # Short timeout to be able to stop the thread
439 response = self._response_queue.get(timeout=1.0)
440 except Empty:
441 continue
442 except Exception as e:
443 if not self._shutdown_event.is_set():
444 logger.error(f"Error getting response from queue: {e}")
445 continue
446
447 # Regular path
448 request_id = response.get("id")
449 logger.debug(f"Received response for request ID {request_id}")
450
451 with self._lock:
452 if request_id in self._pending_requests:
453 req_data = self._pending_requests.pop(request_id)
454 event = req_data.get("event")
455 if event:
456 req_data["result"] = response.get("result")
457 if "error" in response:
458 req_data["error"] = response.get("error")
459 self._pending_requests[request_id] = req_data
460 event.set() # signal _call_wcs_method
461 else:
462 logger.warning(
463 f"Received response for unknown request ID {request_id}"
464 )
465
466 logger.debug("Response listener thread loop finished")
467
468 @retry(retry_on=(RuntimeError, TimeoutError))
469 def _call_wcs_method(self, method_name: str, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401
470 if self._shutdown_event.is_set():
471 raise WCSManagerShutdownError("WCSManager is set to shut down")
472
473 request_id = str(uuid.uuid4())
474 request: RequestType = {
475 "id": request_id,
476 "method": method_name,
477 "args": args,
478 "kwargs": kwargs,
479 }
480
481 event = threading.Event()
482 with self._lock:
483 logger.debug(f"Request ID {request_id} added to the pending requests")
484 self._pending_requests[request_id] = {"event": event}
485
486 try:
487 self._request_queue.put(request)
488 logger.debug(f"Sent request ID {request_id} for method {method_name}")
489 except Exception as e:
490 with self._lock:
491 self._pending_requests.pop(request_id, None)
492 logger.debug(
493 f"Request ID {request_id} removed from pending requests: "
494 "cancellation"
495 )
496 raise RuntimeError(f"Failed to send request to worker: {e}") from e
497
498 with self._lock:
499 self._wcs_calls_made += 1
500
501 if self._wcs_calls_made % check_handles_call_num == 0:
502 logger.debug("Worker process open handle check triggered")
503 # Launch in other thread to not block the listener
504 threading.Thread(target=self._handle_check_worker, daemon=True).start()
505
506 # Waiting for an answer to be received
507 if not event.wait(timeout=self.request_timeout):
508 with self._lock:
509 self._pending_requests.pop(request_id, None)
510 logger.debug(
511 f"Request ID {request_id} removed from pending requests: timeout"
512 )
513 raise TimeoutError(f"Timeout waiting for response to request {request_id}")
514
515 # Processing the result
516 with self._lock:
517 req_data = self._pending_requests.pop(request_id, {})
518 logger.debug(
519 f"Request ID {request_id} removed from pending requests: success"
520 )
521
522 if "error" in req_data: # error path
523 error_response = req_data.get("error")
524 if error_response:
525 error_type = error_response.get("type")
526 error_message = error_response.get("message")
527 error_errno = error_response.get("errno")
528
529 # Recreating exceptions
530 try:
531 exc_class = getattr(builtins, error_type)
532 except Exception:
533 exc_class = WCSWorkerError
534
535 if issubclass(exc_class, OSError):
536 exc = exc_class(error_message)
537 if error_errno is not None:
538 exc.errno = error_errno
539 raise exc
540 # Something else might have happened
541 raise exc_class(f"{error_type}: {error_message}")
542
543 # normal path
544 return req_data.get("result")
545
546 def shutdown(self) -> None:
547 """Shutdowns the worker process and listener thread."""
548 if self._shutdown_event.is_set():
549 logger.debug("WCSManager is already set to shut down")
550 return
551 logger.info("Shutting down WCSManager...")
552 self._shutdown_event.set()
553
554 logger.debug("Stopping worker process and threads")
555 self._stop_worker()
556
557 if self._response_listener_thread and self._response_listener_thread.is_alive():
558 self._response_listener_thread.join(timeout=2.0)
559 logger.info("WCSManager shut down complete")
560
561 def _atexit_shutdown(self) -> None:
562 """Shutdown handler for atexit to ensure cleanup on normal interpreter exit."""
563 if not self._shutdown_event.is_set():
564 logger.info("WCSManager: atexit triggered shutdown")
565 self.shutdown()
566
567 def associate_color_profile_with_device(
568 self, scope: WCS_PROF_SCOPE, profile_name: str, device_key: str
569 ) -> None:
570 """Associate a specified WCS color profile with a specified device.
571
572 This API does not support "advanced color" profiles for HDR monitors.
573
574 Note: this API makes the added profile also be the default one.
575
576 Args:
577 scope (WCS_PROF_SCOPE): specifies the scope of this profile management
578 operation, which could be system-wide or for the current user.
579 profile_name (str): file name of the profile to associate.
580 device_key (str): device key of the device with which to associate
581 the profile.
582
583 Raises:
584 OSError: in case of Win API errors.
585 TimeoutError: if timeout occurs while waiting for worker response.
586 WCSManagerShutdownError: if manager is shutting down.
587 WCSWorkerError: in case of some unspecified error during remote execution.
588 RuntimeError: in case of unrecoverable IPC errors.
589 """
590 self._call_wcs_method(
591 "AssociateColorProfileWithDevice", scope, profile_name, device_key
592 )
593
594 def disassociate_color_profile_from_device(
595 self, scope: WCS_PROF_SCOPE, profile_name: str, device_key: str
596 ) -> None:
597 """Disassociate a specified WCS color profile from a specified device.
598
599 This API does not support "advanced color" profiles for HDR monitors.
600
601 Note: very unreliable due to quirks, the actual result should be
602 double-checked with profile listing.
603
604 Args:
605 scope (WCS_PROF_SCOPE): specifies the scope of this profile
606 management operation, which could be system-wide or for the
607 current user.
608 profile_name (str): file name of the profile to disassociate.
609 device_key (str): device key of the device from which to
610 disassociate the profile.
611
612 Raises:
613 OSError: in case of Win API errors.
614 TimeoutError: if timeout occurs while waiting for worker response.
615 WCSManagerShutdownError: if manager is shutting down.
616 WCSWorkerError: in case of some unspecified error during remote execution.
617 RuntimeError: in case of unrecoverable IPC errors.
618 """
619 self._call_wcs_method(
620 "DisassociateColorProfileFromDevice", scope, profile_name, device_key
621 )
622
623 def get_device_color_profile_list(
624 self,
625 scope: WCS_PROF_SCOPE,
626 device_key: str,
627 device_class: dwDeviceClass = dwDeviceClass.CLASS_MONITOR,
628 ) -> list[str]:
629 """Enumerate color profiles associated with a device.
630
631 This API does not support "advanced color" profiles for HDR monitors.
632
633 Args:
634 scope (WCS_PROF_SCOPE): specifies the scope of this profile
635 management operation, which could be system-wide or for the
636 current user.
637 device_key (str): device key of the device.
638 device_class (dwDeviceClass, optional): device class. Defaults to
639 dwDeviceClass.CLASS_MONITOR.
640
641 Raises:
642 OSError: in case of Win API errors.l
643 TimeoutError: if timeout occurs while waiting for worker response.
644 WCSManagerShutdownError: if manager is shutting down.
645 WCSWorkerError: in case of some unspecified error during remote execution.
646 RuntimeError: in case of unrecoverable IPC errors.
647 ValueError: on parsing errors.
648
649 Returns:
650 list[str]: array of profile names
651 """
652 prof_list: list[str] = self._call_wcs_method(
653 "getDeviceColorProfileList", scope, device_key, device_class
654 )
655 return prof_list
656
657 def get_calibration_management_state(self) -> bool:
658 """Determine if system management of the display calibration state is enabled.
659
660 Raises:
661 OSError: in case of Win API errors.
662 TimeoutError: if timeout occurs while waiting for worker response.
663 WCSManagerShutdownError: if manager is shutting down.
664 WCSWorkerError: in case of some unspecified error during remote execution.
665 RuntimeError: in case of unrecoverable IPC errors.
666
667 Returns:
668 bool: True if system management of the display calibration state is
669 enabled; otherwise, False
670 """
671 return self._call_wcs_method("GetCalibrationManagementState")
672
673 def set_calibration_management_state(self, new_state: bool) -> None:
674 """Enable or disables system management of the display calibration state.
675
676 Args:
677 new_state (bool): True to enable system management of the display
678 calibration state. False to disable it.
679
680 Raises:
681 OSError: in case of Win API errors.
682 TimeoutError: if timeout occurs while waiting for worker response.
683 WCSManagerShutdownError: if manager is shutting down.
684 WCSWorkerError: in case of some unspecified error during remote execution.
685 RuntimeError: in case of unrecoverable IPC errors.
686 """
687 return self._call_wcs_method("SetCalibrationManagementState", new_state)
688
689 def get_default_color_profile(
690 self,
691 scope: WCS_PROF_SCOPE,
692 device_key: str,
693 c_prof_type: COLORPROFILETYPE = COLORPROFILETYPE.CPT_ICC,
694 c_prof_subtype: COLORPROFILESUBTYPE = COLORPROFILESUBTYPE.CPST_NONE,
695 profile_id: int = 0,
696 ) -> None | str:
697 """Retrieve the default color profile for a device.
698
699 This API does not support "advanced color" profiles for HDR monitors.
700
701 Note: If HDR is enabled on a device, it causes OSError.
702
703 Args:
704 scope (WCS_PROF_SCOPE): specifies the scope of this profile
705 management operation, which could be system-wide or for the
706 current user.
707 device_key (str): device key of the device for which the default
708 color profile is obtained. If empty string, a device-independent
709 default is obtained.
710 c_prof_type (COLORPROFILETYPE, optional): value specifying the
711 color profile type. Defaults to `COLORPROFILETYPE.CPT_ICC`.
712 c_prof_subtype (COLORPROFILESUBTYPE, optional): Value specifying
713 the color profile subtype. Defaults to `COLORPROFILESUBTYPE.CPST_NONE`.
714 profile_id (int, optional): ID of the color space that the color
715 profile represents. Defaults to 0.
716
717 Raises:
718 OSError: If a Win API error occurs.
719 TimeoutError: If a timeout occurs while waiting for worker response.
720 WCSManagerShutdownError: If the manager is shutting down.
721 WCSWorkerError: In case of some unspecified error during remote execution.
722 RuntimeError: If unrecoverable IPC errors occur.
723
724 Returns:
725 str: the name of the default color profile for the device (or None
726 if not set)
727 """
728 try:
729 size = self._call_wcs_method(
730 "GetDefaultColorProfileSize",
731 scope,
732 device_key,
733 c_prof_type,
734 c_prof_subtype,
735 profile_id,
736 )
737 return self._call_wcs_method(
738 "GetDefaultColorProfile",
739 scope,
740 device_key,
741 size,
742 c_prof_type,
743 c_prof_subtype,
744 profile_id,
745 )
746 except FileNotFoundError: # no default profile
747 pass
748 return None
749
750 def set_default_color_profile(
751 self,
752 scope: WCS_PROF_SCOPE,
753 device_key: str,
754 profile_name: str,
755 c_prof_type: COLORPROFILETYPE = COLORPROFILETYPE.CPT_ICC,
756 c_prof_subtype: COLORPROFILESUBTYPE = COLORPROFILESUBTYPE.CPST_NONE,
757 profile_id: int = 0,
758 ) -> None:
759 """Set the default color profile name for the specified profile type.
760
761 This API does not support "advanced color" profiles for HDR monitors.
762
763 Args:
764 scope (WCS_PROF_SCOPE): Specifies the scope of this profile management
765 operation, which could be system-wide or for the current user.
766 device_key (str): Device key of the device for which the default
767 color profile is to be set. If empty string, a device-independent
768 default profile is set.
769 profile_name (str): File name of the profile.
770 c_prof_type (COLORPROFILETYPE, optional): Value specifying the color
771 profile type. Defaults to `COLORPROFILETYPE.CPT_ICC`.
772 c_prof_subtype (COLORPROFILESUBTYPE, optional): Value specifying
773 the color profile subtype. Defaults to
774 `COLORPROFILESUBTYPE.CPST_NONE`.
775 profile_id (int, optional): ID of the color space that the color
776 profile represents. Defaults to 0.
777
778 Raises:
779 OSError: If Win API error is raised.
780 TimeoutError: If timeout occurs while waiting for worker response.
781 WCSManagerShutdownError: If manager is shutting down.
782 WCSWorkerError: If some unspecified error occurs during remote execution.
783 RuntimeError: If unrecoverable IPC errors occur.
784 """
785 self._call_wcs_method(
786 "SetDefaultColorProfile",
787 scope,
788 device_key,
789 profile_name,
790 c_prof_type,
791 c_prof_subtype,
792 profile_id,
793 )
794
795 def get_use_per_user_profiles(
796 self, device_key: str, device_class: dwDeviceClass = dwDeviceClass.CLASS_MONITOR
797 ) -> bool:
798 """Determine if per-user profile association is enabled for the device.
799
800 Args:
801 device_key (str): Device key of the device.
802 device_class (dwDeviceClass, optional): The class of the device.
803 Defaults to `dwDeviceClass.CLASS_MONITOR`.
804
805 Raises:
806 OSError: If Win API error is raised.
807 TimeoutError: If timeout occurs while waiting for worker response.
808 WCSManagerShutdownError: If manager is shutting down.
809 WCSWorkerError: If some unspecified error occurs during remote execution.
810 RuntimeError: If unrecoverable IPC errors occur.
811
812 Returns:
813 bool: True if the user chose to use a per-user profile association
814 list for the specified device; otherwise False
815 """
816 return self._call_wcs_method("GetUsePerUserProfiles", device_key, device_class)
817
818 def set_use_per_user_profiles(
819 self,
820 device_key: str,
821 new_state: bool,
822 device_class: dwDeviceClass = dwDeviceClass.CLASS_MONITOR,
823 ) -> None:
824 """Enable or disable per-user profile association for a device.
825
826 Args:
827 device_key (str): Device key of the device.
828 new_state (bool): True if the user wants to use a per-user profile
829 association list for the specified device; otherwise False.
830 device_class (dwDeviceClass, optional): The class of the device.
831 Defaults to dwDeviceClass.CLASS_MONITOR
832
833 Raises:
834 OSError: If Win API error is raised.
835 TimeoutError: If timeout occurs while waiting for worker response.
836 WCSManagerShutdownError: If manager is shutting down.
837 WCSWorkerError: If some unspecified error occurs during remote execution.
838 RuntimeError: If unrecoverable IPC errors occur.
839 """
840 self._call_wcs_method(
841 "SetUsePerUserProfiles", device_key, new_state, device_class
842 )
843
844
845 class WCSManagerProxy:
846 """Proxy class for WCSManager to ensure single instance and lazy initialization."""
847
848 _instance = None
849 _lock = Lock()
850
851 def _ensure_instance(self) -> None:
852 """Ensure that the WCSManager instance is created."""
853 if WCSManagerProxy._instance is None:
854 with WCSManagerProxy._lock:
855 if WCSManagerProxy._instance is None:
856 WCSManagerProxy._instance = WCSManager()
857
858 def __getattr__(self, name: str) -> Any: # noqa: ANN401
859 """Ensure instance exists before getting attributes."""
860 self._ensure_instance()
861 return getattr(WCSManagerProxy._instance, name)
862
863 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
864 """Ensure instance exists before setting attributes."""
865 self._ensure_instance()
866 setattr(WCSManagerProxy._instance, name, value)
867
868 def __delattr__(self, name: str) -> None:
869 """Ensure instance exists before deleting attributes."""
870 self._ensure_instance()
871 delattr(WCSManagerProxy._instance, name)
872
873 def __call__(self, *args, **kwargs) -> WCSManager:
874 """Make the proxy callable."""
875 self._ensure_instance()
876 if callable(WCSManagerProxy._instance):
877 return WCSManagerProxy._instance(*args, **kwargs)
878 raise TypeError(
879 f"'{type(WCSManagerProxy._instance).__name__}' object is not callable"
880 )
881
882 def __repr__(self) -> str:
883 """String representation of the proxy instance."""
884 if WCSManagerProxy._instance is None:
885 return "<WCSManagerProxy (not initialized)>"
886 return f"<WCSManagerProxy wrapping {WCSManagerProxy._instance!r}>"