Debian Codegraph @

DisplayCAL/profile_loader.py

raw
1 """Set ICC profiles and load calibration curves for all configured display devices."""
2
3 # Standard Library Imports
4 from __future__ import annotations
5
6 import contextlib
7 import ctypes
8 import math
9 import os
10 import re
11 import subprocess as sp
12 import sys
13 import threading
14 import time
15 import traceback
16 import warnings
17 from typing import TYPE_CHECKING, Any, Callable
18
19 # Local Imports
20 from DisplayCAL import (
21 config,
22 madvr,
23 )
24 from DisplayCAL.colord import Device, device_id_from_edid
25 from DisplayCAL.colormath import smooth_avg
26 from DisplayCAL.config import (
27 APPBASENAME,
28 AUTOSTART,
29 AUTOSTART_HOME,
30 CONFIG_HOME,
31 ENC,
32 EXE,
33 EXEDIR,
34 ICCPROFILES,
35 PYDIR,
36 get_data_path,
37 get_default_dpi,
38 get_icon,
39 get_icon_bundle,
40 getcfg,
41 setcfg,
42 )
43 from DisplayCAL.debughelpers import Error, UnloggedError, handle_error
44 from DisplayCAL.edid import get_edid
45 from DisplayCAL.icc_profile import (
46 ADict,
47 DictType,
48 ICCProfile,
49 ICCProfileInvalidError,
50 VideoCardGammaFormulaType,
51 VideoCardGammaType,
52 WcsProfilesTagType,
53 get_display_profile,
54 set_display_profile,
55 unset_display_profile,
56 )
57 from DisplayCAL.meta import (
58 DOMAIN,
59 VERSION_STRING,
60 )
61 from DisplayCAL.meta import (
62 NAME as APPNAME,
63 )
64 from DisplayCAL.options import DEBUG, VERBOSE
65 from DisplayCAL.util_list import natsort_key_factory
66 from DisplayCAL.util_mac import osascript
67 from DisplayCAL.util_os import (
68 getenvu,
69 is_superuser,
70 islink,
71 readlink,
72 safe_glob,
73 which,
74 )
75 from DisplayCAL.util_str import safe_asciize
76 from DisplayCAL.wx_addons import CustomGridCellEvent
77 from DisplayCAL.wx_fixes import ThemedGenButton
78 from DisplayCAL.wx_windows import (
79 BaseApp,
80 BaseFrame,
81 ConfirmDialog,
82 CustomCellBoolRenderer,
83 CustomGrid,
84 InfoDialog,
85 TaskBarNotification,
86 get_dialogs,
87 show_result_dialog,
88 wx,
89 )
90
91 if sys.platform == "win32":
92 import errno
93 import winreg
94
95 import pywintypes
96 import win32api
97 import win32gui
98 import win32process
99 import win32ts
100 import winerror
101
102 from DisplayCAL.icc_profile import _winreg_get_display_profiles
103 from DisplayCAL.systrayicon import Menu, MenuItem, SysTrayIcon
104 from DisplayCAL.util_win import (
105 DISPLAY_DEVICE_ACTIVE,
106 MONITORINFOF_PRIMARY,
107 USE_REGISTRY,
108 calibration_management_isenabled,
109 enable_per_user_profiles,
110 get_active_display_device,
111 get_active_display_devices,
112 get_display_devices,
113 get_file_info,
114 get_first_display_device,
115 get_process_filename,
116 get_real_display_devices_info,
117 per_user_profiles_isenabled,
118 run_as_admin,
119 win_ver,
120 )
121
122 if islink(EXE):
123 try:
124 EXE = readlink(EXE)
125 except Exception:
126 pass
127 else:
128 EXEDIR = os.path.dirname(EXE)
129 else:
130 SysTrayIcon = object # type: ignore[misc]
131
132 def calibration_management_isenabled() -> bool:
133 """Stub for non-Windows platforms."""
134 return False
135
136
137 if TYPE_CHECKING:
138 from _win32typing import PyDISPLAY_DEVICE
139
140 from DisplayCAL.worker import Worker
141
142
143 def debug_print(*args, **kwargs) -> None:
144 """Print debug messages."""
145 if DEBUG or VERBOSE > 1:
146 print(*args, **kwargs)
147
148
149 def setup_profile_loader_task(exe: str, exedir: str, pydir: str) -> None:
150 """Setup profile loader task for Windows.
151
152 Args:
153 exe (str): Path to the executable.
154 exedir (str): Directory of the executable.
155 pydir (str): Directory of the Python installation.
156 """
157 print("setup_profile_loader_task start")
158 if sys.getwindowsversion() < (6,):
159 print("setup_profile_loader_task end 1")
160 return
161
162 from DisplayCAL import taskscheduler
163
164 taskname = f"{APPNAME} Profile Loader Launcher"
165
166 try:
167 ts = taskscheduler.TaskScheduler()
168 except Exception as exception:
169 print("Warning - could not access task scheduler:", exception)
170 print("setup_profile_loader_task end 2")
171 return
172
173 if "--task" not in sys.argv[1:] and is_superuser() and not ts.query_task(taskname):
174 # Check if our task exists, and if it does not, create it.
175 # (requires admin privileges)
176 print(f"Trying to create task {taskname}...")
177 # Note that we use a stub so the task cannot be accidentally
178 # stopped (the stub launches the actual profile loader and
179 # then immediately exits)
180 loader_args = []
181 if os.path.basename(exe).lower() in ("python.exe", "pythonw.exe"):
182 cmd = os.path.join(exedir, "pythonw.exe")
183 pyw = os.path.normpath(
184 os.path.join(pydir, "..", f"{APPNAME}-apply-profiles.pyw")
185 )
186 script = get_data_path(
187 "/".join(["scripts", f"{APPNAME}-apply-profiles-launcher"])
188 )
189 if os.path.exists(pyw):
190 # Running from source or 0install
191 # Check if this is a 0install implementation, in which
192 # case we want to call 0launch with the appropriate
193 # command
194 if re.match(
195 r"sha\d+(?:new)?",
196 os.path.basename(os.path.dirname(pydir)),
197 ):
198 # No stub needed as 0install-win acts as stub
199 cmd = which("0install-win.exe") or "0install-win.exe"
200 loader_args.extend(
201 [
202 "run",
203 "--batch",
204 "--no-wait",
205 "--offline",
206 "--command=run-apply-profiles",
207 "--",
208 f"http://{DOMAIN}/0install/{APPNAME}.xml",
209 "--task",
210 ]
211 )
212 else:
213 # Running from source
214 loader_args.append(script)
215 else:
216 # Regular (site-packages) install
217 loader_args.append(script)
218 else:
219 # Standalone executable
220 cmd = os.path.join(pydir, f"{APPNAME}-apply-profiles-launcher.exe")
221 # Start at login, restart when resuming from sleep,
222 # restart daily at 04:00
223 triggers = [
224 taskscheduler.LogonTrigger(),
225 taskscheduler.ResumeFromSleepTrigger(),
226 ]
227 daily = taskscheduler.CalendarTrigger(
228 start_boundary=time.strftime("%Y-%m-%dT04:00:00"),
229 days_interval=1,
230 )
231 actions = [taskscheduler.ExecAction(cmd, loader_args)]
232 try:
233 # Create the main task
234 created = ts.create_task(
235 taskname,
236 "Open Source Developer, Florian Höch",
237 "This task launches the profile "
238 "loader with the applicable "
239 "privileges for logged in users",
240 multiple_instances_policy=taskscheduler.MULTIPLEINSTANCES_IGNORENEW,
241 replace_existing=True,
242 triggers=triggers,
243 actions=actions,
244 )
245 # Create the supplementary task
246 created = ts.create_task(
247 f"{taskname} - Daily Restart",
248 "Open Source Developer, Florian Höch",
249 "This task restarts the profile "
250 "loader with the applicable "
251 "privileges for logged in users",
252 multiple_instances_policy=taskscheduler.MULTIPLEINSTANCES_IGNORENEW,
253 replace_existing=True,
254 triggers=[daily],
255 actions=actions,
256 )
257 except Exception as exception:
258 if DEBUG:
259 exception = traceback.format_exc()
260 print(
261 f"Warning - Could not create task {taskname}:",
262 exception,
263 )
264 if ts.stdout:
265 print(str(ts.stdout, encoding=ENC, errors="replace"))
266 else:
267 print(str(ts.stdout, encoding=ENC, errors="replace"))
268 if created:
269 # Remove autostart entries, if any
270 name = f"{APPNAME} Profile Loader"
271 entries = []
272 if AUTOSTART:
273 entries.append(os.path.join(AUTOSTART, f"{name}.lnk"))
274 if AUTOSTART_HOME:
275 entries.append(os.path.join(AUTOSTART_HOME, f"{name}.lnk"))
276 for entry in entries:
277 if os.path.isfile(entry):
278 print("Removing", entry)
279 try:
280 os.remove(entry)
281 except OSError as exception:
282 print(exception)
283
284 if "Windows 10" not in win_ver()[0]:
285 print("setup_profile_loader_task end 3")
286 return
287
288 # Disable Windows Calibration Loader.
289 # This is absolutely REQUIRED under Win10 1903 to prevent
290 # banding and not applying calibration twice
291 ms_cal_loader = r"\Microsoft\Windows\WindowsColorSystem\Calibration Loader"
292 try:
293 ts.disable(ms_cal_loader)
294 except Exception as exception:
295 print(
296 f"Warning - Could not disable task {ms_cal_loader!r}:",
297 exception,
298 )
299 if ts.stdout:
300 print(str(ts.stdout, encoding=ENC, errors="replace"))
301 else:
302 print(str(ts.stdout, encoding=ENC, errors="replace"))
303 print("setup_profile_loader_task end 4")
304
305
306 class DisplayIdentificationFrame(wx.Frame):
307 """Frame to show display identification.
308
309 Args:
310 display (str): The display identifier, typically in the format
311 "DISPLAY_NAME@EDID - [DESCRIPTION]".
312 pos (tuple): The position of the frame on the screen.
313 size (tuple): The size of the frame, typically in pixels.
314 """
315
316 def __init__(self, display: str, pos: tuple, size: tuple) -> None:
317 wx.Frame.__init__(
318 self,
319 None,
320 pos=pos,
321 size=size,
322 style=wx.CLIP_CHILDREN
323 | wx.STAY_ON_TOP
324 | wx.FRAME_NO_TASKBAR
325 | wx.NO_BORDER,
326 name="DisplayIdentification",
327 )
328 self.SetTransparent(240)
329 self.Sizer = wx.BoxSizer()
330 panel_outer = wx.Panel(self)
331 panel_outer.BackgroundColour = "#303030"
332 panel_outer.Sizer = wx.BoxSizer()
333 self.Sizer.Add(panel_outer, 1, flag=wx.EXPAND)
334 panel_inner = wx.Panel(panel_outer)
335 panel_inner.BackgroundColour = "#0078d7"
336 panel_inner.Sizer = wx.BoxSizer()
337 panel_outer.Sizer.Add(
338 panel_inner,
339 1,
340 flag=wx.ALL | wx.EXPAND,
341 border=math.ceil(size[0] / 12.0 / 40),
342 )
343 display_parts = display.split("@", 1)
344 if len(display_parts) > 1:
345 info = display_parts[1].split(" - ", 1)
346 display_parts[1] = "@" + " ".join(info[:1])
347 if info[1:]:
348 display_parts.append(" ".join(info[1:]))
349 label = "\n".join(display_parts)
350 text = wx.StaticText(panel_inner, -1, label, style=wx.ALIGN_CENTER)
351 text.ForegroundColour = "#FFFFFF"
352 font = wx.Font(
353 int(text.Font.PointSize * size[0] / 12.0 / 16),
354 wx.FONTFAMILY_DEFAULT,
355 wx.FONTSTYLE_NORMAL,
356 wx.FONTWEIGHT_LIGHT,
357 )
358 if not font.SetFaceName("Segoe UI Light"):
359 font = text.Font
360 font.PointSize *= size[0] / 12.0 / 16
361 font.weight = wx.FONTWEIGHT_LIGHT
362 text.Font = font
363 panel_inner.Sizer.Add(text, 1, flag=wx.ALIGN_CENTER_VERTICAL)
364 for element in (self, panel_outer, panel_inner, text):
365 element.Bind(wx.EVT_LEFT_UP, lambda e: self.Close())
366 element.Bind(wx.EVT_MIDDLE_UP, lambda e: self.Close())
367 element.Bind(wx.EVT_RIGHT_UP, lambda e: self.Close())
368 self.Bind(
369 wx.EVT_CHAR_HOOK, lambda e: e.KeyCode == wx.WXK_ESCAPE and self.Close()
370 )
371 self.Layout()
372 self.Show()
373 self.close_timer = wx.CallLater(3000, lambda: self and self.Close())
374
375
376 class FixProfileAssociationsDialog(ConfirmDialog):
377 """Dialog to show profile associations for displays.
378
379 Args:
380 pl (ProfileLoader): The profile loader instance.
381 parent (None | wx.Window, optional): The parent window for the dialog.
382 Defaults to None.
383 """
384
385 def __init__(self, pl: ProfileLoader, parent: None | wx.Window = None) -> None:
386 self.pl = pl
387 ConfirmDialog.__init__(
388 self,
389 parent,
390 msg=lang.getstr("profile_loader.fix_profile_associations_warning"),
391 title=pl.get_title(),
392 ok=lang.getstr("profile_loader.fix_profile_associations"),
393 bitmap=get_icon(32, "dialog-warning"),
394 wrap=128,
395 )
396 dlg = self
397 dlg.SetIcons(get_icon_bundle([256, 48, 32, 16], APPNAME + "-apply-profiles"))
398 scale = getcfg("app.dpi") / get_default_dpi()
399 scale = max(scale, 1)
400 list_panel = wx.Panel(dlg, -1)
401 list_panel.BackgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
402 list_panel.Sizer = wx.BoxSizer(wx.HORIZONTAL)
403 list_ctrl = wx.ListCtrl(
404 list_panel,
405 -1,
406 style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.BORDER_THEME,
407 name="displays2profiles",
408 )
409 list_panel.Sizer.Add(list_ctrl, 1, flag=wx.ALL, border=1)
410 list_ctrl.InsertColumn(0, lang.getstr("display"))
411 list_ctrl.InsertColumn(1, lang.getstr("profile"))
412 list_ctrl.SetColumnWidth(0, int(200 * scale))
413 list_ctrl.SetColumnWidth(1, int(420 * scale))
414 # Ignore item focus/selection
415 list_ctrl.Bind(
416 wx.EVT_LIST_ITEM_FOCUSED,
417 lambda e: list_ctrl.SetItemState(e.GetIndex(), 0, wx.LIST_STATE_FOCUSED),
418 )
419 list_ctrl.Bind(
420 wx.EVT_LIST_ITEM_SELECTED,
421 lambda e: list_ctrl.SetItemState(e.GetIndex(), 0, wx.LIST_STATE_SELECTED),
422 )
423 self.devices2profiles_ctrl = list_ctrl
424 dlg.sizer3.Insert(0, list_panel, 1, flag=wx.BOTTOM | wx.ALIGN_LEFT, border=12)
425 self.update()
426
427 def update(self, event: None | wx.Event = None) -> None:
428 """Update the list of displays and profiles.
429
430 Args:
431 event (wx.Event, optional): The event that triggered this update.
432 Defaults to None.
433 """
434 self.pl._set_display_profiles(dry_run=True)
435 numdisp = min(len(self.pl.devices2profiles), 5)
436 scale = getcfg("app.dpi") / get_default_dpi()
437 scale = max(scale, 1)
438 hscroll = wx.SystemSettings_GetMetric(wx.SYS_HSCROLL_Y)
439 size = (640 * scale, (20 * numdisp + 25 + hscroll) * scale)
440 list_ctrl = self.devices2profiles_ctrl
441 list_ctrl.MinSize = size
442 list_ctrl.DeleteAllItems()
443 for i, (display_edid, profile, desc) in enumerate(
444 self.pl.devices2profiles.values()
445 ):
446 index = list_ctrl.InsertStringItem(i, "")
447 display = display_edid[0].replace(
448 "[PRIMARY]", lang.getstr("display.primary")
449 )
450 list_ctrl.SetStringItem(index, 0, display)
451 list_ctrl.SetStringItem(index, 1, desc)
452 if not profile:
453 continue
454 try:
455 profile = ICCProfile(profile)
456 except (OSError, ICCProfileInvalidError):
457 pass
458 else:
459 if isinstance(profile.tags.get("meta"), DictType):
460 # Check if profile mapping makes sense
461 id1 = device_id_from_edid(display_edid[1], quirk=True)
462 id2 = device_id_from_edid(display_edid[1], quirk=False)
463 if profile.tags.meta.getvalue("MAPPING_device_id") not in (
464 id1,
465 id2,
466 ):
467 list_ctrl.SetItemTextColour(index, "#FF8000")
468 self.sizer0.SetSizeHints(self)
469 self.sizer0.Layout()
470 if event and not self.IsActive():
471 self.RequestUserAttention()
472
473
474 class ProfileLoaderExceptionsDialog(ConfirmDialog):
475 """Dialog to manage exceptions for the profile loader.
476
477 Args:
478 exceptions (dict): A dictionary of exceptions to manage.
479 known_apps (None | set, optional): A set of known application names to
480 prevent from being added as exceptions. Defaults to None.
481 """
482
483 def __init__(self, exceptions: dict, known_apps: None | set = None) -> None:
484 if known_apps is None:
485 known_apps = set()
486 self._exceptions = {}
487 self.known_apps = known_apps
488 scale = getcfg("app.dpi") / config.get_default_dpi()
489 scale = max(scale, 1)
490 ConfirmDialog.__init__(
491 self,
492 None,
493 title=lang.getstr("exceptions"),
494 ok=lang.getstr("ok"),
495 cancel=lang.getstr("cancel"),
496 wrap=120,
497 )
498
499 dlg = self
500
501 dlg.SetIcons(
502 config.get_icon_bundle([256, 48, 32, 16], APPNAME + "-apply-profiles")
503 )
504
505 dlg.delete_btn = wx.Button(dlg.buttonpanel, -1, lang.getstr("delete"))
506 dlg.sizer2.Insert(0, (12, 12))
507 dlg.sizer2.Insert(0, dlg.delete_btn)
508 dlg.delete_btn.Bind(wx.EVT_BUTTON, dlg.delete_handler)
509
510 dlg.browse_btn = wx.Button(dlg.buttonpanel, -1, lang.getstr("browse"))
511 dlg.sizer2.Insert(0, (12, 12))
512 dlg.sizer2.Insert(0, dlg.browse_btn)
513 dlg.browse_btn.Bind(wx.EVT_BUTTON, dlg.browse_handler)
514
515 dlg.add_btn = wx.Button(dlg.buttonpanel, -1, lang.getstr("add"))
516 dlg.sizer2.Insert(0, (12, 12))
517 dlg.sizer2.Insert(0, dlg.add_btn)
518 dlg.add_btn.Bind(wx.EVT_BUTTON, dlg.browse_handler)
519
520 style = wx.BORDER_SIMPLE if "gtk3" in wx.PlatformInfo else wx.BORDER_THEME
521 dlg.grid = CustomGrid(
522 dlg, -1, size=wx.Size(int(648 * scale), int(200 * scale)), style=style
523 )
524 grid = dlg.grid
525 grid.DisableDragRowSize()
526 grid.SetCellHighlightPenWidth(0)
527 grid.SetCellHighlightROPenWidth(0)
528 grid.SetDefaultCellAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)
529 grid.SetMargins(0, 0)
530 grid.SetRowLabelAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
531 grid.SetScrollRate(5, 5)
532 grid.draw_horizontal_grid_lines = False
533 grid.draw_vertical_grid_lines = False
534 grid.CreateGrid(0, 4)
535 grid.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
536 font = grid.GetDefaultCellFont()
537 if font.PointSize > 11:
538 font.PointSize = 11
539 grid.SetDefaultCellFont(font)
540 grid.SetColLabelSize(round(self.grid.GetDefaultRowSize() * 1.4))
541 dc = wx.MemoryDC(wx.EmptyBitmap(1, 1))
542 dc.SetFont(grid.GetLabelFont())
543 grid.SetRowLabelSize(max(dc.GetTextExtent("99")[0], grid.GetDefaultRowSize()))
544 for i in range(grid.GetNumberCols()):
545 if i > 1:
546 attr = wx.grid.GridCellAttr()
547 attr.SetReadOnly(True)
548 grid.SetColAttr(i, attr)
549 if i == 0:
550 # On/off checkbox
551 size = 22 * scale
552 elif i == 1:
553 # Profile loader state icon
554 size = 22 * scale
555 elif i == 2:
556 # Executable basename
557 size = dc.GetTextExtent("W" * 12)[0]
558 else:
559 # Directory component
560 size = dc.GetTextExtent("W" * 34)[0]
561 grid.SetColSize(i, int(size))
562 for i, label in enumerate(["", "", "executable", "directory"]):
563 grid.SetColLabelValue(i, lang.getstr(label))
564
565 # On/off checkbox
566 attr = wx.grid.GridCellAttr()
567 renderer = CustomCellBoolRenderer()
568 renderer._bitmap_unchecked = config.get_icon(16, "empty")
569 attr.SetRenderer(renderer)
570 grid.SetColAttr(0, attr)
571
572 # Profile loader state icon
573 attr = wx.grid.GridCellAttr()
574 renderer = CustomCellBoolRenderer()
575 renderer._bitmap = config.get_icon(16, "apply-profiles-reset")
576 bitmap = renderer._bitmap
577 image = bitmap.ConvertToImage().ConvertToGreyscale(0.75, 0.125, 0.125)
578 renderer._bitmap_unchecked = image.ConvertToBitmap()
579 attr.SetRenderer(renderer)
580 grid.SetColAttr(1, attr)
581
582 attr = wx.grid.GridCellAttr()
583 attr.SetRenderer(wx.grid.GridCellStringRenderer())
584 grid.SetColAttr(2, attr)
585
586 attr = wx.grid.GridCellAttr()
587 attr.SetRenderer(wx.grid.GridCellStringRenderer())
588 grid.SetColAttr(3, attr)
589
590 grid.EnableGridLines(False)
591
592 grid.BeginBatch()
593 for i, (key, (enabled, reset, path)) in enumerate(sorted(exceptions.items())):
594 grid.AppendRows(1)
595 grid.SetRowLabelValue(i, f"{i + 1:d}")
596 grid.SetCellValue(i, 0, "1" if enabled else "")
597 grid.SetCellValue(i, 1, "1" if reset else "")
598 grid.SetCellValue(i, 2, os.path.basename(path))
599 grid.SetCellValue(i, 3, os.path.dirname(path))
600 self._exceptions[key] = enabled, reset, path
601 grid.EndBatch()
602
603 grid.Bind(wx.EVT_KEY_DOWN, dlg.key_handler)
604 grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, dlg.cell_click_handler)
605 grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, dlg.cell_dclick_handler)
606 grid.Bind(wx.grid.EVT_GRID_SELECT_CELL, dlg.cell_select_handler)
607
608 dlg.sizer3.Add(grid, 1, flag=wx.LEFT | wx.ALIGN_LEFT, border=12)
609
610 # Legend
611 sizer = wx.FlexGridSizer(2, 2, 3, 1)
612 sizer.Add(wx.StaticBitmap(dlg, -1, renderer._bitmap_unchecked))
613 sizer.Add(wx.StaticText(dlg, -1, " = " + lang.getstr("profile_loader.disable")))
614 sizer.Add(wx.StaticBitmap(dlg, -1, renderer._bitmap))
615 sizer.Add(wx.StaticText(dlg, -1, " = " + lang.getstr("calibration.reset")))
616
617 dlg.sizer3.Add(sizer, 1, flag=wx.LEFT | wx.TOP | wx.ALIGN_LEFT, border=12)
618
619 dlg.buttonpanel.Layout()
620 dlg.sizer0.SetSizeHints(dlg)
621 dlg.sizer0.Layout()
622
623 # This workaround is needed to update cell colours
624 grid.SelectAll()
625 grid.ClearSelection()
626
627 self.check_select_status()
628 dlg.ok.Disable()
629
630 dlg.Center()
631
632 def _get_path(self, row: int) -> str:
633 """Get the full path of the exception at the specified row.
634
635 Args:
636 row (int): The row index of the exception.
637
638 Returns:
639 str: The full path of the exception.
640 """
641 return os.path.join(
642 self.grid.GetCellValue(row, 3), self.grid.GetCellValue(row, 2)
643 )
644
645 def _update_exception(self, row: int) -> None:
646 """Update the exception at the specified row.
647
648 Args:
649 row (int): The row index of the exception to update.
650 """
651 path = self._get_path(row)
652 enabled = int(self.grid.GetCellValue(row, 0) or 0)
653 reset = int(self.grid.GetCellValue(row, 1) or 0)
654 self._exceptions[path.lower()] = enabled, reset, path
655
656 def cell_click_handler(self, event: wx.Event) -> None:
657 """Handle click events on the grid cells.
658
659 Args:
660 event (wx.Event): The event that triggered this handler.
661 """
662 if event.Col < 2:
663 value = "" if self.grid.GetCellValue(event.Row, event.Col) else "1"
664 self.grid.SetCellValue(event.Row, event.Col, value)
665 self._update_exception(event.Row)
666 self.ok.Enable()
667 event.Skip()
668
669 def cell_dclick_handler(self, event: wx.Event) -> None:
670 """Handle double-click events on the grid cells.
671
672 Args:
673 event (wx.Event): The event that triggered this handler.
674 """
675 if event.Col > 1:
676 self.browse_handler(event)
677 else:
678 self.cell_click_handler(event)
679
680 def cell_select_handler(self, event: wx.Event) -> None:
681 """Handle cell selection events."""
682 event.Skip()
683 wx.CallAfter(self.check_select_status)
684
685 def check_select_status(self) -> None:
686 """Check the selection status of the grid and enable/disable buttons."""
687 rows = self.grid.GetSelectedRows()
688 self.browse_btn.Enable(len(rows) == 1)
689 self.delete_btn.Enable(bool(rows))
690
691 def key_handler(self, event: wx.Event) -> None:
692 """Handle key events for the grid.
693
694 Args:
695 event (wx.Event): The event that triggered this handler.
696 """
697 dlg = self
698 if event.KeyCode == wx.WXK_SPACE:
699 dlg.cell_click_handler(
700 CustomGridCellEvent(
701 wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
702 dlg.grid,
703 dlg.grid.GridCursorRow,
704 dlg.grid.GridCursorCol,
705 )
706 )
707 elif event.KeyCode in (wx.WXK_BACK, wx.WXK_DELETE):
708 self.delete_handler(None)
709 else:
710 event.Skip()
711
712 def browse_handler(self, event: wx.Event) -> None:
713 """Browse for an executable to add or edit an exception.
714
715 Args:
716 event (wx.Event): The event that triggered this handler.
717 """
718 if event.GetId() == self.add_btn.Id:
719 lstr = "add"
720 default_dir = getenvu("ProgramW6432") or getenvu("ProgramFiles")
721 default_file = ""
722 else:
723 lstr = "browse"
724 row = self.grid.GetSelectedRows()[0]
725 default_dir = self.grid.GetCellValue(row, 3)
726 default_file = self.grid.GetCellValue(row, 2)
727 dlg = wx.FileDialog(
728 self,
729 lang.getstr(lstr),
730 defaultDir=default_dir,
731 defaultFile=default_file,
732 wildcard="*.exe",
733 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
734 )
735 dlg.Center(wx.BOTH)
736 result = dlg.ShowModal()
737 path = dlg.GetPath()
738 dlg.Destroy()
739 if result != wx.ID_OK:
740 return
741 if os.path.basename(path).lower() in self.known_apps:
742 show_result_dialog(
743 UnloggedError(
744 lang.getstr(
745 "profile_loader.exceptions.known_app.error",
746 os.path.basename(path),
747 )
748 )
749 )
750 return
751 if event.GetId() == self.add_btn.Id:
752 # If it already exists, select the respective row
753 if path.lower() in self._exceptions:
754 for row in range(self.grid.GetNumberRows()):
755 exception = os.path.join(
756 self.grid.GetCellValue(row, 3),
757 self.grid.GetCellValue(row, 2),
758 )
759 if exception.lower() == path.lower():
760 break
761 else:
762 # Add new row
763 self.grid.AppendRows(1)
764 row = self.grid.GetNumberRows() - 1
765 self.grid.SetCellValue(row, 0, "1")
766 self.grid.SetCellValue(row, 1, "")
767 self._exceptions[path.lower()] = 1, 0, path
768 self.grid.SetCellValue(row, 2, os.path.basename(path))
769 self.grid.SetCellValue(row, 3, os.path.dirname(path))
770 self._update_exception(row)
771 self.grid.SelectRow(row)
772 self.check_select_status()
773 self.grid.MakeCellVisible(row, 0)
774 self.ok.Enable()
775
776 def delete_handler(self, event: wx.Event) -> None:
777 """Delete selected exceptions.
778
779 Args:
780 event (wx.Event): The event that triggered this handler.
781 """
782 for row in sorted(self.grid.GetSelectedRows(), reverse=True):
783 del self._exceptions[self._get_path(row).lower()]
784 self.grid.DeleteRows(row)
785 self.check_select_status()
786 self.ok.Enable()
787
788
789 class ProfileAssociationsDialog(InfoDialog):
790 """Dialog to manage profile associations with displays.
791
792 Args:
793 pl (ProfileLoader): The profile loader instance to manage associations
794 for.
795 """
796
797 def __init__(self, pl: ProfileLoader) -> None:
798 self.monitors = []
799 self.pl = pl
800 self.profile_info = {}
801 self.profiles = []
802 self.current_user = False
803 self.display_identification_frames = {}
804 InfoDialog.__init__(
805 self,
806 None,
807 msg="",
808 title=lang.getstr("profile_associations"),
809 ok=lang.getstr("close"),
810 bitmap=get_icon(32, "display"),
811 show=False,
812 log=False,
813 wrap=128,
814 )
815 dlg = self
816 dlg.SetIcons(get_icon_bundle([256, 48, 32, 16], APPNAME + "-apply-profiles"))
817 dlg.message.Hide()
818 dlg.set_as_default_btn = wx.Button(
819 dlg.buttonpanel, -1, lang.getstr("set_as_default")
820 )
821 dlg.sizer2.Insert(1, dlg.set_as_default_btn, flag=wx.RIGHT, border=12)
822 dlg.set_as_default_btn.Bind(wx.EVT_BUTTON, dlg.set_as_default)
823 dlg.set_as_default_btn.Disable()
824 dlg.profile_info_btn = wx.Button(
825 dlg.buttonpanel, -1, lang.getstr("profile.info")
826 )
827 dlg.sizer2.Insert(
828 0,
829 dlg.profile_info_btn,
830 flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
831 border=12,
832 )
833 dlg.profile_info_btn.Bind(wx.EVT_BUTTON, dlg.show_profile_info)
834 dlg.profile_info_btn.Disable()
835 dlg.remove_btn = wx.Button(dlg.buttonpanel, -1, lang.getstr("remove"))
836 dlg.sizer2.Insert(0, dlg.remove_btn, flag=wx.RIGHT | wx.LEFT, border=12)
837 dlg.remove_btn.Bind(wx.EVT_BUTTON, dlg.remove_profile)
838 dlg.remove_btn.Disable()
839 dlg.add_btn = wx.Button(dlg.buttonpanel, -1, lang.getstr("add"))
840 dlg.sizer2.Insert(0, dlg.add_btn, flag=wx.LEFT, border=32 + 12)
841 dlg.add_btn.Bind(wx.EVT_BUTTON, dlg.add_profile)
842 dlg.add_btn.Disable()
843 scale = getcfg("app.dpi") / get_default_dpi()
844 scale = max(scale, 1)
845 dlg.display_ctrl = wx.Choice(dlg, -1)
846 dlg.display_ctrl.Bind(wx.EVT_CHOICE, dlg.update_profiles)
847 hsizer = wx.BoxSizer(wx.HORIZONTAL)
848 dlg.sizer3.Add(hsizer, 1, flag=wx.ALIGN_LEFT | wx.EXPAND | wx.TOP, border=5)
849 hsizer.Add(dlg.display_ctrl, 1, wx.ALIGN_CENTER_VERTICAL)
850 dlg.display_ctrl.Disable()
851 dlg.identify_btn = ThemedGenButton(dlg, -1, lang.getstr("displays.identify"))
852 dlg.identify_btn.MinSize = -1, dlg.display_ctrl.Size[1] + 2
853 dlg.identify_btn.Bind(wx.EVT_BUTTON, dlg.identify_displays)
854 hsizer.Add(dlg.identify_btn, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=8)
855 dlg.identify_btn.Disable()
856 if sys.getwindowsversion() >= (6,):
857 hsizer = wx.BoxSizer(wx.HORIZONTAL)
858 dlg.sizer3.Add(hsizer, flag=wx.ALIGN_LEFT | wx.EXPAND)
859 dlg.use_my_settings_cb = wx.CheckBox(
860 dlg, -1, lang.getstr("profile_associations.use_my_settings")
861 )
862 dlg.use_my_settings_cb.Bind(wx.EVT_CHECKBOX, self.use_my_settings)
863 hsizer.Add(
864 dlg.use_my_settings_cb,
865 flag=wx.TOP | wx.BOTTOM | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
866 border=12,
867 )
868 self.use_my_settings_cb.Disable()
869 dlg.warn_bmp = wx.StaticBitmap(dlg, -1, get_icon(16, "dialog-warning"))
870 dlg.warning = wx.StaticText(
871 dlg,
872 -1,
873 lang.getstr("profile_associations.changing_system_defaults.warning"),
874 )
875 warnsizer = wx.BoxSizer(wx.HORIZONTAL)
876 hsizer.Add(warnsizer, 0, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=12)
877 warnsizer.Add(dlg.warn_bmp, 0, wx.ALIGN_CENTER_VERTICAL)
878 warnsizer.Add(dlg.warning, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=4)
879 self.warn_bmp.Hide()
880 self.warning.Hide()
881 else:
882 dlg.sizer3.Add((1, 12))
883 list_panel = wx.Panel(dlg, -1)
884 list_panel.BackgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
885 list_panel.Sizer = wx.BoxSizer(wx.HORIZONTAL)
886 hscroll = wx.SystemSettings_GetMetric(wx.SYS_HSCROLL_Y)
887 numrows = 10
888 list_ctrl = wx.ListCtrl(
889 list_panel,
890 -1,
891 size=(640 * scale, (20 * numrows + 25 + hscroll) * scale),
892 style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.BORDER_THEME,
893 name="displays2profiles",
894 )
895 list_panel.Sizer.Add(list_ctrl, 1, flag=wx.ALL, border=1)
896 list_ctrl.InsertColumn(0, lang.getstr("description"))
897 list_ctrl.InsertColumn(1, lang.getstr("filename"))
898 list_ctrl.SetColumnWidth(0, int(430 * scale))
899 list_ctrl.SetColumnWidth(1, int(210 * scale))
900 list_ctrl.Bind(
901 wx.EVT_LIST_ITEM_SELECTED,
902 lambda e: (
903 dlg.remove_btn.Enable(),
904 dlg.set_as_default_btn.Enable(e.GetIndex() > 0),
905 dlg.profile_info_btn.Enable(),
906 ),
907 )
908 list_ctrl.Bind(
909 wx.EVT_LIST_ITEM_DESELECTED,
910 lambda e: (
911 dlg.remove_btn.Disable(),
912 dlg.set_as_default_btn.Disable(),
913 dlg.profile_info_btn.Disable(),
914 ),
915 )
916 list_ctrl.Bind(wx.EVT_LIST_ITEM_ACTIVATED, dlg.set_as_default)
917 dlg.sizer3.Add(list_panel, flag=wx.BOTTOM | wx.ALIGN_LEFT, border=12)
918 dlg.profiles_ctrl = list_ctrl
919 dlg.fix_profile_associations_cb = wx.CheckBox(
920 dlg, -1, lang.getstr("profile_loader.fix_profile_associations")
921 )
922 dlg.fix_profile_associations_cb.Bind(
923 wx.EVT_CHECKBOX, self.toggle_fix_profile_associations
924 )
925 dlg.sizer3.Add(dlg.fix_profile_associations_cb, flag=wx.ALIGN_LEFT)
926 dlg.disable_btns()
927 dlg.update()
928 dlg.sizer0.SetSizeHints(dlg)
929 dlg.sizer0.Layout()
930 dlg.ok.SetDefault()
931 dlg.update_profiles_timer = wx.Timer(dlg)
932 dlg.Bind(wx.EVT_TIMER, dlg.update_profiles, dlg.update_profiles_timer)
933 dlg.update_profiles_timer.Start(1000)
934
935 def OnClose(self, event: wx.Event) -> None: # noqa: N802
936 """Handle the close event for the dialog.
937
938 Args:
939 event (wx.Event): The event that triggered this method.
940 """
941 InfoDialog.OnClose(self, event)
942
943 def EndModal(self, retCode: int) -> None: # noqa: N802, N803
944 """End the modal dialog and stop the update timer.
945
946 Args:
947 retCode (int): The return code for the dialog.
948 """
949 self.update_profiles_timer.Stop()
950 wx.Dialog.EndModal(self, retCode)
951
952 def add_profile(self, event: wx.Event) -> None:
953 """Add a profile to the selected display.
954
955 Args:
956 event (wx.Event): The event that triggered this method.
957 """
958 if self.add_btn.GetAuthNeeded():
959 if self.pl.elevate():
960 self.EndModal(wx.ID_CANCEL)
961 return
962 dlg = ConfirmDialog(
963 self,
964 msg=lang.getstr("profile.choose"),
965 title=lang.getstr("add"),
966 ok=lang.getstr("ok"),
967 cancel=lang.getstr("cancel"),
968 bitmap=get_icon(32, APPNAME + "-profile-info"),
969 wrap=128,
970 )
971 dlg.SetIcons(get_icon_bundle([256, 48, 32, 16], APPNAME + "-apply-profiles"))
972 scale = getcfg("app.dpi") / get_default_dpi()
973 scale = max(scale, 1)
974 list_panel = wx.Panel(dlg, -1)
975 list_panel.BackgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
976 list_panel.Sizer = wx.BoxSizer(wx.HORIZONTAL)
977 hscroll = wx.SystemSettings_GetMetric(wx.SYS_HSCROLL_Y)
978 numrows = 15
979 list_ctrl = wx.ListCtrl(
980 list_panel,
981 -1,
982 size=(640 * scale, (20 * numrows + 25 + hscroll) * scale),
983 style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.BORDER_THEME,
984 name="displays2profiles",
985 )
986 list_panel.Sizer.Add(list_ctrl, 1, flag=wx.ALL, border=1)
987 list_ctrl.InsertColumn(0, lang.getstr("description"))
988 list_ctrl.InsertColumn(1, lang.getstr("filename"))
989 list_ctrl.SetColumnWidth(0, int(430 * scale))
990 list_ctrl.SetColumnWidth(1, int(210 * scale))
991 list_ctrl.Bind(wx.EVT_LIST_ITEM_SELECTED, lambda e: dlg.ok.Enable())
992 list_ctrl.Bind(wx.EVT_LIST_ITEM_DESELECTED, lambda e: dlg.ok.Disable())
993 list_ctrl.Bind(wx.EVT_LIST_ITEM_ACTIVATED, lambda e: dlg.EndModal(wx.ID_OK))
994 profiles = []
995 for pth in safe_glob(os.path.join(ICCPROFILES[0], "*.ic[cm]")) + safe_glob(
996 os.path.join(ICCPROFILES[0], "*.cdmp")
997 ):
998 try:
999 profile = ICCProfile(pth)
1000 except ICCProfileInvalidError as exception:
1001 print(f"{pth}:", exception)
1002 traceback.print_exc()
1003 continue
1004 except OSError as exception:
1005 print(exception)
1006 continue
1007 if profile.profileClass == b"mntr":
1008 profiles.append((profile.getDescription(), os.path.basename(pth)))
1009 natsort_key = natsort_key_factory()
1010 profiles.sort(key=lambda item: natsort_key(item[0]))
1011 for i, (desc, profile) in enumerate(profiles):
1012 pindex = list_ctrl.InsertStringItem(i, "")
1013 list_ctrl.SetStringItem(pindex, 0, desc)
1014 list_ctrl.SetStringItem(pindex, 1, profile)
1015 dlg.profiles_ctrl = list_ctrl
1016 dlg.sizer3.Add(list_panel, 1, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
1017 dlg.sizer0.SetSizeHints(dlg)
1018 dlg.sizer0.Layout()
1019 dlg.ok.SetDefault()
1020 dlg.ok.Disable()
1021 dlg.Center()
1022 result = dlg.ShowModal()
1023 if result == wx.ID_OK:
1024 pindex = list_ctrl.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
1025 if pindex > -1:
1026 self.set_profile(profiles[pindex][1])
1027 else:
1028 wx.Bell()
1029 dlg.Destroy()
1030
1031 def identify_displays(self, event: wx.Event) -> None:
1032 """Identify the displays by showing a frame with their description.
1033
1034 Args:
1035 event (wx.Event): The event that triggered this method.
1036 """
1037 for display, frame in list(self.display_identification_frames.items()):
1038 if not frame:
1039 self.display_identification_frames.pop(display)
1040 for display, _edid, moninfo, _device in self.monitors:
1041 frame = self.display_identification_frames.get(display)
1042 if frame:
1043 frame.close_timer.Stop()
1044 frame.close_timer.Start(3000)
1045 else:
1046 m_left, m_top, m_right, m_bottom = moninfo["Monitor"]
1047 m_width = abs(m_right - m_left)
1048 m_height = abs(m_bottom - m_top)
1049 pos = wx.Point(int(m_left + m_width / 4), int(m_top + m_height / 4))
1050 size = wx.Size(int(m_width / 2), int(m_height / 2))
1051 display_desc = display.replace(
1052 "[PRIMARY]", lang.getstr("display.primary")
1053 )
1054 frame = DisplayIdentificationFrame(display_desc, pos, size)
1055 self.display_identification_frames[display] = frame
1056
1057 def show_profile_info(self, event: wx.Event) -> None:
1058 """Show the profile information for the selected profile.
1059
1060 Args:
1061 event (wx.Event): The event that triggered this method.
1062 """
1063 pindex = self.profiles_ctrl.GetNextItem(
1064 -1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED
1065 )
1066 if pindex < 0:
1067 wx.Bell()
1068 return
1069 try:
1070 profile = ICCProfile(self.profiles[pindex])
1071 except (OSError, ICCProfileInvalidError):
1072 show_result_dialog(
1073 Error(lang.getstr("profile.invalid") + "\n" + self.profiles[pindex]),
1074 self,
1075 )
1076 return
1077 id_ = profile.calculate_id(False) if profile.ID == "\0" * 16 else profile.ID
1078 if id_ not in self.profile_info:
1079 # Create profile info window and store in hash table
1080 from DisplayCAL.wx_profile_info import ProfileInfoFrame
1081
1082 self.profile_info[id_] = ProfileInfoFrame(None, -1)
1083 self.profile_info[id_].Unbind(wx.EVT_CLOSE)
1084 self.profile_info[id_].Bind(wx.EVT_CLOSE, self.close_profile_info)
1085 if (
1086 not self.profile_info[id_].profile
1087 or self.profile_info[id_].profile.calculate_id(False) != id_
1088 ):
1089 # Load profile if info window has no profile or ID is different
1090 self.profile_info[id_].profileID = id_
1091 self.profile_info[id_].LoadProfile(profile)
1092 if self.profile_info[id_].IsIconized():
1093 self.profile_info[id_].Restore()
1094 else:
1095 self.profile_info[id_].Show()
1096 self.profile_info[id_].Raise()
1097 argyll_dir = getcfg("argyll.dir")
1098 if getcfg("argyll.dir") != argyll_dir:
1099 if self.pl.frame:
1100 result = self.pl.frame.send_command(
1101 None, 'set-argyll-dir "{}"'.format(getcfg("argyll.dir"))
1102 )
1103 else:
1104 result = "ok"
1105 if result == "ok":
1106 self.pl.writecfg()
1107
1108 def close_profile_info(self, event: wx.Event) -> None:
1109 """Close the profile info window and remove it from the hash table.
1110
1111 Args:
1112 event (wx.Event): The event that triggered this method.
1113 """
1114 # Remove the frame from the hash table
1115 if self:
1116 self.profile_info.pop(event.GetEventObject().profileID)
1117 # Closes the window
1118 event.Skip()
1119
1120 def disable_btns(self) -> None:
1121 """Disable buttons that are not applicable."""
1122 self.remove_btn.Disable()
1123 self.profile_info_btn.Disable()
1124 self.set_as_default_btn.Disable()
1125
1126 def remove_profile(self, event: wx.Event) -> None:
1127 """Remove the selected profile from the monitor.
1128
1129 Args:
1130 event (wx.Event): The event that triggered this method.
1131 """
1132 if self.remove_btn.GetAuthNeeded():
1133 if self.pl.elevate():
1134 self.EndModal(wx.ID_CANCEL)
1135 return
1136 pindex = self.profiles_ctrl.GetNextItem(
1137 -1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED
1138 )
1139 if pindex > -1:
1140 self.set_profile(self.profiles[pindex], True)
1141 else:
1142 wx.Bell()
1143
1144 def set_as_default(self, event: wx.Event) -> None:
1145 """Set the selected profile as the default for the monitor.
1146
1147 Args:
1148 event (wx.Event): The event that triggered this method.
1149 """
1150 if self.set_as_default_btn.GetAuthNeeded():
1151 if self.pl.elevate():
1152 self.EndModal(wx.ID_CANCEL)
1153 return
1154 pindex = self.profiles_ctrl.GetNextItem(
1155 -1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED
1156 )
1157 if pindex > -1:
1158 self.set_profile(self.profiles[pindex])
1159 else:
1160 wx.Bell()
1161
1162 def set_profile(self, profile: str, unset: bool = False) -> None:
1163 """Set the display profile for the selected monitor.
1164
1165 Args:
1166 profile (str): The name of the profile to set.
1167 unset (bool, optional): Whether to unset the profile instead of
1168 setting it. Defaults to False.
1169 """
1170 fn = unset_display_profile if unset else set_display_profile
1171 self._update_configuration(fn, profile)
1172
1173 def _update_configuration(self, fn: Callable, arg0: object) -> None:
1174 """Update the display profile configuration.
1175
1176 Args:
1177 fn (Callable): The function to call for updating the profile.
1178 arg0 (object): The argument to pass to the function.
1179 """
1180 dindex = self.display_ctrl.GetSelection()
1181 display, edid, moninfo, device = self.monitors[dindex]
1182 device0 = get_first_display_device(moninfo["Device"])
1183 if device0 and device:
1184 self._update_device(fn, arg0, device.DeviceKey)
1185 if (
1186 getcfg("profile_loader.fix_profile_associations")
1187 and device.DeviceKey != device0.DeviceKey
1188 and self.pl._can_fix_profile_associations()
1189 ):
1190 self._update_device(fn, arg0, device0.DeviceKey)
1191 self.update_profiles(True, monitor=self.monitors[dindex], next_=True)
1192 else:
1193 wx.Bell()
1194
1195 def _update_device(
1196 self,
1197 fn: Callable,
1198 arg0: Any, # noqa: ANN401
1199 devicekey: str,
1200 show_error: bool = True,
1201 ) -> None:
1202 """Update the display profile for a specific device.
1203
1204 Args:
1205 fn (callable): The function to call for updating the profile.
1206 arg0 (Any): The argument to pass to the function.
1207 devicekey (str): The device key for the display.
1208 show_error (bool): Whether to show an error dialog on failure.
1209 """
1210 if (
1211 not USE_REGISTRY
1212 and fn is enable_per_user_profiles
1213 and not per_user_profiles_isenabled(devicekey=devicekey)
1214 ):
1215 # We need to re-associate per-user profiles to the
1216 # display, otherwise the associations will be lost
1217 # after enabling per-user if a system default profile
1218 # was set (but only if we call WcsSetUsePerUserProfiles
1219 # instead of setting the underlying registry value directly)
1220 monkey = devicekey.split("\\")[-2:]
1221 profiles = _winreg_get_display_profiles(monkey, True)
1222 else:
1223 profiles = []
1224 try:
1225 fn(arg0, devicekey=devicekey)
1226 except Exception as exception:
1227 print(
1228 f"{fn.__name__}({arg0!r}, devicekey={devicekey!r}):",
1229 exception,
1230 )
1231 if show_error:
1232 wx.CallAfter(show_result_dialog, UnloggedError(str(exception)), self)
1233 for profile_name in profiles:
1234 set_display_profile(profile_name, devicekey=devicekey)
1235
1236 def toggle_fix_profile_associations(self, event: wx.Event) -> None:
1237 """Toggle the fix profile associations checkbox.
1238
1239 Args:
1240 event (wx.Event): The event that triggered this method.
1241 """
1242 self.fix_profile_associations_cb.Value = (
1243 self.pl._toggle_fix_profile_associations(event, self)
1244 )
1245 if self.fix_profile_associations_cb.Value == event.IsChecked():
1246 self.update_profiles(True)
1247
1248 def update(self, event: None | wx.Event = None) -> None:
1249 """Update the list of monitors and their associated profiles.
1250
1251 Args:
1252 event (None | wx.Event, optional): The event that triggered this
1253 method.
1254 """
1255 self.monitors = list(self.pl.monitors)
1256 self.display_ctrl.SetItems(
1257 [
1258 entry[0].replace("[PRIMARY]", lang.getstr("display.primary"))
1259 for entry in self.monitors
1260 ]
1261 )
1262 if self.monitors:
1263 self.display_ctrl.SetSelection(0)
1264 self.display_ctrl.Enable(bool(self.monitors))
1265 self.identify_btn.Enable(bool(self.monitors))
1266 self.add_btn.Enable(bool(self.monitors))
1267 fix = self.pl._can_fix_profile_associations()
1268 self.fix_profile_associations_cb.Enable(fix)
1269 if fix:
1270 self.fix_profile_associations_cb.SetValue(
1271 bool(getcfg("profile_loader.fix_profile_associations"))
1272 )
1273 self.update_profiles(event)
1274 if event and not self.IsActive():
1275 self.RequestUserAttention()
1276
1277 def update_profiles(
1278 self,
1279 event: None | wx.Event = None,
1280 monitor: None | tuple[int, dict, dict, Device] = None,
1281 next_: bool = False,
1282 ) -> None:
1283 """Update the profile associations for the selected monitor.
1284
1285 Args:
1286 event (None | wx.Event): The event that triggered this method.
1287 monitor (None | tuple[int, dict, dict, Device], optional): A tuple
1288 containing display (int), edid (dict), moninfo (dict), and
1289 device (Device).
1290 next_ (bool): Whether to proceed to the next step in the update.
1291 """
1292 if not monitor:
1293 dindex = self.display_ctrl.GetSelection()
1294 if -1 < dindex < len(self.monitors):
1295 monitor = self.monitors[dindex]
1296 else:
1297 if event and not isinstance(event, wx.TimerEvent):
1298 wx.Bell()
1299 return
1300 _display, _edid, _moninfo, device = monitor
1301 if not device:
1302 if event and not isinstance(event, wx.TimerEvent):
1303 wx.Bell()
1304 return
1305 if sys.getwindowsversion() >= (6,):
1306 current_user = per_user_profiles_isenabled(devicekey=device.DeviceKey)
1307 scope_changed = current_user != self.current_user
1308 if scope_changed:
1309 self.current_user = current_user
1310 self.use_my_settings_cb.SetValue(current_user)
1311 self.use_my_settings_cb.Enable()
1312 superuser = is_superuser()
1313 warn = not current_user and superuser
1314 update_layout = warn is not self.warning.IsShown()
1315 if update_layout:
1316 self.warn_bmp.Show(warn)
1317 self.warning.Show(warn)
1318 self.sizer3.Layout()
1319 auth_needed = not (current_user or superuser)
1320 update_layout = self.add_btn.GetAuthNeeded() is not auth_needed
1321 if update_layout:
1322 self.buttonpanel.Freeze()
1323 self.add_btn.SetAuthNeeded(auth_needed)
1324 self.remove_btn.SetAuthNeeded(auth_needed)
1325 self.set_as_default_btn.SetAuthNeeded(auth_needed)
1326 self.buttonpanel.Layout()
1327 self.buttonpanel.Thaw()
1328 else:
1329 current_user = False
1330 scope_changed = False
1331 monkey = device.DeviceKey.split("\\")[-2:]
1332 profiles = _winreg_get_display_profiles(monkey, current_user)
1333 profiles.reverse()
1334 profiles_changed = profiles != self.profiles
1335 if profiles_changed:
1336 self.profiles_ctrl.Freeze()
1337 self.profiles = profiles
1338 self.disable_btns()
1339 self.profiles_ctrl.DeleteAllItems()
1340 for i, profile in enumerate(self.profiles):
1341 pindex = self.profiles_ctrl.InsertStringItem(i, "")
1342 description = get_profile_desc(profile, False)
1343 if i == 0:
1344 # First profile is always default
1345 description += " ({})".format(lang.getstr("default"))
1346 self.profiles_ctrl.SetStringItem(pindex, 0, description)
1347 self.profiles_ctrl.SetStringItem(pindex, 1, profile)
1348 self.profiles_ctrl.Thaw()
1349 if scope_changed or (
1350 profiles_changed and (next_ or isinstance(event, wx.TimerEvent))
1351 ):
1352 wx.CallAfter(self._next)
1353
1354 def _next(self) -> None:
1355 locked = self.pl.lock.locked()
1356 if locked:
1357 print("ProfileAssociationsDialog: Waiting to acquire lock...")
1358 with self.pl.lock:
1359 if locked:
1360 print("ProfileAssociationsDialog: Acquired lock")
1361 self.pl._next = True
1362 if locked:
1363 print("ProfileAssociationsDialog: Releasing lock")
1364
1365 def use_my_settings(self, event: wx.Event) -> None:
1366 """Enable or disable per-user profiles.
1367
1368 Args:
1369 event (wx.Event): The event that triggered this method.
1370 """
1371 self._update_configuration(enable_per_user_profiles, event.IsChecked())
1372
1373
1374 class PLFrame(BaseFrame):
1375 """Main frame class for the profile loader.
1376
1377 Args:
1378 pl (ProfileLoader): The profile loader instance.
1379 """
1380
1381 def __init__(self, pl: ProfileLoader) -> None:
1382 BaseFrame.__init__(self, None)
1383 self.pl = pl
1384 self.Bind(wx.EVT_CLOSE, pl.exit)
1385 self.Bind(wx.EVT_DISPLAY_CHANGED, self.pl._display_changed)
1386
1387 def get_commands(self) -> list[str]:
1388 """Get the list of supported commands.
1389
1390 Returns:
1391 list[str]: The list of supported commands.
1392 """
1393 return [
1394 *self.get_common_commands(),
1395 "apply-profiles [force | display-changed]",
1396 "notify <message> [silent] [sticky]",
1397 "reset-vcgt [force]",
1398 "setlanguage <languagecode>",
1399 ]
1400
1401 def process_data(self, data: list) -> str:
1402 """Process incoming command data.
1403
1404 Args:
1405 data (list): The command data to process.
1406 """
1407 if data[0] in ("apply-profiles", "reset-vcgt") and (
1408 len(data) == 1
1409 or (len(data) == 2 and data[1] in ("force", "display-changed"))
1410 ):
1411 if (
1412 not ("--force" in sys.argv[1:] or len(data) == 2)
1413 and calibration_management_isenabled()
1414 ):
1415 return lang.getstr("calibration.load.handled_by_os")
1416 if (
1417 len(data) == 1 and self.pl._is_displaycal_running()
1418 ) or self.pl._is_other_running(False):
1419 return "forbidden"
1420 if data[-1] == "display-changed":
1421 if self.pl.lock.locked():
1422 print("PLFrame.process_data: Waiting to acquire lock...")
1423 with self.pl.lock:
1424 print("PLFrame.process_data: Acquired lock")
1425 if self.pl._has_display_changed:
1426 # Normally calibration loading is disabled while
1427 # DisplayCAL is running. Override this when the
1428 # display has changed
1429 self.pl._manual_restore = getcfg("profile.load_on_login") and 2
1430 print("PLFrame.process_data: Releasing lock")
1431 elif data[0] == "reset-vcgt":
1432 self.pl._set_reset_gamma_ramps(None, len(data))
1433 else:
1434 self.pl._set_manual_restore(None, len(data))
1435 return "ok"
1436 if data[0] == "notify" and (
1437 len(data) == 2
1438 or (len(data) == 3 and data[2] in ("silent", "sticky"))
1439 or (len(data) == 4 and "silent" in data[2:] and "sticky" in data[2:])
1440 ):
1441 self.pl.notify(
1442 [data[1]],
1443 [],
1444 sticky="sticky" in data[2:],
1445 show_notification="silent" not in data[2:],
1446 )
1447 return "ok"
1448 if data[0] == "setlanguage" and len(data) == 2:
1449 config.setcfg("lang", data[1])
1450 wx.CallAfter(self.pl.taskbar_icon.set_visual_state)
1451 self.pl.writecfg()
1452 return "ok"
1453 return "invalid"
1454
1455
1456 class TaskBarIcon(SysTrayIcon):
1457 """System tray icon class for the profile loader.
1458
1459 Args:
1460 pl (ProfileLoader): The profile loader instance.
1461 """
1462
1463 def __init__(self, pl: ProfileLoader) -> None:
1464 super().__init__()
1465 self.pl = pl
1466 self.balloon_text = None
1467 self.flags = 0
1468 self.set_icons()
1469 self._active_icon_reset = config.get_bitmap_as_icon(16, "apply-profiles-reset")
1470 self._error_icon = config.get_bitmap_as_icon(16, "apply-profiles-error")
1471 self._animate = False
1472 self.set_visual_state(True)
1473 self.Bind(wx.EVT_TASKBAR_LEFT_UP, self.on_left_up)
1474 self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.on_left_dclick)
1475 self._dclick = False
1476 self._show_notification_later = None
1477
1478 @property
1479 def _active_icon(self) -> wx.Icon:
1480 """Get the active icon for the system tray.
1481
1482 Returns:
1483 wx.Icon: The active icon.
1484 """
1485 debug_print(f"[DEBUG] _active_icon[{self._icon_index:d}]")
1486 return self._active_icons[self._icon_index]
1487
1488 @_active_icon.setter
1489 def _active_icon(self, icon: wx.Icon) -> None:
1490 """Set the active icon for the system tray.
1491
1492 Args:
1493 icon (wx.Icon): The icon to set as active.
1494 """
1495 self._active_icons.append(icon)
1496
1497 def CreatePopupMenu(self) -> wx.Menu: # noqa: N802
1498 """Create the popup menu for the system tray icon.
1499
1500 Returns:
1501 wx.Menu: The created popup menu.
1502 """
1503 # Popup menu appears on right-click
1504 menu = Menu()
1505
1506 if self.pl._is_displaycal_running() or self.pl._is_other_running(False):
1507 restore_auto = restore_manual = reset = None
1508 else:
1509 restore_manual = self.pl._set_manual_restore
1510 if "--force" in sys.argv[1:] or calibration_management_isenabled():
1511 restore_auto = None
1512 else:
1513 restore_auto = self.set_auto_restore
1514 reset = self.pl._set_reset_gamma_ramps
1515 if "--force" not in sys.argv[1:] and calibration_management_isenabled():
1516 restore_auto_kind = apply_kind = wx.ITEM_NORMAL
1517 else:
1518 if config.getcfg("profile.load_on_login"):
1519 apply_kind = wx.ITEM_RADIO
1520 else:
1521 apply_kind = wx.ITEM_NORMAL
1522 restore_auto_kind = wx.ITEM_CHECK
1523
1524 fix = self.pl._can_fix_profile_associations()
1525 if fix:
1526 fix = self.pl._toggle_fix_profile_associations
1527
1528 menu_items = [
1529 (
1530 "calibration.load_from_display_profiles",
1531 restore_manual,
1532 apply_kind,
1533 "reset_gamma_ramps",
1534 lambda v: not v,
1535 ),
1536 (
1537 "calibration.reset",
1538 reset,
1539 apply_kind,
1540 "reset_gamma_ramps",
1541 None,
1542 ),
1543 ("-", None, False, None, None),
1544 (
1545 "calibration.preserve",
1546 restore_auto,
1547 restore_auto_kind,
1548 "profile.load_on_login",
1549 None,
1550 ),
1551 (
1552 "profile_loader.fix_profile_associations",
1553 fix,
1554 wx.ITEM_CHECK,
1555 "profile_loader.fix_profile_associations",
1556 None,
1557 ),
1558 (
1559 "show_notifications",
1560 lambda event: setcfg(
1561 "profile_loader.show_notifications",
1562 int(event.IsChecked()),
1563 ),
1564 wx.ITEM_CHECK,
1565 "profile_loader.show_notifications",
1566 None,
1567 ),
1568 (
1569 "tray_icon_animation",
1570 self.set_animation,
1571 wx.ITEM_CHECK,
1572 "profile_loader.tray_icon_animation_quality",
1573 None,
1574 ),
1575 ("-", None, False, None, None),
1576 (
1577 "bitdepth",
1578 (
1579 ("8", lambda event: self.set_bitdepth(event, 8)),
1580 ("10", lambda event: self.set_bitdepth(event, 10)),
1581 ("12", lambda event: self.set_bitdepth(event, 12)),
1582 ("14", lambda event: self.set_bitdepth(event, 14)),
1583 ("16", lambda event: self.set_bitdepth(event, 16)),
1584 ),
1585 wx.ITEM_CHECK,
1586 "profile_loader.quantize_bits",
1587 lambda v: {8: 0, 10: 1, 12: 2, 14: 3, 16: 4}[v],
1588 ),
1589 ("-", None, False, None, None),
1590 ("exceptions", self.set_exceptions, wx.ITEM_NORMAL, None, None),
1591 ("-", None, False, None, None),
1592 ]
1593 menu_items.append(
1594 (
1595 "profile_associations",
1596 self.pl._set_profile_associations,
1597 wx.ITEM_NORMAL,
1598 None,
1599 None,
1600 )
1601 )
1602 if sys.getwindowsversion() >= (6,):
1603 menu_items.append(
1604 (
1605 "mswin.open_display_settings",
1606 self.open_display_settings,
1607 wx.ITEM_NORMAL,
1608 None,
1609 None,
1610 )
1611 )
1612 menu_items.append(("-", None, False, None, None))
1613 menu_items.append(("menuitem.quit", self.pl.exit, wx.ITEM_NORMAL, None, None))
1614 for label, method, kind, option, oxform in menu_items:
1615 if label == "-":
1616 menu.AppendSeparator()
1617 else:
1618 label = lang.getstr(label)
1619 if option == "profile.load_on_login":
1620 lstr = lang.getstr("profile.load_on_login")
1621 if lang.getcode() != "de":
1622 label = label[0].lower() + label[1:]
1623 label = lstr + " && " + label
1624 item = MenuItem(menu, -1, label, kind=kind)
1625 if not oxform:
1626 oxform = bool
1627 if not method:
1628 item.Enable(False)
1629 elif isinstance(method, tuple):
1630 submenu = Menu()
1631 for i, (sublabel, submethod) in enumerate(method):
1632 subitem = MenuItem(
1633 submenu, -1, lang.getstr(sublabel), kind=kind
1634 )
1635 if oxform(getcfg(option)) == i:
1636 subitem.Check(True)
1637 submenu.AppendItem(subitem)
1638 submenu.Bind(wx.EVT_MENU, submethod, id=subitem.Id)
1639 menu.AppendSubMenu(submenu, label)
1640 continue
1641 else:
1642 menu.Bind(wx.EVT_MENU, method, id=item.Id)
1643 menu.AppendItem(item)
1644 if kind != wx.ITEM_NORMAL:
1645 if option == "profile.load_on_login" and "--force" in sys.argv[1:]:
1646 item.Check(True)
1647 else:
1648 if option == "reset_gamma_ramps":
1649 value = self.pl._reset_gamma_ramps
1650 else:
1651 value = config.getcfg(option)
1652 item.Check(method and oxform(value))
1653
1654 return menu
1655
1656 def PopupMenu(self, menu: wx.Menu) -> None: # noqa: N802
1657 """Show the popup menu.
1658
1659 Args:
1660 menu (wx.Menu): The menu to display.
1661 """
1662 if not self.check_user_attention():
1663 if self.menu and self.menu is not menu:
1664 self.menu.Destroy()
1665 SysTrayIcon.PopupMenu(self, menu)
1666
1667 def animate(
1668 self,
1669 enumerate_windows_and_processes: bool = False,
1670 idle: bool = False,
1671 ) -> None:
1672 """Animate the taskbar icon.
1673
1674 Args:
1675 enumerate_windows_and_processes (bool): Whether to
1676 enumerate windows and processes.
1677 idle (bool): Whether the system is idle.
1678 """
1679 if not self.pl.monitoring:
1680 return
1681 debug_print(
1682 "[DEBUG] animate(enumerate_windows_and_processes="
1683 f"{enumerate_windows_and_processes}, idle={idle})"
1684 )
1685 if self._icon_index < len(self._active_icons) - 1:
1686 self._animate = True
1687 self._icon_index += 1
1688 else:
1689 self._animate = False
1690 self._icon_index = 0
1691 self.set_visual_state(enumerate_windows_and_processes, idle)
1692 if self._icon_index > 0:
1693 wx.CallLater(
1694 int(200 / len(self._active_icons)),
1695 lambda enumerate_windows_and_processes, idle: (
1696 self and self.animate(enumerate_windows_and_processes, idle)
1697 ),
1698 enumerate_windows_and_processes,
1699 idle,
1700 )
1701 debug_print("[DEBUG] /animate")
1702
1703 def get_icon(
1704 self,
1705 enumerate_windows_and_processes: bool = False,
1706 idle: bool = False,
1707 ) -> wx.Icon:
1708 """Get the appropriate icon based on the current state.
1709
1710 Args:
1711 enumerate_windows_and_processes (bool): Whether to
1712 enumerate windows and processes.
1713 idle (bool): Whether the system is idle.
1714
1715 Returns:
1716 wx.Icon: The appropriate icon.
1717 """
1718 debug_print(
1719 "[DEBUG] "
1720 "get_icon(enumerate_windows_and_processes="
1721 f"{enumerate_windows_and_processes}, idle={idle})"
1722 )
1723 if (
1724 self.pl._should_apply_profiles(
1725 enumerate_windows_and_processes, manual_override=None
1726 )
1727 or self._animate
1728 ):
1729 count = len(self.pl.monitors)
1730 if (
1731 len(
1732 [
1733 i_success
1734 for i_success in sorted(self.pl.setgammaramp_success.items())[
1735 : count or 1
1736 ]
1737 if not i_success[1]
1738 ]
1739 )
1740 != 0
1741 ):
1742 icon = self._error_icon
1743 elif self.pl._reset_gamma_ramps:
1744 icon = self._active_icon_reset
1745 else:
1746 icon = self._idle_icon if idle else self._active_icon
1747 else:
1748 icon = self._inactive_icon
1749 debug_print("[DEBUG] /get_icon")
1750 return icon
1751
1752 def on_left_up(self, event: wx.Event) -> None:
1753 """Handle left click event on the taskbar icon.
1754
1755 Args:
1756 event (wx.Event): The event that triggered this method.
1757 """
1758 if self._dclick:
1759 self._dclick = False
1760 return
1761 if not getattr(self, "_notification", None):
1762 # Make sure the displayed info is up-to-date
1763 locked = self.pl.lock.locked()
1764 if locked:
1765 print("TaskBarIcon.on_left_down: Waiting to acquire lock...")
1766 with self.pl.lock:
1767 if locked:
1768 print("TaskBarIcon.on_left_down: Acquired lock")
1769 self.pl._next = True
1770 if locked:
1771 print("TaskBarIcon.on_left_down: Releasing lock")
1772 time.sleep(0.11)
1773 locked = self.pl.lock.locked()
1774 if locked:
1775 print("TaskBarIcon.on_left_down: Waiting to acquire lock...")
1776 with self.pl.lock:
1777 if locked:
1778 print("TaskBarIcon.on_left_down: Acquired lock")
1779 if locked:
1780 print("TaskBarIcon.on_left_down: Releasing lock")
1781 self._show_notification_later = wx.CallLater(40, self.show_notification)
1782 else:
1783 self.show_notification(toggle=True)
1784
1785 def on_left_dclick(self, event: wx.Event) -> None:
1786 """Handle left double-click event on the taskbar icon.
1787
1788 Args:
1789 event (wx.Event): The event that triggered this method.
1790 """
1791 self._dclick = True
1792 if self.pl._is_other_running(False):
1793 return
1794 if self._show_notification_later and self._show_notification_later.IsRunning():
1795 self._show_notification_later.Stop()
1796 locked = self.pl.lock.locked()
1797 if locked:
1798 print("TaskBarIcon.on_left_dclick: Waiting to acquire lock...")
1799 with self.pl.lock:
1800 if locked:
1801 print("TaskBarIcon.on_left_dclick: Acquired lock")
1802 self.pl._manual_restore = True
1803 self.pl._next = True
1804 if locked:
1805 print("TaskBarIcon.on_left_dclick: Releasing lock")
1806
1807 def check_user_attention(self) -> None | wx.Dialog:
1808 """Check if any dialog needs user attention.
1809
1810 Returns:
1811 None | wx.Dialog: The dialog that needs attention, or
1812 None if none do.
1813 """
1814 dlgs = get_dialogs()
1815 if not dlgs:
1816 return None
1817 wx.Bell()
1818 for dlg in dlgs:
1819 # Need to request user attention for all open
1820 # dialogs because calling it only on the topmost
1821 # one does not guarantee taskbar flash
1822 dlg.RequestUserAttention()
1823 dlg.Raise()
1824 return dlg
1825
1826 def open_display_settings(self, event: wx.Event) -> None:
1827 """Open the Windows display settings.
1828
1829 Args:
1830 event (wx.Event): The event that triggered this method.
1831 """
1832 print("Menu command: Open display settings")
1833 try:
1834 sp.call(
1835 [ # noqa: S607
1836 "control",
1837 "/name",
1838 "Microsoft.Display",
1839 "/page",
1840 "Settings",
1841 ],
1842 close_fds=True,
1843 )
1844 except Exception as exception:
1845 wx.Bell()
1846 print(exception)
1847
1848 def set_animation(self, event: None | wx.Event = None) -> None:
1849 """Set the tray icon animation quality.
1850
1851 Args:
1852 event (wx.Event, optional): The event that triggered
1853 this method. Defaults to None.
1854 """
1855 q = getcfg("profile_loader.tray_icon_animation_quality")
1856 q = 0 if q else 2
1857 print("Menu command: Set tray icon animation", q)
1858 setcfg("profile_loader.tray_icon_animation_quality", q)
1859 self.set_icons()
1860
1861 def set_auto_restore(self, event: wx.Event) -> None:
1862 """Set the automatic profile loading on login.
1863
1864 Args:
1865 event (wx.Event): The event that triggered this method.
1866 """
1867 print("Menu command: Preserve calibration state", event.IsChecked())
1868 config.setcfg("profile.load_on_login", int(event.IsChecked()))
1869 self.pl.writecfg()
1870 if event.IsChecked():
1871 if self.pl.lock.locked():
1872 print("TaskBarIcon: Waiting to acquire lock...")
1873 with self.pl.lock:
1874 print("TaskBarIcon: Acquired lock")
1875 self.pl._manual_restore = True
1876 self.pl._next = True
1877 print("TaskBarIcon: Releasing lock")
1878 else:
1879 self.set_visual_state()
1880
1881 def set_bitdepth(
1882 self,
1883 event: None | wx.Event = None,
1884 bits: int = 16,
1885 ) -> None:
1886 """Set the quantization bit depth.
1887
1888 Args:
1889 event (wx.Event, optional): The event that triggered
1890 this method. Defaults to None.
1891 bits (int, optional): The bit depth to set. Defaults to
1892 16.
1893 """
1894 print("Menu command: Set quantization bitdepth", bits)
1895 setcfg("profile_loader.quantize_bits", bits)
1896 with self.pl.lock:
1897 self.pl._quantize = 2**bits - 1.0
1898 self.pl.ramps = {}
1899 self.pl._manual_restore = True
1900
1901 def set_exceptions(self, event: wx.Event) -> None:
1902 """Set application exceptions for profile loading.
1903
1904 Args:
1905 event (wx.Event): The event that triggered this method.
1906 """
1907 print("Menu command: Set exceptions")
1908 dlg = ProfileLoaderExceptionsDialog(self.pl._exceptions, self.pl._known_apps)
1909 result = dlg.ShowModal()
1910 if result == wx.ID_OK:
1911 exceptions = []
1912 for key in dlg._exceptions:
1913 enabled, reset, path = dlg._exceptions[key]
1914 exceptions.append(f"{enabled:d}:{reset:d}:{path}")
1915 print(
1916 f"Enabled={bool(enabled)}",
1917 "Action={}".format((reset and "Reset") or "Disable"),
1918 path,
1919 )
1920 if not exceptions:
1921 print("Clearing exceptions")
1922 config.setcfg("profile_loader.exceptions", ";".join(exceptions))
1923 self.pl._exceptions = dlg._exceptions
1924 self.pl._exception_names = {
1925 os.path.basename(key) for key in dlg._exceptions
1926 }
1927 self.pl.writecfg()
1928 else:
1929 print("Cancelled setting exceptions")
1930 dlg.Destroy()
1931
1932 def set_icons(self) -> None:
1933 """Set up the tray icons."""
1934 bitmap = config.get_icon(16, "apply-profiles-tray")
1935 image = bitmap.ConvertToImage()
1936 # Use Rec. 709 luma coefficients to convert to grayscale
1937 bitmap = image.ConvertToGreyscale(0.2126, 0.7152, 0.0722).ConvertToBitmap()
1938 icon = wx.IconFromBitmap(bitmap)
1939 self._active_icons = []
1940 self._icon_index = 0
1941 anim_quality = getcfg("profile_loader.tray_icon_animation_quality")
1942 if anim_quality == 2:
1943 numframes = 8
1944 elif anim_quality == 1:
1945 numframes = 4
1946 else:
1947 numframes = 1
1948 for i in range(numframes):
1949 if i:
1950 rad = i / float(numframes)
1951 bitmap = config.get_icon(16, f"apply-profiles-tray-{360 * rad:0.0f}")
1952 image = bitmap.ConvertToImage()
1953 image.RotateHue(-rad)
1954 self._active_icon = wx.IconFromBitmap(image.ConvertToBitmap())
1955 self._idle_icon = self._active_icon
1956 self._inactive_icon = icon
1957
1958 def set_visual_state(
1959 self,
1960 enumerate_windows_and_processes: bool = False,
1961 idle: bool = False,
1962 ) -> None:
1963 """Set the visual state of the taskbar icon.
1964
1965 Args:
1966 enumerate_windows_and_processes (bool): Whether to
1967 enumerate windows and processes.
1968 idle (bool): Whether the system is idle.
1969 """
1970 if not self.pl.monitoring:
1971 return
1972 debug_print(
1973 "[DEBUG] set_visual_state(enumerate_windows_and_processes="
1974 f"{enumerate_windows_and_processes}, idle={idle})"
1975 )
1976 self.SetIcon(
1977 self.get_icon(enumerate_windows_and_processes, idle),
1978 self.pl.get_title(),
1979 )
1980 debug_print("[DEBUG] /set_visual_state")
1981
1982 def show_notification(
1983 self,
1984 text: None | str = None,
1985 sticky: bool = False,
1986 show_notification: bool = True,
1987 flags: int = wx.ICON_INFORMATION,
1988 toggle: bool = False,
1989 ) -> None:
1990 """Show a notification balloon.
1991
1992 Args:
1993 text (str, optional): The text to display in the
1994 notification. If None, displays the last
1995 notification text. Defaults to None.
1996 sticky (bool, optional): Whether the notification
1997 should be sticky (i.e., remain until dismissed).
1998 Defaults to False.
1999 show_notification (bool, optional): Whether to actually
2000 show the notification. Defaults to True.
2001 flags (int, optional): The icon type for the
2002 notification. Defaults to wx.ICON_INFORMATION.
2003 toggle (bool, optional): Whether to toggle the
2004 notification (i.e., hide it if it's already shown).
2005 Defaults to False.
2006 """
2007 if wx.VERSION < (3,) or not self.pl._check_keep_running():
2008 wx.Bell()
2009 return
2010 debug_print(
2011 f"[DEBUG] show_notification(text={text!r}, "
2012 f"sticky={sticky}, show_notification={show_notification}, "
2013 f"flags={flags!r}, toggle={toggle})"
2014 )
2015 if (sticky or text) and show_notification:
2016 # Do not show notification unless enabled
2017 show_notification = getcfg("profile_loader.show_notifications")
2018 if sticky:
2019 self.balloon_text = text
2020 self.flags = flags
2021 elif text:
2022 self.balloon_text = None
2023 self.flags = 0
2024 else:
2025 text = self.balloon_text
2026 flags = self.flags or flags
2027 if not text:
2028 if "--force" not in sys.argv[1:] and calibration_management_isenabled():
2029 text = lang.getstr("calibration.load.handled_by_os") + "\n"
2030 else:
2031 text = ""
2032 if self.pl._component_name:
2033 text += lang.getstr("app.detected", self.pl._component_name) + "\n"
2034 text += lang.getstr("profile_loader.info", self.pl.reload_count)
2035 for i, (display, _edid, _moninfo, device) in enumerate(self.pl.monitors):
2036 devicekey = device.DeviceKey if device else None
2037 key = devicekey or str(i)
2038 (
2039 profile_key,
2040 mtime,
2041 desc,
2042 ) = self.pl.profile_associations.get(key, (False, 0, ""))
2043 if profile_key is False:
2044 desc = lang.getstr("unknown")
2045 elif not profile_key:
2046 desc = lang.getstr("unassigned").lower()
2047 if self.pl.setgammaramp_success.get(i) and self.pl._reset_gamma_ramps:
2048 desc = f"{lang.getstr('linear').capitalize()} / {desc}"
2049 elif not self.pl.setgammaramp_success.get(i) or not profile_key:
2050 desc = f"{lang.getstr('unknown')} / {desc}"
2051 display = display.replace("[PRIMARY]", lang.getstr("display.primary"))
2052 text += f"\n{display}: {desc}"
2053 if not show_notification:
2054 debug_print("[DEBUG] /show_notification")
2055 return
2056 if getattr(self, "_notification", None):
2057 self._notification.fade("out")
2058 if toggle:
2059 debug_print("[DEBUG] /show_notification")
2060 return
2061 bitmap = wx.BitmapFromIcon(self.get_icon())
2062 self._notification = TaskBarNotification(bitmap, self.pl.get_title(), text)
2063 debug_print("[DEBUG] /show_notification")
2064
2065
2066 class ProfileLoader:
2067 """Profile loader class for Windows."""
2068
2069 def __init__(self) -> None:
2070 from DisplayCAL.wx_windows import BaseApp, wx
2071
2072 if not wx.GetApp():
2073 app = BaseApp(0, clearSigInt=sys.platform != "win32")
2074 BaseApp.register_exitfunc(self.shutdown)
2075 else:
2076 app = None
2077 self.reload_count = 0
2078 self.lock = threading.Lock()
2079 self._is_other_running_lock = threading.Lock()
2080 self.monitoring = True
2081 self._active_displays = []
2082 self._display_changed_event = False
2083 self.monitors = [] # Display devices that can be represented as ON
2084 self.display_devices = {} # All display devices
2085 self.child_devices_count = {}
2086 self._current_display_key = -1
2087 self.numwindows = 0
2088 self.profile_associations = {}
2089 self.profiles = {}
2090 self.devices2profiles = {}
2091 self.ramps = {}
2092 self.linear_vcgt_values = ([], [], [])
2093 for j in range(3):
2094 for k in range(256):
2095 self.linear_vcgt_values[j].append([float(k), k * 257])
2096 self.setgammaramp_success = {}
2097 self.use_madhcnet = bool(config.getcfg("profile_loader.use_madhcnet"))
2098 self._has_display_changed = False
2099 self._last_exception_args = ()
2100 self._shutdown = False
2101 self._skip = "--skip" in sys.argv[1:]
2102 apply_profiles = bool(
2103 "--force" in sys.argv[1:] or config.getcfg("profile.load_on_login")
2104 )
2105 self._manual_restore = apply_profiles
2106 self._reset_gamma_ramps = bool(
2107 config.getcfg("profile_loader.reset_gamma_ramps")
2108 )
2109 self._known_apps = {
2110 known_app.lower()
2111 for known_app in config.DEFAULTS["profile_loader.known_apps"].split(";")
2112 + config.getcfg("profile_loader.known_apps").split(";")
2113 }
2114 self._known_window_classes = set(
2115 config.DEFAULTS["profile_loader.known_window_classes"].split(";")
2116 + config.getcfg("profile_loader.known_window_classes").split(";")
2117 )
2118 self._buggy_video_drivers = {
2119 buggy_video_driver.lower()
2120 for buggy_video_driver in config.getcfg(
2121 "profile_loader.buggy_video_drivers"
2122 ).split(";")
2123 }
2124 self._set_exceptions()
2125 self._madvr_instances = []
2126 self._madvr_reset_cal = {}
2127 self._quantize = 2 ** getcfg("profile_loader.quantize_bits") - 1.0
2128 self._timestamp = time.time()
2129 self._component_name = None
2130 self._app_detection_msg = None
2131 self._hwnds_pids = set()
2132 self._fixed_profile_associations = set()
2133 self.__other_component = None, None, 0
2134 self.__apply_profiles = None
2135 if (
2136 sys.platform == "win32"
2137 and "--force" not in sys.argv[1:]
2138 and sys.getwindowsversion() >= (6, 1)
2139 and calibration_management_isenabled()
2140 ):
2141 # Incase calibration loading is handled by Windows 7 and
2142 # isn't forced
2143 self._manual_restore = False
2144
2145 if (
2146 sys.platform != "win32"
2147 and apply_profiles
2148 and not self._skip
2149 and not self._is_displaycal_running()
2150 and not self._is_other_running(True)
2151 ):
2152 self.apply_profiles_and_warn_on_error()
2153
2154 if sys.platform == "win32":
2155 self.setup_taskbar_icon(app)
2156 elif (
2157 sys.platform == "darwin"
2158 and config.getcfg("profile.load_on_login")
2159 and "--force" not in sys.argv[1:]
2160 and not self._skip
2161 and config.getcfg("profile_loader.macos_reapply_watch")
2162 ):
2163 # macOS has no persistent calibration loader. Keep this process
2164 # running and re-load calibration if the OS clobbers the VideoLUT
2165 # (black screen bug, issue #694). A manual one-shot apply (--force)
2166 # is left as a one-shot and does not enter the watch loop.
2167 self._macos_watch()
2168
2169 def setup_taskbar_icon(self, app: None | BaseApp) -> None:
2170 """Set up the taskbar icon.
2171
2172 Args:
2173 app (None | BaseApp): The wx application instance.
2174 """
2175 # We create a TSR tray program only under Windows.
2176 # Linux has colord/Oyranos and respective session daemons should
2177 # take care of calibration loading
2178 self._pid = os.getpid()
2179 self._tid = threading.current_thread().ident
2180
2181 self.taskbar_icon = TaskBarIcon(self)
2182
2183 try:
2184 self.gdi32 = ctypes.windll.gdi32
2185 self.gdi32.GetDeviceGammaRamp.restype = ctypes.c_bool
2186 self.gdi32.SetDeviceGammaRamp.restype = ctypes.c_bool
2187 except Exception as exception:
2188 self.gdi32 = None
2189 print(exception)
2190 self.taskbar_icon.show_notification(str(exception))
2191
2192 if self.use_madhcnet:
2193 try:
2194 self.madvr = madvr.MadTPG()
2195 except Exception as exception:
2196 print(exception)
2197 if str(exception) != lang.getstr("madvr.not_found"):
2198 self.taskbar_icon.show_notification(str(exception))
2199 else:
2200 self.madvr.add_connection_callback(
2201 self._madvr_connection_callback, None, "madVR"
2202 )
2203 self.madvr.add_connection_callback(
2204 self._madvr_connection_callback, None, "madTPG"
2205 )
2206 self.madvr.listen()
2207 self.madvr.announce()
2208
2209 self.frame = PLFrame(self)
2210 self.frame.listen()
2211
2212 self._check_keep_running()
2213
2214 self._check_display_conf_thread = threading.Thread(
2215 target=self._check_display_conf_wrapper,
2216 name="DisplayConfigurationMonitoring",
2217 )
2218 self._check_display_conf_thread.start()
2219
2220 if app:
2221 app.TopWindow = self.frame
2222 app.MainLoop()
2223
2224 def apply_profiles(
2225 self, event: None | wx.Event = None, index: None | int = None
2226 ) -> None | list[str]:
2227 """Apply profiles to the displays.
2228
2229 Args:
2230 event (None | wx.Event, optional): The event that triggered the
2231 profile application.
2232 index (None | int, optional): The index of the display to apply the
2233 profile to. If None, applies to all displays.
2234
2235 Returns:
2236 None | list[str]: A list of errors if any, None otherwise.
2237 """
2238 from DisplayCAL.util_os import dlopen, which
2239 from DisplayCAL.worker import Worker, get_argyll_util
2240
2241 if sys.platform == "win32":
2242 self.lock.acquire()
2243
2244 worker = Worker()
2245
2246 errors = []
2247
2248 if sys.platform == "win32":
2249 separator = "-"
2250 else:
2251 separator = "="
2252 print(separator * 80)
2253 print(lang.getstr("calibration.loading_from_display_profile"))
2254
2255 # dispwin sets the _ICC_PROFILE(_n) root window atom, per-output xrandr
2256 # _ICC_PROFILE property (if xrandr is working) and loads the vcgt for the
2257 # requested screen (ucmm backend using color.jcnf), and has to be called
2258 # multiple times to setup multiple screens.
2259 #
2260 # If there is no profile configured in ucmm for the requested screen (or
2261 # ucmm support has been removed, like in the Argyll CMS versions shipped by
2262 # recent Fedora releases), it falls back to a possibly existing per-output
2263 # xrandr _ICC_PROFILE property (if xrandr is working) or _ICC_PROFILE(_n)
2264 # root window atom.
2265 dispwin = get_argyll_util("dispwin")
2266 if dispwin:
2267 # Always enumerate so that worker.displays is populated, even when
2268 # applying to a single display by index (e.g. from the macOS
2269 # VideoLUT watch). Without this the per-display loop below would
2270 # have nothing to iterate over for an indexed call.
2271 worker.enumerate_displays_and_ports(
2272 silent=True,
2273 check_lut_access=False,
2274 enumerate_ports=False,
2275 include_network_devices=False,
2276 )
2277 if index is None:
2278 self.monitors = []
2279 if sys.platform == "win32" and worker.displays:
2280 self._enumerate_monitors()
2281 elif index is None:
2282 errors.append(lang.getstr("argyll.util.not_found", "dispwin"))
2283
2284 if sys.platform != "win32":
2285 # gcm-apply sets the _ICC_PROFILE root window atom for the first screen,
2286 # per-output xrandr _ICC_PROFILE properties (if xrandr is working) and
2287 # loads the vcgt for all configured screens (device-profiles.conf)
2288 # NOTE: gcm-apply is no longer part of GNOME Color Manager since the
2289 # introduction of colord as it's no longer needed
2290 gcm_apply = which("gcm-apply")
2291 if gcm_apply:
2292 worker.exec_cmd(
2293 gcm_apply, capture_output=True, skip_scripts=True, silent=False
2294 )
2295
2296 # oyranos-monitor sets _ICC_PROFILE(_n) root window atoms (oyranos
2297 # db backend) and loads the vcgt for all configured screens when
2298 # xcalib is installed
2299 oyranos_monitor = which("oyranos-monitor")
2300 xcalib = which("xcalib")
2301
2302 argyll_use_colord = os.getenv("ARGYLL_USE_COLORD") and dlopen(
2303 "libcolordcompat.so"
2304 )
2305
2306 results = []
2307 for i, display in enumerate(
2308 [
2309 display.replace("[PRIMARY]", lang.getstr("display.primary"))
2310 for display in worker.displays
2311 ]
2312 ):
2313 if config.is_virtual_display(i) or (index is not None and i != index):
2314 continue
2315 # Load profile and set vcgt
2316 if sys.platform != "win32" and oyranos_monitor:
2317 display_conf_oy_compat = worker.check_display_conf_oy_compat(i + 1)
2318 if display_conf_oy_compat:
2319 worker.exec_cmd(
2320 oyranos_monitor,
2321 [
2322 "-x",
2323 str(worker.display_rects[i][0]),
2324 "-y",
2325 str(worker.display_rects[i][1]),
2326 ],
2327 capture_output=True,
2328 skip_scripts=True,
2329 silent=False,
2330 )
2331 if dispwin:
2332 if not argyll_use_colord:
2333 # Deal with colord ourself
2334 profile_arg = worker.get_dispwin_display_profile_argument(i)
2335 else:
2336 # Argyll deals with colord directly
2337 profile_arg = "-L"
2338 if (
2339 sys.platform == "win32"
2340 or not oyranos_monitor
2341 or not display_conf_oy_compat
2342 or not xcalib
2343 or profile_arg == "-L"
2344 ):
2345 # Only need to run dispwin if under Windows, or if nothing else
2346 # has already taken care of display profile and vcgt loading
2347 # (e.g. oyranos-monitor with xcalib, or colord)
2348 #
2349 # On macOS the OS (WindowServer) may intermittently clobber
2350 # the VideoLUT to all-black right after loading it, turning
2351 # the display black (issue #694). We therefore verify that
2352 # the calibration was actually loaded and re-try the load a
2353 # few times if it wasn't. Verification is also done on other
2354 # platforms when explicitly enabled.
2355 verify_load = (
2356 sys.platform == "darwin"
2357 or config.getcfg("profile_loader.verify_calibration")
2358 or "--verify" in sys.argv[1:]
2359 ) and profile_arg != "-L"
2360 max_attempts = max(
2361 1, int(config.getcfg("profile_loader.load_retries"))
2362 )
2363 load_error = None
2364 for attempt in range(max_attempts):
2365 if worker.exec_cmd(
2366 dispwin,
2367 ["-v", f"-d{i + 1:d}", profile_arg],
2368 capture_output=True,
2369 skip_scripts=True,
2370 silent=False,
2371 ):
2372 errortxt = ""
2373 else:
2374 errortxt = "\n".join(worker.errors).strip()
2375 if errortxt and (
2376 (
2377 "using linear" not in errortxt
2378 and "assuming linear" not in errortxt
2379 )
2380 or len(errortxt.split("\n")) > 1
2381 ):
2382 if (
2383 "Failed to get the displays current ICC profile"
2384 in errortxt
2385 ):
2386 # Maybe just not configured
2387 load_error = "skip"
2388 break
2389 if (
2390 sys.platform == "win32"
2391 or "Failed to set VideoLUT" in errortxt
2392 or "We don't have access to the VideoLUT" in errortxt
2393 ):
2394 errstr = lang.getstr("calibration.load_error")
2395 else:
2396 errstr = lang.getstr("profile.load_error")
2397 load_error = f"{display}: {errstr}"
2398 break
2399 # The load command itself succeeded. Verify the
2400 # calibration is actually loaded in the VideoLUT and
2401 # re-try the load if it was clobbered (macOS black
2402 # screen), see issue #694.
2403 if not verify_load:
2404 break
2405 if not worker.calibration_is_clobbered(
2406 dispwin, i, profile_arg
2407 ):
2408 # Loaded OK (or could not be determined)
2409 break
2410 if attempt + 1 < max_attempts:
2411 # Give the OS a moment to settle, then re-load
2412 print(
2413 f"VideoLUT for {display} not loaded "
2414 f"(attempt {attempt + 1:d}/{max_attempts:d}), "
2415 "re-loading calibration"
2416 )
2417 time.sleep(0.5)
2418 continue
2419 load_error = ": ".join(
2420 [display, lang.getstr("calibration.load_error")]
2421 )
2422 if load_error == "skip":
2423 continue
2424 if load_error:
2425 errors.append(load_error)
2426 continue
2427 results.append(display)
2428
2429 if sys.platform == "win32":
2430 self.lock.release()
2431 if event:
2432 self.notify(results, errors)
2433
2434 return errors
2435
2436 def _clobbered_displays(self, worker: Worker, dispwin: str) -> list[int]:
2437 """Return indices of displays whose VideoLUT looks clobbered (black).
2438
2439 Reads each display's VideoLUT directly via CoreGraphics rather than
2440 running ``dispwin -V``. Spawning any dispwin subprocess - even a
2441 read-only verify - can itself trigger macOS to clobber a *different*
2442 display's VideoLUT (issue #824), since Argyll's dispwin always
2443 restores its own captured baseline gamma table on exit, and it is
2444 that restore-then-exit sequence that the OS mishandles. See
2445 :func:`DisplayCAL.worker.get_macos_videolut_maxima`.
2446
2447 Args:
2448 worker (Worker): Worker with an up-to-date ``displays`` list.
2449 dispwin (str): Path to the dispwin executable. Unused now, kept
2450 for interface stability with callers/tests.
2451
2452 Returns:
2453 list[int]: Zero-based indices of clobbered displays.
2454 """
2455 from DisplayCAL.worker import get_macos_videolut_maxima
2456
2457 threshold = float(
2458 config.getcfg("profile_loader.macos_videolut_black_threshold")
2459 )
2460 maxima = get_macos_videolut_maxima()
2461 clobbered = []
2462 for i in range(len(worker.displays)):
2463 if config.is_virtual_display(i):
2464 continue
2465 if i >= len(maxima):
2466 continue
2467 maximum = maxima[i]
2468 if maximum is not None and maximum < threshold:
2469 clobbered.append(i)
2470 return clobbered
2471
2472 def _reload_clobbered_displays(
2473 self,
2474 worker: Worker,
2475 dispwin: str,
2476 max_passes: None | int = None,
2477 settle: float = 0.5,
2478 ) -> bool:
2479 """Reload calibration for every clobbered display, all in one process.
2480
2481 Applies every clobbered display's calibration directly via
2482 CoreGraphics (see :func:`DisplayCAL.worker.reload_macos_videoluts`),
2483 back-to-back from this single still-running process. Re-loading one
2484 display's calibration by running (and exiting) a dispwin process is
2485 exactly the event that triggers macOS to clobber a *different*
2486 display's VideoLUT (issue #694/#824's root cause): macOS mishandles
2487 the cleanup of a just-exited process's transient VideoLUT claim.
2488 Reloading every clobbered display from a single process that never
2489 exits between them avoids that OS bug entirely, confirmed
2490 experimentally on real multi-display hardware - so a single pass is
2491 expected to converge immediately. The pass loop remains as a safety
2492 net in case a display's VideoLUT is disturbed again mid-reload (e.g.
2493 by an unrelated display reconfiguration).
2494
2495 Args:
2496 worker (Worker): Worker with an up-to-date ``displays`` list.
2497 dispwin (str): Path to the dispwin executable. Unused now, kept
2498 for interface stability with callers/tests.
2499 max_passes (None | int): Maximum number of scan/reload passes.
2500 Defaults to ``profile_loader.macos_reapply_watch_max_passes``.
2501 settle (float): Seconds to wait between passes.
2502
2503 Returns:
2504 bool: True if every display verified clean before the pass budget
2505 ran out, False if some display was still clobbered when it
2506 gave up.
2507 """
2508 from DisplayCAL.worker import reload_macos_videoluts
2509
2510 if max_passes is None:
2511 max_passes = int(
2512 config.getcfg("profile_loader.macos_reapply_watch_max_passes")
2513 )
2514 for _ in range(max(1, max_passes)):
2515 if self._shutdown:
2516 return True
2517 clobbered = self._clobbered_displays(worker, dispwin)
2518 if not clobbered:
2519 return True
2520 print(
2521 "VideoLUT for display(s) "
2522 f"{', '.join(str(i + 1) for i in clobbered)} was clobbered - "
2523 "re-loading calibration"
2524 )
2525 reload_macos_videoluts(clobbered, log=print)
2526 if self._shutdown:
2527 return True
2528 time.sleep(settle)
2529 print(
2530 "Some displays' VideoLUTs are still clobbered after "
2531 f"{max_passes:d} re-load passes - will retry on the next watch tick"
2532 )
2533 return False
2534
2535 def _notify_macos_watch_unstable(self) -> None:
2536 """Warn the user that automatic VideoLUT recovery is not converging.
2537
2538 Some multi-display Macs exhibit a deterministic oscillation where
2539 reloading one display's calibration always clobbers another display's
2540 VideoLUT and vice-versa (issue #824): no amount of retrying can ever
2541 converge that case, since the last reload always evicts the previous
2542 one. Rather than keep hammering dispwin (and the displays) forever,
2543 this surfaces a one-time notification recommending a sleep/wake
2544 cycle, which reloads calibration through the OS's normal path
2545 (rather than Argyll's) and has been confirmed to recover cleanly.
2546 """
2547 message = (
2548 f"{APPNAME} could not automatically stabilize your displays' "
2549 "calibration. Try putting your Mac to sleep and waking it "
2550 "(or closing and re-opening the lid) to recover."
2551 )
2552 print(f"{APPNAME}: {message}")
2553 try:
2554 osascript(f'display notification "{message}" with title "{APPNAME}"')
2555 except Exception as exception:
2556 print(exception)
2557
2558 def _macos_watch(self) -> None:
2559 """Keep re-loading calibration on macOS if the VideoLUT gets clobbered.
2560
2561 macOS (WindowServer) intermittently resets the VideoLUT of a display to
2562 all-black some time after the calibration was loaded, turning the
2563 display black (issue #694). Unlike Windows, macOS has no persistent
2564 calibration loader by default, so this keeps the apply-profiles process
2565 running and periodically verifies that each display's calibration is
2566 still loaded, re-applying it for any display where it isn't.
2567
2568 On some multi-display setups, a display's own reload deterministically
2569 clobbers another display's VideoLUT (issue #824), so recovery can fail
2570 to converge no matter how many times it's retried within a tick. After
2571 several consecutive ticks without converging, this backs off - stops
2572 touching the displays for a while and shows a one-time notification -
2573 instead of endlessly re-triggering the flicker.
2574
2575 This blocks until ``self._shutdown`` is set, keeping the process alive.
2576 """
2577 from DisplayCAL.worker import Worker, get_argyll_util
2578
2579 dispwin = get_argyll_util("dispwin")
2580 if not dispwin:
2581 return
2582 interval = max(
2583 1, int(config.getcfg("profile_loader.macos_reapply_watch_interval"))
2584 )
2585 unstable_threshold = max(
2586 1,
2587 int(
2588 config.getcfg("profile_loader.macos_reapply_watch_unstable_threshold")
2589 ),
2590 )
2591 backoff_seconds = max(
2592 0,
2593 int(config.getcfg("profile_loader.macos_reapply_watch_backoff_seconds")),
2594 )
2595 unstable_ticks = 0
2596 backoff_until = 0.0
2597 worker = Worker()
2598 debug_print("Starting macOS VideoLUT watch (issue #694 mitigation)")
2599 while not self._shutdown:
2600 # Sleep in short slices so shutdown is responsive
2601 for _ in range(interval * 2):
2602 if self._shutdown:
2603 return
2604 time.sleep(0.5)
2605 # Don't touch the VideoLUT while DisplayCAL itself is calibrating or
2606 # profiling - it owns the VideoLUT during that time.
2607 if self._is_displaycal_running():
2608 continue
2609 if time.time() < backoff_until:
2610 # Recovery hasn't been converging - leave the displays alone
2611 # for the backoff window instead of continuing to flicker them.
2612 continue
2613 try:
2614 worker.enumerate_displays_and_ports(
2615 silent=True,
2616 check_lut_access=False,
2617 enumerate_ports=False,
2618 include_network_devices=False,
2619 )
2620 except Exception as exception:
2621 print(exception)
2622 continue
2623 if self._reload_clobbered_displays(worker, dispwin):
2624 unstable_ticks = 0
2625 continue
2626 unstable_ticks += 1
2627 if unstable_ticks >= unstable_threshold:
2628 self._notify_macos_watch_unstable()
2629 unstable_ticks = 0
2630 backoff_until = time.time() + backoff_seconds
2631
2632 def notify(
2633 self,
2634 results: list,
2635 errors: list,
2636 sticky: bool = False,
2637 show_notification: bool = False,
2638 ) -> None:
2639 """Notify the user about the results of profile application.
2640
2641 Args:
2642 results (list): List of successful profile applications.
2643 errors (list): List of errors encountered during profile application.
2644 sticky (bool, optional): Whether the notification should be sticky.
2645 Defaults to False.
2646 show_notification (bool, optional): Whether to show the notification.
2647 Defaults to False.
2648 """
2649 wx.CallAfter(
2650 lambda: self and self._notify(results, errors, sticky, show_notification)
2651 )
2652
2653 def _notify(
2654 self,
2655 results: list,
2656 errors: list,
2657 sticky: bool = False,
2658 show_notification: bool = False,
2659 ) -> None:
2660 """Handle the notification logic.
2661
2662 Args:
2663 results (list): List of successful profile applications.
2664 errors (list): List of errors encountered during profile application.
2665 sticky (bool, optional): Whether the notification should be sticky.
2666 Defaults to False.
2667 show_notification (bool, optional): Whether to show the notification.
2668 Defaults to False.
2669 """
2670 debug_print(
2671 f"[DEBUG] notify(results={results!r}, errors={errors!r}, "
2672 f"sticky={sticky}, show_notification={show_notification})"
2673 )
2674 self.taskbar_icon.set_visual_state()
2675 results.extend(errors)
2676 flags = wx.ICON_ERROR if errors else wx.ICON_INFORMATION
2677 self.taskbar_icon.show_notification(
2678 "\n".join(results), sticky, show_notification, flags
2679 )
2680 debug_print("[DEBUG] /notify")
2681
2682 def apply_profiles_and_warn_on_error(
2683 self, event: None | wx.Event = None, index: None | int = None
2684 ) -> None:
2685 """Apply profiles and show a warning dialog if there are errors.
2686
2687 Args:
2688 event (None | wx.Event, optional): The event that triggered the
2689 application of profiles. Defaults to None.
2690 index (None | int, optional): The index of the monitor to apply profiles
2691 to. If None, applies to all monitors. Defaults to None.
2692 """
2693 # wx.App must already be initialized at this point!
2694 errors = self.apply_profiles(event, index)
2695 if (
2696 errors
2697 and (
2698 config.getcfg("profile_loader.error.show_msg")
2699 or "--error-dialog" in sys.argv[1:]
2700 )
2701 and "--silent" not in sys.argv[1:]
2702 ):
2703 from DisplayCAL.wx_windows import InfoDialog, wx
2704
2705 dlg = InfoDialog(
2706 None,
2707 msg="\n".join(errors),
2708 title=self.get_title(),
2709 ok=lang.getstr("ok"),
2710 bitmap=config.get_icon(32, "dialog-error"),
2711 show=False,
2712 )
2713 dlg.SetIcons(
2714 config.get_icon_bundle([256, 48, 32, 16], APPNAME + "-apply-profiles")
2715 )
2716 dlg.do_not_show_again_cb = wx.CheckBox(
2717 dlg, -1, lang.getstr("dialog.do_not_show_again")
2718 )
2719 dlg.do_not_show_again_cb.SetValue(
2720 not bool(config.getcfg("profile_loader.error.show_msg"))
2721 )
2722
2723 def do_not_show_again_handler(event: None | wx.Event = None) -> None:
2724 """Handle the 'do not show again' checkbox event.
2725
2726 Args:
2727 event (None | wx.Event, optional): The event that triggered
2728 the handler. Defaults to None.
2729 """
2730 config.setcfg(
2731 "profile_loader.error.show_msg",
2732 int(not dlg.do_not_show_again_cb.GetValue()),
2733 )
2734 config.writecfg(
2735 module="apply-profiles",
2736 options=("argyll.dir", "profile.load_on_login", "profile_loader"),
2737 )
2738
2739 dlg.do_not_show_again_cb.Bind(wx.EVT_CHECKBOX, do_not_show_again_handler)
2740 dlg.sizer3.Add(dlg.do_not_show_again_cb, flag=wx.TOP, border=12)
2741 dlg.sizer0.SetSizeHints(dlg)
2742 dlg.sizer0.Layout()
2743 dlg.Center(wx.BOTH)
2744 dlg.ok.SetDefault()
2745 dlg.ShowModalThenDestroy()
2746
2747 def elevate(self) -> bool:
2748 """Elevate the process to run as administrator.
2749
2750 Returns:
2751 bool: True if the process was elevated, False otherwise.
2752 """
2753 if sys.getwindowsversion() < (6,):
2754 return False
2755
2756 loader_args = []
2757 if os.path.basename(EXE).lower() not in ("python.exe", "pythonw.exe"):
2758 cmd = os.path.join(PYDIR, f"{APPNAME}-apply-profiles.exe")
2759 else:
2760 # cmd = os.path.join(exedir, "pythonw.exe")
2761 cmd = EXE
2762 pyw = os.path.normpath(
2763 os.path.join(PYDIR, "..", f"{APPNAME}-apply-profiles.pyw")
2764 )
2765 if os.path.exists(pyw):
2766 # Running from source or 0install
2767 # Check if this is a 0install implementation, in which
2768 # case we want to call 0launch with the appropriate
2769 # command
2770 if re.match(
2771 r"sha\d+(?:new)?", os.path.basename(os.path.dirname(PYDIR))
2772 ):
2773 cmd = which("0install-win.exe") or "0install-win.exe"
2774 loader_args.extend(
2775 [
2776 "run",
2777 "--batch",
2778 "--no-wait",
2779 "--offline",
2780 "--command=run-apply-profiles",
2781 f"http://{DOMAIN}/0install/{APPNAME}.xml",
2782 ]
2783 )
2784 else:
2785 # Running from source
2786 loader_args.append(pyw)
2787 else:
2788 # Regular install
2789 loader_args.append(
2790 get_data_path("/".join(["scripts", f"{APPNAME}-apply-profiles"]))
2791 )
2792
2793 loader_args.append("--profile-associations")
2794 print(f"cmd: {cmd}")
2795 print(f"loader_args: {loader_args}")
2796 try:
2797 run_as_admin(cmd, loader_args)
2798 except pywintypes.error as exception:
2799 if exception.args[0] != winerror.ERROR_CANCELLED:
2800 show_result_dialog(exception)
2801 else:
2802 self.shutdown()
2803 wx.CallLater(50, self.exit)
2804 return True
2805 return False
2806
2807 def exit(self, event: None | wx.Event = None) -> None:
2808 """Exit the application.
2809
2810 Args:
2811 event (None | wx.Event, optional): The event that triggered the
2812 exit. Defaults to None.
2813 """
2814 print(f"Executing ProfileLoader.exit({event})")
2815 dlg = None
2816 for dlg in get_dialogs():
2817 if not isinstance(dlg, ProfileLoaderExceptionsDialog) or (
2818 event and hasattr(event, "CanVeto") and not event.CanVeto()
2819 ):
2820 try:
2821 dlg.EndModal(wx.ID_CANCEL)
2822 except Exception:
2823 pass
2824 else:
2825 dlg = None
2826 if dlg and event and hasattr(event, "CanVeto") and event.CanVeto():
2827 # Need to request user attention for all open
2828 # dialogs because calling it only on the topmost
2829 # one does not guarantee taskbar flash
2830 dlg.RequestUserAttention()
2831 else:
2832 if dlg and event and hasattr(event, "CanVeto") and event.CanVeto():
2833 event.Veto()
2834 print("Vetoed", event)
2835 return
2836 if (
2837 event
2838 and self.frame
2839 and event.GetEventType() == wx.EVT_MENU.typeId
2840 and (
2841 not calibration_management_isenabled()
2842 or config.getcfg("profile_loader.fix_profile_associations")
2843 )
2844 ):
2845 dlg = ConfirmDialog(
2846 None,
2847 msg=lang.getstr("profile_loader.exit_warning"),
2848 title=self.get_title(),
2849 ok=lang.getstr("menuitem.quit"),
2850 bitmap=config.get_icon(32, "dialog-warning"),
2851 )
2852 dlg.SetIcons(
2853 config.get_icon_bundle([256, 48, 32, 16], APPNAME + "-apply-profiles")
2854 )
2855 result = dlg.ShowModal()
2856 dlg.Destroy()
2857 if result != wx.ID_OK:
2858 print(f"Cancelled ProfileLoader.exit({event})")
2859 return
2860 if isinstance(event, wx.CloseEvent):
2861 # Other event source
2862 event.Skip()
2863 else:
2864 # Called from menu
2865 wx.GetApp().ExitMainLoop()
2866
2867 def get_title(self) -> str:
2868 """Get the title of the application.
2869
2870 Returns:
2871 str: The title of the application.
2872 """
2873 title = "{} {} {}".format(
2874 APPNAME,
2875 lang.getstr("profile_loader").title(),
2876 VERSION_STRING,
2877 )
2878 if "--force" in sys.argv[1:]:
2879 title += " ({})".format(lang.getstr("forced"))
2880 return title
2881
2882 def _can_fix_profile_associations(self) -> bool:
2883 """Check whether we can 'fix' profile associations or not.
2884
2885 'Fixing' means we assign the profile of the actual active child device
2886 to the 1st child device so that applications using GetICMProfile get
2887 the correct profile (GetICMProfile always returns the profile of the
2888 1st child device irrespective if this device is active or not. This is
2889 a Windows bug).
2890
2891 This only works if a child device is not attached to several adapters
2892 (which is something that can happen due to the inexplicable mess that
2893 is the Windows display enumeration API).
2894
2895 Returns:
2896 bool: True if we can fix profile associations, False otherwise.
2897 """
2898 if not self.child_devices_count:
2899 for _display, _edid, moninfo, _device in self.monitors:
2900 child_devices = get_display_devices(moninfo["Device"])
2901 for child_device in child_devices:
2902 if child_device.DeviceKey not in self.child_devices_count:
2903 self.child_devices_count[child_device.DeviceKey] = 0
2904 self.child_devices_count[child_device.DeviceKey] += 1
2905 return (
2906 bool(self.child_devices_count)
2907 and max(self.child_devices_count.values()) == 1
2908 )
2909
2910 def _check_keep_running(self) -> bool:
2911 """Check if the application should keep running."""
2912 windows = []
2913 # print '-' * 79
2914 with contextlib.suppress(pywintypes.error):
2915 win32gui.EnumThreadWindows(
2916 self._tid, self._enumerate_own_windows_callback, windows
2917 )
2918 windows.extend(
2919 [
2920 window
2921 for window in list(wx.GetTopLevelWindows())
2922 if not isinstance(window, wx.Dialog)
2923 and window.Name
2924 not in {"TaskBarNotification", "DisplayIdentification", "profile_info"}
2925 ]
2926 )
2927 numwindows = len(windows)
2928 if numwindows < self.numwindows:
2929 # One of our windows has been closed by an external event
2930 # (i.e. WM_CLOSE). This is a hint that something external is trying
2931 # to get us to exit. Comply by closing our main top-level window to
2932 # initiate clean shutdown.
2933 print("Window count", self.numwindows, "->", numwindows)
2934 return False
2935 self.numwindows = numwindows
2936 return True
2937
2938 def _enumerate_own_windows_callback(self, hwnd: int, windowlist: list) -> None:
2939 """Callback for enumerating own windows.
2940
2941 Args:
2942 hwnd (int): The handle of the window.
2943 windowlist (list): The list to append the window class names to.
2944 """
2945 cls = win32gui.GetClassName(hwnd)
2946 # print cls
2947 if cls in (
2948 "madHcNetQueueWindow",
2949 "wxTLWHiddenParent",
2950 "wxTimerHiddenWindow",
2951 "wxDisplayHiddenWindow",
2952 "SysTrayIcon",
2953 ) or cls.startswith("madToolsMsgHandlerWindow"):
2954 windowlist.append(cls)
2955
2956 def _display_changed(self, event: wx.Event) -> None:
2957 """Handle a display changed event.
2958
2959 Args:
2960 event (wx.Event): The event that triggered the display change.
2961 """
2962 threading.Thread(
2963 target=self._process_display_changed, name="ProcessDisplayChangedEvent"
2964 ).start()
2965
2966 def _process_display_changed(self) -> None:
2967 """Process a display changed event."""
2968 if self.lock.locked():
2969 print("ProcessDisplayChangedEvent: Waiting to acquire lock...")
2970 with self.lock:
2971 print("ProcessDisplayChangedEvent: Acquired lock")
2972 self._display_changed_event = True
2973 self._next = True
2974 if getattr(self, "profile_associations_dlg", None):
2975 wx.CallAfter(
2976 wx.CallLater,
2977 1000,
2978 lambda: (
2979 self.profile_associations_dlg
2980 and self.profile_associations_dlg.update(True)
2981 ),
2982 )
2983 if getattr(self, "fix_profile_associations_dlg", None):
2984 wx.CallAfter(
2985 wx.CallLater,
2986 1000,
2987 lambda: (
2988 self.fix_profile_associations_dlg
2989 and self.fix_profile_associations_dlg.update(True)
2990 ),
2991 )
2992 print("ProcessDisplayChangedEvent: Releasing lock")
2993
2994 def _check_display_changed(
2995 self,
2996 first_run: bool = False,
2997 dry_run: bool = False,
2998 ) -> bool:
2999 """Check if the display configuration has changed.
3000
3001 Args:
3002 first_run (bool, optional): Whether this is the first run of the
3003 application. Defaults to False.
3004 dry_run (bool, optional): If True, do not update internal state,
3005 just check if display configuration has changed. Defaults to False.
3006
3007 Returns:
3008 bool: True if the display configuration has changed, False otherwise.
3009 """
3010 # Check registry if display configuration changed (e.g. if a display
3011 # was added/removed, and not just the resolution changed)
3012 if not (first_run or self._display_changed_event):
3013 # Not first run and no prior display changed event
3014 return False
3015 has_display_changed = False
3016 ts = time.time()
3017 key_name = r"SYSTEM\CurrentControlSet\Control\GraphicsDrivers\Configuration"
3018 try:
3019 key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name)
3020 numsubkeys, numvalues, mtime = winreg.QueryInfoKey(key)
3021 except OSError as exception:
3022 # Windows XP or Win10 >= 1903 if not running elevated
3023 if exception.args[0] != errno.ENOENT or sys.getwindowsversion() >= (6,):
3024 warnings.warn(
3025 rf"Registry access failed: {exception}: HKLM\{key_name}",
3026 Warning,
3027 stacklevel=2,
3028 )
3029 key = None
3030 numsubkeys = 0
3031 # get_active_display_devices takes around 3-10ms in contrast to
3032 # querying registry which takes 1-3ms
3033 if (
3034 not self._active_displays
3035 or self._active_displays != get_active_display_devices("DeviceKey")
3036 ):
3037 has_display_changed = True
3038 for i in range(numsubkeys):
3039 try:
3040 subkey_name = winreg.EnumKey(key, i)
3041 subkey = winreg.OpenKey(key, subkey_name)
3042 except OSError as exception:
3043 warnings.warn(
3044 f"Registry access failed: {exception}: "
3045 rf"HKLM\{key_name}\{subkey_name}",
3046 Warning,
3047 stacklevel=2,
3048 )
3049 continue
3050 value_name = "SetId"
3051 try:
3052 display = winreg.QueryValueEx(subkey, "SetId")[0]
3053 value_name = "Timestamp"
3054 # winreg.QueryValuesEx will directly return the int value,
3055 # so no need to convert the binary data as in Python2
3056 timestamp = winreg.QueryValueEx(subkey, "Timestamp")[0]
3057 except OSError as exception:
3058 warnings.warn(
3059 f"Registry access failed: {exception}: {value_name} "
3060 rf"(HKLM\{key_name}\{subkey_name})",
3061 Warning,
3062 stacklevel=2,
3063 )
3064 continue
3065 if timestamp > self._current_timestamp:
3066 if display != self._current_display:
3067 has_display_changed = True
3068 if not dry_run:
3069 self._current_display = display
3070 self._current_timestamp = timestamp
3071 winreg.CloseKey(subkey)
3072 if key:
3073 winreg.CloseKey(key)
3074 print(
3075 "Display configuration change detection took {:.6f} ms".format( # noqa: UP032
3076 (time.time() - ts) * 1000.0
3077 )
3078 )
3079 if not dry_run:
3080 # Display conf or resolution change
3081 self._enumerate_monitors()
3082 if has_display_changed:
3083 # First run or display conf change, not just resolution
3084 if not (first_run or dry_run):
3085 print(lang.getstr("display_detected"))
3086 if not dry_run and getcfg("profile_loader.fix_profile_associations"):
3087 # Work-around long-standing bug in applications
3088 # querying the monitor profile not making sure
3089 # to use the active display (this affects Windows
3090 # itself as well) when only one display is
3091 # active in a multi-monitor setup.
3092 if not first_run:
3093 self._reset_display_profile_associations()
3094 self._set_display_profiles()
3095 if not (first_run or dry_run) and self._is_displaycal_running():
3096 # Normally calibration loading is disabled while
3097 # DisplayCAL is running. Override this when the
3098 # display has changed
3099 self._manual_restore = getcfg("profile.load_on_login") and 2
3100 if not dry_run:
3101 self._has_display_changed = has_display_changed
3102 self._display_changed_event = False
3103 return has_display_changed
3104
3105 def _check_display_conf_wrapper(self) -> None:
3106 try:
3107 self._check_display_conf()
3108 except Exception as exception:
3109 if self.lock.locked():
3110 self.lock.release()
3111 wx.CallAfter(self._handle_fatal_error, exception)
3112
3113 def _handle_fatal_error(self, exception: Exception) -> None:
3114 handle_error(exception)
3115 wx.CallAfter(self.exit)
3116
3117 def _check_display_conf(self) -> None:
3118 """Thread to monitor display configuration changes."""
3119 self._current_display = None
3120 self._current_timestamp = 0
3121 self._next = False
3122 first_run = True
3123 apply_profiles = self._should_apply_profiles()
3124 displaycal_running = False
3125 previous_hwnds_pids = self._hwnds_pids
3126 while self and self.monitoring:
3127 result = None
3128 results = []
3129 errors = []
3130 idle = True
3131 locked = self.lock.locked()
3132 if locked:
3133 print(
3134 "DisplayConfigurationMonitoringThread: Waiting to acquire lock..."
3135 )
3136 lock_acquired = self.lock.acquire()
3137 if lock_acquired:
3138 print("DisplayConfigurationMonitoringThread: Acquired lock")
3139 # Check if display configuration changed
3140 self._check_display_changed(first_run)
3141 profile_associations_changed, apply_profiles, idle, result = (
3142 self._check_profile_associations(
3143 first_run, idle, previous_hwnds_pids, result, results, errors
3144 )
3145 )
3146 if self._next:
3147 # We only arrive here if a change in profile associations was
3148 # detected and we exited the loop early
3149 if locked:
3150 print("DisplayConfigurationMonitoringThread: Releasing lock")
3151 self.lock.release()
3152 if locked:
3153 print("DisplayConfigurationMonitoringThread: Released lock")
3154 continue
3155 previous_hwnds_pids = self._hwnds_pids
3156 timestamp = time.time()
3157 localtime = list(time.localtime(self._timestamp))
3158 localtime[3:6] = 23, 59, 59
3159 midnight = time.mktime(tuple(localtime)) + 1
3160 if timestamp >= midnight:
3161 self.reload_count = 0
3162 self._timestamp = timestamp
3163 self._handle_profile_updates(
3164 first_run,
3165 apply_profiles,
3166 displaycal_running,
3167 results,
3168 errors,
3169 idle,
3170 profile_associations_changed,
3171 )
3172 if apply_profiles and not idle:
3173 wx.CallAfter(lambda: self and self.taskbar_icon.animate())
3174 self.__apply_profiles = apply_profiles
3175 first_run = False
3176 if profile_associations_changed and not self._has_display_changed:
3177 if getattr(self, "profile_associations_dlg", None):
3178 wx.CallAfter(
3179 lambda: (
3180 self.profile_associations_dlg
3181 and self.profile_associations_dlg.update_profiles()
3182 )
3183 )
3184 if getattr(self, "fix_profile_associations_dlg", None):
3185 wx.CallAfter(
3186 lambda: (
3187 self.fix_profile_associations_dlg
3188 and self.fix_profile_associations_dlg.update()
3189 )
3190 )
3191 if result:
3192 self._has_display_changed = False
3193 self._manual_restore = False
3194 self._skip = False
3195 if locked:
3196 print("DisplayConfigurationMonitoringThread: Releasing lock")
3197 self.lock.release()
3198 if locked:
3199 print("DisplayConfigurationMonitoringThread: Released lock")
3200 if "--oneshot" in sys.argv[1:]:
3201 wx.CallAfter(self.exit)
3202 break
3203 if "--profile-associations" in sys.argv[1:]:
3204 sys.argv.remove("--profile-associations")
3205 wx.CallAfter(self._set_profile_associations, None)
3206 # Wait three seconds
3207 timeout = 0
3208 while (
3209 self
3210 and self.monitoring
3211 and timeout < 3
3212 and not self._manual_restore
3213 and not self._next
3214 ):
3215 if round(timeout * 100) % 25 == 0 and not self._check_keep_running():
3216 self.monitoring = False
3217 wx.CallAfter(lambda: self.frame and self.frame.Close(force=True))
3218 break
3219 time.sleep(0.1)
3220 timeout += 0.1
3221 print("Display configuration monitoring thread finished")
3222 self.shutdown()
3223
3224 def _check_profile_associations(
3225 self,
3226 first_run: bool,
3227 idle: bool,
3228 previous_hwnds_pids: dict,
3229 result: None | bool,
3230 results: list[str],
3231 errors: list[str],
3232 ) -> tuple[int, bool, bool, None | bool]:
3233 """Check profile associations and apply profiles if necessary.
3234
3235 Args:
3236 first_run (bool): Whether this is the first run of the application.
3237 idle (bool): Whether the system is idle.
3238 previous_hwnds_pids (dict): Previous window handles and process IDs.
3239 result (None | bool): Result of the last profile application.
3240 results (list[str]): List to store results of profile applications.
3241 errors (list[str]): List to store errors encountered during profile
3242 applications.
3243
3244 Returns:
3245 tuple[int, bool, bool, None | bool]: A tuple containing:
3246 - profile_associations_changed (int): Number of changed profile
3247 associations.
3248 - apply_profiles (bool): Whether to apply profiles.
3249 - idle (bool): Whether the system is idle.
3250 - result (None | bool): Result of the last profile application.
3251 """
3252 # Check profile associations
3253 profile_associations_changed = 0
3254 apply_profiles = self._should_apply_profiles()
3255 for i, (display, _edid, moninfo, device) in enumerate(self.monitors):
3256 display_desc = display.replace("[PRIMARY]", lang.getstr("display.primary"))
3257 devicekey = device.DeviceKey if device else None
3258 key = devicekey or str(i)
3259 self._current_display_key = key
3260 exception = None
3261 profile_path = profile_name = None
3262 try:
3263 profile_path = get_display_profile(
3264 i, path_only=True, devicekey=devicekey
3265 )
3266 except IndexError:
3267 debug_print(f"Display {key} ({display}) no longer present?")
3268 self._next = False
3269 break
3270 except Exception as exception:
3271 if (
3272 exception.args[0] != errno.ENOENT
3273 and exception.args != self._last_exception_args
3274 ) or DEBUG:
3275 self._last_exception_args = exception.args
3276 print(
3277 f"Could not get display profile for display {key} ({display}):",
3278 exception,
3279 )
3280 if exception.args[0] == errno.ENOENT:
3281 # Unassigned - don't show error icon
3282 self.setgammaramp_success[i] = True
3283 exception = None
3284 else:
3285 self.setgammaramp_success[i] = None
3286 else:
3287 if profile_path:
3288 profile_name = os.path.basename(profile_path)
3289 profile_key = str(profile_name or exception or "")
3290 association = self.profile_associations.get(key, (False, 0, ""))
3291 if (
3292 getcfg("profile_loader.fix_profile_associations")
3293 and not first_run
3294 and not self._has_display_changed
3295 and not self._next
3296 and association[0] != profile_key
3297 ):
3298 # At this point we do not yet know if only the profile
3299 # association has changed or the display configuration.
3300 # One second delay to allow display configuration
3301 # to settle
3302 if not self._check_display_changed(dry_run=True):
3303 debug_print("Delay 1s")
3304 timeout = 0
3305 while (
3306 self
3307 and self.monitoring
3308 and timeout < 1
3309 and self._manual_restore != 2
3310 and not self._next
3311 ):
3312 time.sleep(0.1)
3313 timeout += 0.1
3314 self._next = True
3315 break
3316 mtime = (
3317 os.stat(profile_path).st_mtime
3318 if (profile_path and os.path.isfile(profile_path))
3319 else 0
3320 )
3321 profile_association_changed = False
3322 profile_associations_changed, profile_association_changed, desc = (
3323 self._update_profile_associations(
3324 display,
3325 first_run,
3326 i,
3327 moninfo,
3328 key,
3329 exception,
3330 profile_name,
3331 profile_key,
3332 association,
3333 mtime,
3334 profile_association_changed,
3335 profile_associations_changed,
3336 )
3337 )
3338 # Check video card gamma table and (re)load calibration if
3339 # necessary
3340 if not self.gdi32 or not (profile_name or self._reset_gamma_ramps):
3341 continue
3342 recheck = False
3343 apply_profiles, recheck, vcgt_ramp, vcgt_ramp_hack, vcgt_values = (
3344 self._generate_and_apply_profiles(
3345 recheck,
3346 results,
3347 errors,
3348 i,
3349 display_desc,
3350 key,
3351 profile_name,
3352 profile_association_changed,
3353 desc,
3354 )
3355 )
3356 if (
3357 not apply_profiles
3358 and self.__other_component[1] != "madHcNetQueueWindow"
3359 ):
3360 # Important: Do not break here because we still want to
3361 # detect changed profile associations
3362 continue
3363 hwnds_pids_changed = self._track_process_changes(previous_hwnds_pids)
3364 idle = (
3365 (
3366 not hwnds_pids_changed
3367 and not self._manual_restore
3368 and not profile_association_changed
3369 )
3370 if idle
3371 else idle
3372 )
3373 idle, do_continue = self._check_gamma_ramp_status(
3374 display,
3375 idle,
3376 i,
3377 moninfo,
3378 display_desc,
3379 key,
3380 profile_association_changed,
3381 apply_profiles,
3382 vcgt_values,
3383 hwnds_pids_changed,
3384 )
3385 if do_continue:
3386 continue
3387 is_buggy_video_driver = self._is_buggy_video_driver(moninfo)
3388 if recheck:
3389 # Try and prevent race condition with madVR
3390 # launching and resetting video card gamma table
3391 apply_profiles = self._should_apply_profiles()
3392 if not apply_profiles or idle:
3393 # Important: Do not break here because we still want to
3394 # detect changed profile associations
3395 continue
3396 self._log_profile_association_changes(
3397 profile_associations_changed,
3398 profile_association_changed,
3399 apply_profiles,
3400 )
3401 # Now actually reload or reset calibration
3402 self._reload_or_reset_calibration(
3403 display,
3404 display_desc,
3405 profile_association_changed,
3406 desc,
3407 hwnds_pids_changed,
3408 )
3409 try:
3410 hdc = win32gui.CreateDC(moninfo["Device"], None, None)
3411 except Exception as exception:
3412 if exception.args != self._last_exception_args or DEBUG:
3413 self._last_exception_args = exception.args
3414 print(
3415 "Couldn't create DC for",
3416 moninfo["Device"],
3417 f"({display})",
3418 )
3419 continue
3420 result = self._set_device_gamma_ramp(
3421 i, key, vcgt_ramp, vcgt_ramp_hack, is_buggy_video_driver, hdc
3422 )
3423 self._report_calibration_status(
3424 results,
3425 errors,
3426 display_desc,
3427 profile_association_changed,
3428 desc,
3429 hwnds_pids_changed,
3430 result,
3431 )
3432 else:
3433 # We only arrive here if the loop was completed
3434 self._next = False
3435 return profile_associations_changed, apply_profiles, idle, result
3436
3437 def _generate_and_apply_profiles(
3438 self,
3439 recheck: bool,
3440 results: list[str],
3441 errors: list[str],
3442 i: int,
3443 display_desc: str,
3444 key: str,
3445 profile_name: str,
3446 profile_association_changed: bool,
3447 desc: str,
3448 ) -> tuple[
3449 bool,
3450 bool,
3451 ctypes.c_ushort_Array_256_Array_3,
3452 ctypes.c_ushort_Array_256_Array_3,
3453 list[tuple[int, int, int]],
3454 ]:
3455 """Generate and apply profiles.
3456
3457 Args:
3458 recheck (bool): Whether to recheck the gamma ramp.
3459 results (list[str]): The list of results.
3460 errors (list[str]): The list of errors.
3461 i (int): The display index.
3462 display_desc (str): The description of the display.
3463 key (str): The profile association key.
3464 profile_name (str): The profile name.
3465 profile_association_changed (bool): Whether the profile association
3466 has changed.
3467 desc (str): The description of the profile.
3468
3469 Returns:
3470 tuple[
3471 bool,
3472 bool,
3473 ctypes.c_ushort_Array_256_Array_3,
3474 ctypes.c_ushort_Array_256_Array_3,
3475 list[tuple[int, int, int]]
3476 ]: A tuple containing whether to apply profiles, whether to recheck,
3477 the VCGT ramp, the VCGT ramp hack, and the VCGT values.
3478 """
3479 apply_profiles = self._should_apply_profiles()
3480 recheck, vcgt_ramp, vcgt_ramp_hack, vcgt_values = self._generate_gamma_ramp(
3481 recheck,
3482 results,
3483 errors,
3484 display_desc,
3485 key,
3486 profile_name,
3487 profile_association_changed,
3488 desc,
3489 )
3490 if self._skip:
3491 self.setgammaramp_success[i] = True
3492 return apply_profiles, recheck, vcgt_ramp, vcgt_ramp_hack, vcgt_values
3493
3494 def _log_profile_association_changes(
3495 self,
3496 profile_associations_changed: int,
3497 profile_association_changed: bool,
3498 apply_profiles: bool,
3499 ) -> None:
3500 """Log profile association changes for debugging.
3501
3502 Args:
3503 profile_associations_changed (int): The number of profile
3504 associations changed.
3505 profile_association_changed (bool): Whether the profile association
3506 has changed.
3507 apply_profiles (bool): Whether to apply profiles.
3508 """
3509 if self._manual_restore:
3510 debug_print("Manual restore flag:", self._manual_restore)
3511 if profile_association_changed:
3512 debug_print(
3513 "Number of profile associations changed:",
3514 profile_associations_changed,
3515 )
3516 if apply_profiles:
3517 debug_print("Apply profiles:", apply_profiles)
3518
3519 def _set_device_gamma_ramp(
3520 self,
3521 i: int,
3522 key: str,
3523 vcgt_ramp: ctypes.c_ushort_Array_256_Array_3,
3524 vcgt_ramp_hack: ctypes.c_ushort_Array_256_Array_3,
3525 is_buggy_video_driver: bool,
3526 hdc: int,
3527 ) -> None | bool | Exception:
3528 """Set the device gamma ramp.
3529
3530 Args:
3531 i (int): The display index.
3532 key (str): The profile association key.
3533 vcgt_ramp (ctypes.c_ushort_Array_256_Array_3): The VCGT ramp.
3534 vcgt_ramp_hack (ctypes.c_ushort_Array_256_Array_3): The VCGT ramp
3535 hack for buggy video drivers.
3536 is_buggy_video_driver (bool): Whether the video driver is buggy.
3537 hdc (int): The device context handle.
3538
3539 Returns:
3540 None | bool | Exception: The result of setting the device gamma
3541 ramp.
3542 """
3543 try:
3544 if is_buggy_video_driver:
3545 result = self.gdi32.SetDeviceGammaRamp(hdc, vcgt_ramp_hack)
3546 result = self.gdi32.SetDeviceGammaRamp(hdc, vcgt_ramp)
3547 except Exception as exception:
3548 result = exception
3549 finally:
3550 win32gui.DeleteDC(hdc)
3551 self.setgammaramp_success[i] = (
3552 result
3553 and not isinstance(result, Exception)
3554 and (self._reset_gamma_ramps or bool(self.profiles.get(key)))
3555 )
3556
3557 return result
3558
3559 def _report_calibration_status(
3560 self,
3561 results: list[str],
3562 errors: list[str],
3563 display_desc: str,
3564 profile_association_changed: bool,
3565 desc: str,
3566 hwnds_pids_changed: bool,
3567 result: None | bool | Exception,
3568 ) -> None:
3569 """Report the calibration status.
3570
3571 Args:
3572 results (list[str]): The list of results.
3573 errors (list[str]): The list of errors.
3574 display_desc (str): The description of the display.
3575 profile_association_changed (bool): Whether the profile association
3576 has changed.
3577 desc (str): The description of the profile.
3578 hwnds_pids_changed (bool): Whether the HWNDs and PIDs have changed.
3579 result (None | bool | Exception): The result of setting the gamma
3580 ramp.
3581 """
3582 if (
3583 self._manual_restore
3584 or profile_association_changed
3585 or (not hwnds_pids_changed and getcfg("profile_loader.check_gamma_ramps"))
3586 ):
3587 if isinstance(result, Exception) or not result:
3588 if result:
3589 print(result)
3590 print(lang.getstr("failure"))
3591 else:
3592 print(lang.getstr("success"))
3593 if self._manual_restore or (
3594 profile_association_changed
3595 and (isinstance(result, Exception) or not result)
3596 ):
3597 if isinstance(result, Exception) or not result:
3598 errstr = lang.getstr("calibration.load_error")
3599 errors.append(f"{display_desc}: {errstr}")
3600 else:
3601 text = display_desc + ": "
3602 if self._reset_gamma_ramps:
3603 text += lang.getstr("linear").capitalize()
3604 else:
3605 text += desc
3606 results.append(text)
3607
3608 def _update_profile_associations(
3609 self,
3610 display: str,
3611 first_run: bool,
3612 i: int,
3613 moninfo: dict,
3614 key: str,
3615 exception: Exception,
3616 profile_name: str,
3617 profile_key: str,
3618 association: tuple[bool, float, str],
3619 mtime: float,
3620 profile_association_changed: bool,
3621 profile_associations_changed: int,
3622 ) -> tuple[int, bool, str]:
3623 """Update profile associations.
3624
3625 Args:
3626 display (str): The display name.
3627 first_run (bool): Whether this is the first run.
3628 i (int): The display index.
3629 moninfo (dict): The monitor information.
3630 key (str): The profile association key.
3631 exception (Exception): The exception if any.
3632 profile_name (str): The profile name.
3633 profile_key (str): The profile key.
3634 association (tuple[bool, float, str]): The current association.
3635 mtime (float): The modification time of the profile.
3636 profile_association_changed (bool): Whether the profile association
3637 has changed.
3638 profile_associations_changed (int): The number of profile
3639 associations changed.
3640
3641 Returns:
3642 tuple[int, bool, str]: The updated number of profile associations
3643 changed, whether the profile association changed, and the
3644 description.
3645 """
3646 if association[:2] == (profile_key, mtime):
3647 desc = association[2]
3648 return profile_associations_changed, profile_association_changed, desc
3649
3650 if profile_name is None:
3651 desc = str(exception or "?")
3652 else:
3653 desc = get_profile_desc(profile_name)
3654 if not first_run:
3655 print("A profile change has been detected")
3656 print(display, "->", desc)
3657 device = get_active_display_device(moninfo["Device"])
3658 if device:
3659 display_edid = get_display_name_edid(device, moninfo, i)
3660 if self.monitoring:
3661 self.devices2profiles[device.DeviceKey] = (
3662 display_edid,
3663 profile_name,
3664 desc,
3665 )
3666 if device:
3667 debug_print(
3668 f"Monitor {moninfo['Device']} active display device name:",
3669 device.DeviceName,
3670 )
3671 debug_print(
3672 f"Monitor {moninfo['Device']} active display device string:",
3673 device.DeviceString,
3674 )
3675 debug_print(
3676 f"Monitor {moninfo['Device']} "
3677 "active display device state flags: "
3678 f"0x{device.StateFlags:x}"
3679 )
3680 debug_print(
3681 f"Monitor {moninfo['Device']} active display device ID:",
3682 device.DeviceID,
3683 )
3684 debug_print(
3685 f"Monitor {moninfo['Device']} active display device key:",
3686 device.DeviceKey,
3687 )
3688 else:
3689 debug_print(
3690 f"WARNING: Monitor {moninfo['Device']} has no active display device"
3691 )
3692 self.profile_associations[key] = (profile_key, mtime, desc)
3693 self.profiles[key] = None
3694 self.ramps[key] = (None, None, None)
3695 profile_association_changed = True
3696 profile_associations_changed += 1
3697 if not first_run and self._is_displaycal_running():
3698 # Normally calibration loading is disabled while
3699 # DisplayCAL is running. Override this when the
3700 # display has changed
3701 self._manual_restore = getcfg("profile.load_on_login") and 2
3702
3703 return profile_associations_changed, profile_association_changed, desc
3704
3705 def _generate_gamma_ramp(
3706 self,
3707 recheck: bool,
3708 results: list[str],
3709 errors: list[str],
3710 display_desc: str,
3711 key: str,
3712 profile_name: str,
3713 profile_association_changed: bool,
3714 desc: str,
3715 ) -> tuple[
3716 bool,
3717 ctypes.c_ushort_Array_256_Array_3,
3718 ctypes.c_ushort_Array_256_Array_3,
3719 tuple[list[float], list[float], list[float]],
3720 ]:
3721 """Generate the gamma ramp for the given profile.
3722
3723 Args:
3724 recheck (bool): Whether to recheck the gamma ramp.
3725 results (list[str]): The list of results.
3726 errors (list[str]): The list of errors.
3727 display_desc (str): The description of the display.
3728 key (str): The key for the profile.
3729 profile_name (str): The name of the profile.
3730 profile_association_changed (bool): Whether the profile association
3731 has changed.
3732 desc (str): The description of the profile.
3733
3734 Returns:
3735 tuple[
3736 bool,
3737 ctypes.c_ushort_Array_256_Array_3,
3738 ctypes.c_ushort_Array_256_Array_3,
3739 tuple[list[float], list[float], list[float]]
3740 ]: The recheck flag, the gamma ramp, the hack gamma ramp, and the
3741 VCGT values.
3742 """
3743 (vcgt_ramp, vcgt_ramp_hack, vcgt_values) = self.ramps.get(
3744 self._reset_gamma_ramps or key, (None, None, None)
3745 )
3746 recheck = False
3747 if vcgt_ramp:
3748 return recheck, vcgt_ramp, vcgt_ramp_hack, vcgt_values
3749
3750 vcgt_values, profile = self._retrieve_profile_vcgt(key, profile_name)
3751
3752 if len(vcgt_values[0]) != 256:
3753 # Hmm. Do we need to deal with this?
3754 # I've never seen table-based vcgt with != 256 entries
3755 if (
3756 not self._reset_gamma_ramps
3757 and (self._manual_restore or profile_association_changed)
3758 and profile.tags.get("vcgt")
3759 ):
3760 print(lang.getstr("calibration.loading_from_display_profile"))
3761 print(display_desc)
3762 print(
3763 lang.getstr(
3764 "vcgt.unknown_format",
3765 os.path.basename(profile.filename),
3766 )
3767 )
3768 print(lang.getstr("failure"))
3769 results.append(display_desc)
3770 errors.append(
3771 lang.getstr(
3772 "vcgt.unknown_format",
3773 os.path.basename(profile.filename),
3774 )
3775 )
3776 # Fall back to linear calibration
3777 tag_data = b"vcgt"
3778 tag_data += b"\0" * 4 # Reserved
3779 tag_data += b"\0\0\0\x01" # Formula type
3780 for _channel in range(3):
3781 tag_data += b"\0\x01\0\0" # Gamma 1.0
3782 tag_data += b"\0" * 4 # Min 0.0
3783 tag_data += b"\0\x01\0\0" # Max 1.0
3784 vcgt = VideoCardGammaFormulaType(tag_data, "vcgt")
3785 vcgt_values = vcgt.get_values()[:3]
3786 if self._reset_gamma_ramps:
3787 print("Caching linear gamma ramps")
3788 else:
3789 print("Caching implicit linear gamma ramps for profile", desc)
3790 else:
3791 print("Caching gamma ramps for profile", desc)
3792 # Convert vcgt to ushort_Array_256_Array_3
3793 vcgt_ramp = ((ctypes.c_ushort * 256) * 3)()
3794 vcgt_ramp_hack = ((ctypes.c_ushort * 256) * 3)()
3795 for j in range(len(vcgt_values[0])):
3796 for k in range(3):
3797 vcgt_value = vcgt_values[k][j][1]
3798 vcgt_ramp[k][j] = vcgt_value
3799 # Some video drivers won't reload gamma ramps if
3800 # the previously loaded calibration was the same.
3801 # Work-around by first loading a slightly changed
3802 # gamma ramp.
3803 if j == 0:
3804 vcgt_value += 1
3805 vcgt_ramp_hack[k][j] = vcgt_value
3806 self.ramps[self._reset_gamma_ramps or key] = (
3807 vcgt_ramp,
3808 vcgt_ramp_hack,
3809 vcgt_values,
3810 )
3811 recheck = True
3812 return recheck, vcgt_ramp, vcgt_ramp_hack, vcgt_values
3813
3814 def _retrieve_profile_vcgt(
3815 self,
3816 key: str,
3817 profile_name: str,
3818 ) -> tuple[tuple[list[float], list[float], list[float]], None | ICCProfile]:
3819 """Retrieve the VCGT values from the profile.
3820
3821 Args:
3822 key (str): The key for the profile.
3823 profile_name (str): The name of the profile.
3824 """
3825 vcgt_values = ([], [], [])
3826 # in the pre-refactored code at this point the `profile` variable is
3827 # undefined, so we need to define it here to avoid UnboundLocalError.
3828 # and trust that it will be properly set later in the code.
3829 profile = None
3830 if self._reset_gamma_ramps:
3831 return vcgt_values, profile
3832
3833 # Get display profile
3834 if not self.profiles.get(key):
3835 try:
3836 self.profiles[key] = ICCProfile(profile_name)
3837 if (
3838 isinstance(
3839 self.profiles[key].tags.get("MS00"),
3840 WcsProfilesTagType,
3841 )
3842 and "vcgt" not in self.profiles[key].tags
3843 ):
3844 self.profiles[key].tags["vcgt"] = (
3845 self.profiles[key].tags["MS00"].get_vcgt()
3846 )
3847 self.profiles[key].tags.get("vcgt")
3848 except Exception as exception:
3849 print(exception)
3850 self.profiles[key] = ICCProfile()
3851 profile = self.profiles[key]
3852 if isinstance(profile.tags.get("vcgt"), VideoCardGammaType):
3853 # Get display profile vcgt
3854 vcgt_values = profile.tags.vcgt.get_values()[:3]
3855 # Quantize to n bits
3856 # 8 bits can be encoded accurately in a 256-entry
3857 # 16 bit vcgt, but all other bitdepths need to be
3858 # quantized in such a way that the encoded 16-bit
3859 # values lie as close as possible to the ideal ones.
3860 # We assume the graphics subsystem quantizes using
3861 # integer truncating from the 16 bit encoded value
3862 if self._quantize < 65535.0:
3863 smooth = str(getcfg("profile_loader.quantize_bits")) in getcfg(
3864 "profile_loader.smooth_bits"
3865 ).split(";")
3866 smooth_window = (0.5, 1, 1, 1, 0.5)
3867 for points in vcgt_values:
3868 quantized = [
3869 round(point[1] / 65535.0 * self._quantize) for point in points
3870 ]
3871 if smooth:
3872 # Smooth and round to nearest again
3873 quantized = [
3874 round(v) for v in smooth_avg(quantized, 1, smooth_window)
3875 ]
3876 for k, point in enumerate(points):
3877 point[1] = math.ceil(quantized[k] / self._quantize * 65535)
3878
3879 return vcgt_values, profile
3880
3881 def _track_process_changes(
3882 self,
3883 previous_hwnds_pids: set[tuple[int, int]],
3884 ) -> bool:
3885 """Track changes in running processes.
3886
3887 Args:
3888 previous_hwnds_pids (set[tuple[int, int]]): Previous set of HWND
3889 and PID tuples.
3890 """
3891 if not getcfg("profile_loader.track_other_processes"):
3892 return getcfg("profile_loader.ignore_unchanged_gamma_ramps")
3893
3894 hwnds_pids_changed = self._hwnds_pids != previous_hwnds_pids
3895 if hwnds_pids_changed and previous_hwnds_pids:
3896 debug_print("List of running processes changed")
3897 hwnds_pids_diff = previous_hwnds_pids.difference(self._hwnds_pids)
3898 if hwnds_pids_diff:
3899 debug_print("Gone processes:")
3900 for hwnd_pid in hwnds_pids_diff:
3901 debug_print(*hwnd_pid)
3902 hwnds_pids_diff = self._hwnds_pids.difference(previous_hwnds_pids)
3903 if hwnds_pids_diff:
3904 debug_print("New processes:")
3905 for hwnd_pid in hwnds_pids_diff:
3906 debug_print(*hwnd_pid)
3907
3908 return hwnds_pids_changed
3909
3910 def _check_gamma_ramp_status(
3911 self,
3912 display: str,
3913 idle: bool,
3914 i: int,
3915 moninfo: dict,
3916 display_desc: str,
3917 key: str,
3918 profile_association_changed: bool,
3919 apply_profiles: bool,
3920 vcgt_values: tuple[list[float], list[float], list[float]],
3921 hwnds_pids_changed: bool,
3922 ) -> tuple[bool, bool]:
3923 """Check the gamma ramp status.
3924
3925 Args:
3926 display (str): Display identifier.
3927 idle (bool): Indicates if the system is idle.
3928 i (int): Monitor index.
3929 moninfo (dict): Monitor information.
3930 display_desc (str): Display description.
3931 key (str): Profile key.
3932 profile_association_changed (bool): Indicates if profile
3933 association changed.
3934 apply_profiles (bool): Indicates if profiles should be applied.
3935 vcgt_values (tuple[list[float], list[float], list[float]]): VCGT values.
3936 hwnds_pids_changed (bool): Indicates if HWNDs and PIDs have changed.
3937
3938 Returns:
3939 tuple[bool, bool]: Updated idle status and a flag indicating
3940 whether to continue.
3941 """
3942 if (
3943 not self._manual_restore
3944 and not profile_association_changed
3945 and (idle or self.__other_component[1] == "madHcNetQueueWindow")
3946 and getcfg("profile_loader.check_gamma_ramps")
3947 ):
3948 # Get video card gamma ramp
3949 try:
3950 hdc = win32gui.CreateDC(moninfo["Device"], None, None)
3951 except Exception as exception:
3952 if exception.args != self._last_exception_args or DEBUG:
3953 self._last_exception_args = exception.args
3954 print(
3955 "Couldn't create DC for",
3956 moninfo["Device"],
3957 f"({display})",
3958 )
3959 # continue
3960 return idle, True
3961
3962 ramp: ctypes.c_ushort_Array_256_Array_3 = ((ctypes.c_ushort * 256) * 3)()
3963 try:
3964 result = self.gdi32.GetDeviceGammaRamp(hdc, ramp)
3965 except Exception as e:
3966 print("Handled exception:", e)
3967 # continue
3968 return idle, True
3969 finally:
3970 win32gui.DeleteDC(hdc)
3971
3972 if not result:
3973 # continue
3974 return idle, True
3975
3976 ramp_values, do_return = self._get_ramp_values(
3977 ramp, key, display, i, vcgt_values
3978 )
3979 if do_return:
3980 return idle, True
3981
3982 # Check if video card matches profile vcgt
3983 if (
3984 not hwnds_pids_changed
3985 and ramp_values == vcgt_values
3986 and i in self.setgammaramp_success
3987 ):
3988 idle = True
3989 # continue
3990 return idle, True
3991
3992 idle = False
3993 if apply_profiles and not hwnds_pids_changed:
3994 print(lang.getstr("vcgt.mismatch", display_desc))
3995 return idle, False
3996
3997 def _get_ramp_values(
3998 self,
3999 ramp: ctypes.c_ushort_Array_256_Array_3,
4000 key: str,
4001 display: str,
4002 i: int,
4003 vcgt_values: tuple[list[float], list[float], list[float]],
4004 ) -> tuple[list, bool]:
4005 # Get ramp values
4006 values = ([], [], [])
4007 for j, channel in enumerate(ramp):
4008 for k, v in enumerate(channel):
4009 values[j].append([float(k), v])
4010 if self.__other_component[1] == "madHcNetQueueWindow":
4011 madvr_reset_cal = self._madvr_reset_cal.get(key, True)
4012 if not madvr_reset_cal and values == self.linear_vcgt_values:
4013 # madVR has reset vcgt
4014 self._madvr_reset_cal[key] = True
4015 print(
4016 f"madVR did reset gamma ramps for {display}, "
4017 "do not preserve calibration state"
4018 )
4019 elif (
4020 madvr_reset_cal
4021 and values == vcgt_values
4022 and values != self.linear_vcgt_values
4023 ):
4024 # madVR did not reset vcgt
4025 self._madvr_reset_cal[key] = False
4026 print(
4027 f"madVR did not reset gamma ramps for {display}, "
4028 "preserve calibration state"
4029 )
4030 self.setgammaramp_success[i] = True
4031 if self._madvr_reset_cal.get(key, True) != madvr_reset_cal:
4032 if self._madvr_reset_cal.get(key, True):
4033 msg = lang.getstr(
4034 "app.detected.calibration_loading_disabled",
4035 self._component_name,
4036 )
4037 self.notify([msg], [], True, False)
4038 # continue
4039 return None, True
4040 self.notify([], [], True, False)
4041 return values, False
4042
4043 def _reload_or_reset_calibration(
4044 self,
4045 display: str,
4046 display_desc: str,
4047 profile_association_changed: bool,
4048 desc: str,
4049 hwnds_pids_changed: bool,
4050 ) -> None:
4051 """Reload or reset calibration.
4052
4053 Args:
4054 display (str): Display identifier.
4055 display_desc (str): Display description.
4056 profile_association_changed (bool): Indicates if profile
4057 association changed.
4058 desc (str): Profile description.
4059 hwnds_pids_changed (bool): Indicates if the list of
4060 running processes changed.
4061 """
4062 if (
4063 self._manual_restore
4064 or profile_association_changed
4065 or (not hwnds_pids_changed and getcfg("profile_loader.check_gamma_ramps"))
4066 ):
4067 if self._reset_gamma_ramps:
4068 print(lang.getstr("calibration.resetting"))
4069 print(display_desc)
4070 else:
4071 print(lang.getstr("calibration.loading_from_display_profile"))
4072 print(f"{display_desc}:", desc)
4073 elif VERBOSE > 1 and getcfg("profile_loader.track_other_processes"):
4074 print("Preserving calibration state for display", display)
4075
4076 def _handle_profile_updates(
4077 self,
4078 first_run: bool,
4079 apply_profiles: bool,
4080 displaycal_running: bool,
4081 results: list[str],
4082 errors: list[str],
4083 idle: bool,
4084 profile_associations_changed: bool,
4085 ) -> None:
4086 """Handle profile updates and notify user.
4087
4088 Args:
4089 first_run (bool): Indicates if this is the first run.
4090 apply_profiles (bool): Indicates if profiles should be applied.
4091 displaycal_running (bool): Indicates if DisplayCAL is running.
4092 results (list): List to store result messages.
4093 errors (list): List to store error messages.
4094 idle (bool): Indicates if the system is idle.
4095 profile_associations_changed (bool): Indicates if profile
4096 associations changed.
4097 """
4098 if results or errors:
4099 if results:
4100 self.reload_count += 1
4101 lstr = (
4102 "calibration.reset_success"
4103 if self._reset_gamma_ramps
4104 else "calibration.load_success"
4105 )
4106 results.insert(0, lang.getstr(lstr))
4107 if self._app_detection_msg:
4108 results.insert(0, self._app_detection_msg)
4109 self._app_detection_msg = None
4110 self.notify(
4111 results,
4112 errors,
4113 show_notification=bool(not first_run or errors)
4114 and self.__other_component[1] != "madHcNetQueueWindow",
4115 )
4116 else:
4117 # if (apply_profiles != self.__apply_profiles or
4118 # profile_associations_changed):
4119 if (
4120 not idle
4121 and apply_profiles
4122 and (not profile_associations_changed or not self._reset_gamma_ramps)
4123 ):
4124 self.reload_count += 1
4125 if displaycal_running != self._is_displaycal_running():
4126 msg = lang.getstr(
4127 "app.detection_lost.calibration_loading_enabled"
4128 if displaycal_running
4129 else "app.detected.calibration_loading_disabled",
4130 APPNAME,
4131 )
4132 displaycal_running = self._is_displaycal_running()
4133 print(msg)
4134 self.notify([msg], [], displaycal_running, show_notification=False)
4135 elif (
4136 apply_profiles != self.__apply_profiles or profile_associations_changed
4137 ):
4138 wx.CallAfter(lambda: self and self.taskbar_icon.set_visual_state())
4139
4140 def shutdown(self) -> None:
4141 """Shut down the profile loader."""
4142 if self._shutdown:
4143 return
4144 self._shutdown = True
4145 print("Shutting down profile loader")
4146 if self.monitoring:
4147 print("Shutting down display configuration monitoring thread")
4148 self.monitoring = False
4149 if getcfg("profile_loader.fix_profile_associations"):
4150 self._reset_display_profile_associations()
4151 self.writecfg()
4152 if getattr(self, "taskbar_icon", None):
4153 if self.taskbar_icon.menu:
4154 self.taskbar_icon.menu.Destroy()
4155 self.taskbar_icon.RemoveIcon()
4156 if getattr(self, "frame", None):
4157 self.frame.listening = False
4158
4159 def _enumerate_monitors(self) -> None:
4160 """Enumerate display adapters and devices."""
4161 print("-" * 80)
4162 print("Enumerating display adapters and devices:")
4163 print("")
4164 self.adapters = {
4165 device.DeviceName: device for device in get_display_devices(None)
4166 }
4167 self.monitors = []
4168 self.display_devices = {}
4169 self.child_devices_count = {}
4170 # Enumerate per-adapter devices
4171 for adapter in self.adapters:
4172 for i, device in enumerate(get_display_devices(adapter)):
4173 if not i:
4174 device0 = device
4175 if device.DeviceKey in self.display_devices:
4176 continue
4177 display, edid = get_display_name_edid(device)
4178 self.display_devices[device.DeviceKey] = [
4179 display,
4180 edid,
4181 device,
4182 device0,
4183 ]
4184 # Enumerate monitors
4185 try:
4186 monitors = get_real_display_devices_info()
4187 except Exception:
4188 import traceback
4189
4190 print(traceback.format_exc())
4191 monitors = []
4192 self.setgammaramp_success[0] = False
4193 self._active_displays = []
4194 self._process_monitor_info(monitors)
4195 self._print_display_device_info()
4196
4197 def _process_monitor_info(self, monitors: list[dict]) -> None:
4198 """Process monitor information.
4199
4200 Args:
4201 monitors (list[dict]): List of monitor information dictionaries.
4202 """
4203 for i, moninfo in enumerate(monitors):
4204 if moninfo["Device"] == "WinDisc":
4205 # If e.g. we physically disconnect the display device, we will
4206 # get a 'WinDisc' temporary monitor we cannot do anything with
4207 # (MS, why is this not documented?)
4208 print(f"Skipping 'WinDisc' temporary monitor {i:d}")
4209 continue
4210 moninfo["_adapter"] = self.adapters.get(
4211 moninfo["Device"], ADict({"DeviceString": moninfo["Device"][4:]})
4212 )
4213 if self._is_buggy_video_driver(moninfo):
4214 print(
4215 "Buggy video driver detected: {}.".format(
4216 moninfo["_adapter"].DeviceString
4217 ),
4218 "Gamma ramp hack activated.",
4219 )
4220 device = get_active_display_device(moninfo["Device"])
4221 if device:
4222 self._active_displays.append(device.DeviceKey)
4223 debug_print(
4224 "Found monitor {:d} {} flags 0x{:x}".format(
4225 i, moninfo["Device"], moninfo["Flags"]
4226 )
4227 )
4228 if device:
4229 debug_print(
4230 f"Monitor {i:d} active display device name:", device.DeviceName
4231 )
4232 debug_print(
4233 f"Monitor {i:d} active display device string:",
4234 device.DeviceString,
4235 )
4236 debug_print(
4237 f"Monitor {i:d} active display device state flags: "
4238 f"0x{device.StateFlags:x}"
4239 )
4240 debug_print(f"Monitor {i:d} active display device ID:", device.DeviceID)
4241 debug_print(
4242 f"Monitor {i:d} active display device key:", device.DeviceKey
4243 )
4244 else:
4245 debug_print(f"WARNING: Monitor {i:d} has no active display device")
4246 # Get monitor descriptive string
4247 display, edid = get_display_name_edid(device, moninfo, i)
4248 debug_print(f"Monitor {i:d} active display description:", display)
4249 debug_print(
4250 "Enumerating 1st display device for monitor {:d} {}".format(
4251 i, moninfo["Device"]
4252 )
4253 )
4254 try:
4255 device0 = win32api.EnumDisplayDevices(moninfo["Device"], 0)
4256 except pywintypes.error as exception:
4257 print(
4258 f"EnumDisplayDevices({moninfo['Device']!r}, 0) failed:",
4259 exception,
4260 )
4261 device0 = None
4262 if device0:
4263 debug_print(
4264 f"Monitor {i:d} 1st display device name:", device0.DeviceName
4265 )
4266 debug_print(
4267 f"Monitor {i:d} 1st display device string:", device0.DeviceString
4268 )
4269 debug_print(
4270 f"Monitor {i:d} 1st display device state flags: "
4271 f"0x{device0.StateFlags:x}"
4272 )
4273 debug_print(f"Monitor {i:d} 1st display device ID:", device0.DeviceID)
4274 debug_print(
4275 f"Monitor {i:d} 1st display device key:", device0.DeviceKey
4276 )
4277 display0, edid0 = get_display_name_edid(device0)
4278 debug_print(f"Monitor {i:d} 1st display description:", display0)
4279 if (
4280 device0
4281 and (not device or device0.DeviceKey != device.DeviceKey)
4282 and device0.DeviceKey not in self.display_devices
4283 ):
4284 # Key may not exist if device was added after enumerating
4285 # per-adapters devices
4286 self.display_devices[device0.DeviceKey] = [
4287 display0,
4288 edid0,
4289 device0,
4290 device0,
4291 ]
4292 if device:
4293 if device.DeviceKey in self.display_devices:
4294 self.display_devices[device.DeviceKey][0] = display
4295 else:
4296 # Key may not exist if device was added after enumerating
4297 # per-adapters devices
4298 self.display_devices[device.DeviceKey] = [
4299 display,
4300 edid,
4301 device,
4302 device0,
4303 ]
4304 self.monitors.append((display, edid, moninfo, device))
4305
4306 def _print_display_device_info(self) -> None:
4307 """Print information about display devices."""
4308 for display, _edid, device, device0 in self.display_devices.values():
4309 if device0 and device.DeviceKey == device0.DeviceKey:
4310 device_name = "\\".join(device.DeviceName.split("\\")[:-1])
4311 print(
4312 self.adapters.get(
4313 device_name, ADict({"DeviceString": device_name[4:]})
4314 ).DeviceString
4315 )
4316 display_parts = display.split("@", 1)
4317 if len(display_parts) > 1:
4318 info = display_parts[1].split(" - ", 1)
4319 display_parts[1] = "@" + " ".join(info[:1])
4320 if not device.StateFlags & DISPLAY_DEVICE_ACTIVE:
4321 display_parts.append(" ({})".format(lang.getstr("deactivated")))
4322 print(" |-", "".join(display_parts))
4323
4324 def _enumerate_windows_callback(self, hwnd: int, extra: object) -> None:
4325 """Callback for enumerating windows.
4326
4327 Args:
4328 hwnd (int): Handle to the window.
4329 extra (object): Extra parameter (not used).
4330 """
4331 cls = win32gui.GetClassName(hwnd)
4332 if cls == "madHcNetQueueWindow" or self._is_known_window_class(cls):
4333 try:
4334 thread_id, pid = win32process.GetWindowThreadProcessId(hwnd)
4335 filename: str = get_process_filename(pid)
4336 except pywintypes.error:
4337 return
4338 self._hwnds_pids.add((filename, pid, thread_id, hwnd))
4339 basename = os.path.basename(filename)
4340 if basename.lower() != "madhcctrl.exe" and pid != self._pid:
4341 self.__other_component = filename, cls, 0
4342
4343 def _is_known_window_class(self, cls: type) -> bool:
4344 """Check if the window class is known and should be monitored.
4345
4346 Args:
4347 cls (type): The window class to check.
4348
4349 Returns:
4350 bool: True if the window class is known, False otherwise.
4351 """
4352 return any(partial in cls for partial in self._known_window_classes)
4353
4354 def _is_buggy_video_driver(self, moninfo: dict) -> bool:
4355 """Check if the video driver is buggy and requires a gamma ramp hack.
4356
4357 Args:
4358 moninfo (dict): Monitor information dictionary containing adapter
4359 info.
4360
4361 Returns:
4362 bool: True if the video driver is buggy, False otherwise.
4363 """
4364 # Intel video drivers won't reload gamma ramps if the
4365 # previously loaded calibration was the same.
4366 # Work-around by first loading a slightly changed
4367 # gamma ramp.
4368 adapter = moninfo["_adapter"].DeviceString.lower()
4369 for buggy_video_driver in self._buggy_video_drivers:
4370 if buggy_video_driver == "*" or buggy_video_driver in adapter:
4371 return True
4372 return False
4373
4374 def _is_displaycal_running(self) -> bool:
4375 """Check if DisplayCAL is running by looking for its lock file.
4376
4377 Returns:
4378 bool: True if DisplayCAL is running, False otherwise.
4379 """
4380 displaycal_lockfile = os.path.join(CONFIG_HOME, APPBASENAME + ".lock")
4381 return os.path.isfile(displaycal_lockfile)
4382
4383 def _is_other_running(
4384 self,
4385 enumerate_windows_and_processes: bool = True,
4386 ) -> bool:
4387 """Determine if other software that may be using the videoLUT is in use.
4388
4389 (e.g. madVR video playback, madTPG, other calibration software)
4390
4391 Args:
4392 enumerate_windows_and_processes (bool): Whether to enumerate
4393 windows and processes to determine if other software is
4394 running. This should be True at launch, and False when called
4395 from the madVR callback.
4396
4397 Returns:
4398 bool: True if other software is running, False otherwise.
4399 """
4400 if sys.platform != "win32":
4401 return None
4402 self._is_other_running_lock.acquire()
4403 if enumerate_windows_and_processes:
4404 # At launch, we won't be able to determine if madVR is running via
4405 # the callback API, and we can only determine if another
4406 # calibration solution is running by enumerating windows and
4407 # processes anyway.
4408 other_component = self.__other_component
4409 self.__other_component = None, None, 0
4410 # Look for known window classes
4411 # Performance on C2D 3.16 GHz (Win7 x64, ~ 90 processes): ~ 1ms
4412 self._hwnds_pids = set()
4413 try:
4414 win32gui.EnumWindows(self._enumerate_windows_callback, None)
4415 except pywintypes.error as exception:
4416 print("Enumerating windows failed:", exception)
4417 if (
4418 not self.__other_component[1]
4419 or self.__other_component[1] == "madHcNetQueueWindow"
4420 ):
4421 self._look_for_known_processes(other_component)
4422 if other_component != self.__other_component:
4423 self._handle_component_detection(other_component)
4424 result = (
4425 self.__other_component[0:2] != (None, None)
4426 and not self.__other_component[2]
4427 )
4428 self._is_other_running_lock.release()
4429 if self.__other_component[1] == "madHcNetQueueWindow":
4430 if enumerate_windows_and_processes:
4431 # Check if gamma ramps were reset for current display
4432 return self._madvr_reset_cal.get(self._current_display_key, True)
4433 # Check if gamma ramps were reset for any display
4434 return len(self._madvr_reset_cal) < len(self.monitors) or True in list(
4435 self._madvr_reset_cal.values()
4436 )
4437 return result
4438
4439 def _look_for_known_processes(
4440 self, other_component: tuple[None | str, None | str, int]
4441 ) -> None:
4442 """Look for known processes that may be using the videoLUT.
4443
4444 Args:
4445 other_component (tuple): A tuple containing the filename,
4446 window class, and reset flag of the other component.
4447 """
4448 # Look for known processes
4449 # Performance on C2D 3.16 GHz (Win7 x64, ~ 90 processes):
4450 # ~ 6-9ms (1ms to get PIDs)
4451 try:
4452 processes = win32ts.WTSEnumerateProcesses()
4453 except pywintypes.error as exception:
4454 print("Enumerating processes failed:", exception)
4455 return
4456
4457 skip = False
4458 for _session_id, pid, basename, user_security_id in processes:
4459 name_lower = basename.lower()
4460 if name_lower != "madhcctrl.exe":
4461 # Add all processes except madVR Home Cinema Control
4462 self._hwnds_pids.add((basename, pid))
4463 if skip or not user_security_id:
4464 # Skip detection if other component already detected
4465 # or no user security ID (if no user SID, it's a
4466 # system process and we cannot get process filename
4467 # due to access restrictions)
4468 continue
4469 known_app = name_lower in self._known_apps
4470 has_exception = name_lower in self._exception_names
4471 if not (known_app or has_exception):
4472 continue
4473 try:
4474 filename = get_process_filename(pid)
4475 except (OSError, pywintypes.error) as exception:
4476 if exception.args[0] not in (
4477 winerror.ERROR_ACCESS_DENIED,
4478 winerror.ERROR_PARTIAL_COPY,
4479 winerror.ERROR_INVALID_PARAMETER,
4480 winerror.ERROR_GEN_FAILURE,
4481 ):
4482 print(
4483 f"Couldn't get filename of process {pid}:",
4484 exception,
4485 )
4486 continue
4487 enabled, reset, path = self._exceptions.get(filename.lower(), (0, 0, ""))
4488 if known_app or enabled:
4489 if known_app or not reset:
4490 self.__other_component = filename, None, 0
4491 skip = True
4492 elif other_component != (filename, None, reset):
4493 self._reset_gamma_ramps = True
4494 self.__other_component = filename, None, reset
4495
4496 def _handle_component_detection(
4497 self,
4498 other_component: tuple[None | str, None | str, int],
4499 ) -> None:
4500 """Handle detection of other software using the videoLUT.
4501
4502 Args:
4503 other_component (tuple): A tuple containing the filename,
4504 window class, and reset flag of the other component.
4505 """
4506 if other_component[2] and not self.__other_component[2]:
4507 self._reset_gamma_ramps = bool(
4508 config.getcfg("profile_loader.reset_gamma_ramps")
4509 )
4510 check = (not other_component[2] and not self.__other_component[2]) or (
4511 other_component[2]
4512 and self.__other_component[0:2] != (None, None)
4513 and not self.__other_component[2]
4514 )
4515 if check:
4516 if self.__other_component[0:2] == (None, None):
4517 lstr = "app.detection_lost.calibration_loading_enabled"
4518 component = other_component
4519 sticky = False
4520 else:
4521 lstr = "app.detected.calibration_loading_disabled"
4522 component = self.__other_component
4523 sticky = True
4524 elif self.__other_component[0:2] != (None, None):
4525 lstr = "app.detected"
4526 component = self.__other_component
4527 else:
4528 lstr = "app.detection_lost"
4529 component = other_component
4530 if component[1] == "madHcNetQueueWindow":
4531 component_name = "madVR"
4532 self._madvr_reset_cal = {}
4533 elif component[0]:
4534 component_name = os.path.basename(component[0])
4535 try:
4536 info = list(get_file_info(component[0])["StringFileInfo"].values())
4537 except Exception:
4538 info = None
4539 if info:
4540 # Use FileDescription over ProductName (the former may
4541 # be more specific, e.g. Windows Display Color
4542 # Calibration, the latter more generic, e.g. Microsoft
4543 # Windows)
4544 component_name = info[0].get(
4545 "FileDescription",
4546 info[0].get("ProductName", component_name),
4547 )
4548 else:
4549 component_name = lang.getstr("unknown")
4550 if self.__other_component[0:2] != (None, None):
4551 self._component_name = component_name
4552 else:
4553 self._component_name = None
4554 msg = lang.getstr(lstr, component_name)
4555 print(msg)
4556 if check:
4557 self.notify([msg], [], sticky, show_notification=component_name != "madVR")
4558 else:
4559 self._app_detection_msg = msg
4560 self._manual_restore = getcfg("profile.load_on_login") and 2
4561
4562 def _madvr_connection_callback(
4563 self,
4564 param: int,
4565 connection: object,
4566 ip: str,
4567 pid: int,
4568 module: str,
4569 component: str,
4570 instance: int,
4571 is_new_instance: bool,
4572 ) -> None:
4573 """Callback for madVR connection events.
4574
4575 Args:
4576 param (int): Parameter passed to the callback.
4577 connection (object): Connection object.
4578 ip (str): IP address of the madVR instance.
4579 pid (int): Process ID of the madVR instance.
4580 module (str): Module name of the madVR instance.
4581 component (str): Component name of the madVR instance.
4582 instance (int): Instance number of the madVR instance.
4583 is_new_instance (bool): True if this is a new madVR instance, False
4584 if it is a disconnection.
4585 """
4586 if self.lock.locked():
4587 print("Waiting to acquire lock...")
4588 with self.lock:
4589 print("Acquired lock")
4590 if ip not in ("127.0.0.1", "localhost", "::1", "0:0:0:0:0:0:0:1"):
4591 print("Releasing lock")
4592 return
4593 args = (param, connection, ip, pid, module, component, instance)
4594 try:
4595 filename = get_process_filename(pid)
4596 except Exception:
4597 filename = lang.getstr("unknown")
4598 if is_new_instance:
4599 apply_profiles = self._should_apply_profiles(manual_override=None)
4600 self._madvr_instances.append(args)
4601 self.__other_component = filename, "madHcNetQueueWindow", 0
4602 print("madVR instance connected:", "PID", pid, filename)
4603 if apply_profiles:
4604 msg = lang.getstr(
4605 "app.detected.calibration_loading_disabled", component
4606 )
4607 print(msg)
4608 self.notify([msg], [], True, show_notification=False)
4609 wx.CallAfter(wx.CallLater, 1500, self._check_madvr_reset_cal, args)
4610 elif args in self._madvr_instances:
4611 self._madvr_instances.remove(args)
4612 print("madVR instance disconnected:", "PID", pid, filename)
4613 if not self._madvr_instances and self._should_apply_profiles(
4614 manual_override=None
4615 ):
4616 msg = lang.getstr(
4617 "app.detection_lost.calibration_loading_enabled", component
4618 )
4619 print(msg)
4620 self.notify([msg], [], show_notification=False)
4621 print("Releasing lock")
4622
4623 def _check_madvr_reset_cal(self, madvr_instance: tuple) -> None:
4624 """Check if madVR reset the video card gamma tables.
4625
4626 Args:
4627 madvr_instance (tuple): A tuple containing madVR instance details
4628 (param, connection, ip, pid, module, component, instance).
4629 """
4630 if madvr_instance not in self._madvr_instances:
4631 return
4632 # Check if madVR did reset the video card gamma tables.
4633 # If it didn't, assume we can keep preserving calibration state
4634 with self.lock:
4635 self._next = True
4636
4637 def _reset_display_profile_associations(self) -> None:
4638 """Reset display profile associations for all monitors."""
4639 if not self._can_fix_profile_associations():
4640 return
4641 for devicekey in self.devices2profiles:
4642 display_edid, profile, desc = self.devices2profiles[devicekey]
4643 if devicekey not in self._fixed_profile_associations or not profile:
4644 continue
4645 try:
4646 current_profile = get_display_profile(
4647 path_only=True, devicekey=devicekey
4648 )
4649 except Exception as exception:
4650 print(
4651 "Could not get display profile for display "
4652 f"device {devicekey} ({display_edid[0]}):",
4653 exception,
4654 )
4655 continue
4656 if not current_profile:
4657 continue
4658 current_profile = os.path.basename(current_profile)
4659 if not current_profile or current_profile == profile:
4660 continue
4661 print(
4662 f"Resetting profile association for {display_edid[0]}:",
4663 current_profile,
4664 "->",
4665 profile,
4666 )
4667 try:
4668 if not is_superuser() and not per_user_profiles_isenabled(
4669 devicekey=devicekey
4670 ):
4671 # Can only associate profiles to the display if
4672 # per-user-profiles are enabled or if running as admin
4673 enable_per_user_profiles(devicekey=devicekey)
4674 set_display_profile(profile, devicekey=devicekey)
4675 unset_display_profile(current_profile, devicekey=devicekey)
4676 except OSError as exception:
4677 print(exception)
4678
4679 def _set_display_profiles(self, dry_run: bool = False) -> None:
4680 """Set display profiles for all monitors.
4681
4682 Args:
4683 dry_run (bool): If True, do not actually set the profiles.
4684 """
4685 if not self._can_fix_profile_associations():
4686 return
4687 debug_print("-" * 80)
4688 debug_print("Checking profile associations")
4689 debug_print("")
4690 self.devices2profiles = {}
4691 for i, (display, _edid, moninfo, _device) in enumerate(self.monitors):
4692 debug_print(
4693 f"Enumerating display devices for monitor {i:d} {moninfo['Device']}"
4694 )
4695 devices = get_display_devices(moninfo["Device"])
4696 if not devices:
4697 debug_print(f"WARNING: Monitor {i:d} has no display devices")
4698 continue
4699 active_device = get_active_display_device(None, devices=devices)
4700 self._log_active_device_info(i, active_device)
4701 self._map_device_to_profile(moninfo, devices, active_device)
4702 self._set_active_profile(active_device, display, devices, dry_run)
4703
4704 def _log_active_device_info(self, i: int, active_device: PyDISPLAY_DEVICE) -> None:
4705 """Log information about the active display device.
4706
4707 Args:
4708 i (int): Monitor index.
4709 active_device (PyDISPLAY_DEVICE): The active display device.
4710 """
4711 if active_device:
4712 debug_print(
4713 f"Monitor {i:d} active display device name:",
4714 active_device.DeviceName,
4715 )
4716 debug_print(
4717 f"Monitor {i:d} active display device string:",
4718 active_device.DeviceString,
4719 )
4720 debug_print(
4721 f"Monitor {i:d} active display device state flags: "
4722 f"0x{active_device.StateFlags:x}"
4723 )
4724 debug_print(
4725 f"Monitor {i:d} active display device ID:",
4726 active_device.DeviceID,
4727 )
4728 debug_print(
4729 f"Monitor {i:d} active display device key:",
4730 active_device.DeviceKey,
4731 )
4732 else:
4733 debug_print(f"WARNING: Monitor {i:d} has no active display device")
4734
4735 def _map_device_to_profile(
4736 self,
4737 moninfo: PyDISPLAY_DEVICE,
4738 devices: list[PyDISPLAY_DEVICE],
4739 active_device: PyDISPLAY_DEVICE,
4740 ) -> None:
4741 """Map display devices to their profiles.
4742
4743 Args:
4744 moninfo (PyDISPLAY_DEVICE): Monitor information.
4745 devices: List of display devices.
4746 active_device: The active display device.
4747 """
4748 for device in devices:
4749 if active_device and device.DeviceID == active_device.DeviceID:
4750 active_moninfo = moninfo
4751 else:
4752 active_moninfo = None
4753 display_edid = get_display_name_edid(device, active_moninfo)
4754 try:
4755 profile = get_display_profile(
4756 path_only=True, devicekey=device.DeviceKey
4757 )
4758 except Exception as exception:
4759 print(
4760 "Could not get display profile for display "
4761 f"device {device.DeviceKey} ({display_edid[0]}):",
4762 exception,
4763 )
4764 profile = None
4765 if profile:
4766 profile = os.path.basename(profile)
4767 self.devices2profiles[device.DeviceKey] = (
4768 display_edid,
4769 profile,
4770 get_profile_desc(profile),
4771 )
4772 debug_print(f"{display_edid[0]} ({device.DeviceKey}): {profile}")
4773
4774 def _set_active_profile(
4775 self,
4776 active_device: PyDISPLAY_DEVICE,
4777 display: str,
4778 devices: list[PyDISPLAY_DEVICE],
4779 dry_run: bool = False,
4780 ) -> None:
4781 """Set the active profile for a display device.
4782
4783 Args:
4784 active_device (PyDISPLAY_DEVICE): The active display device.
4785 display (str): The display name.
4786 devices (list[PyDISPLAY_DEVICE]): List of display devices.
4787 dry_run (bool): If True, do not actually set the profile.
4788 """
4789 # Set the active profile
4790 device = active_device
4791 if not device:
4792 return
4793 try:
4794 correct_profile = get_display_profile(
4795 path_only=True, devicekey=device.DeviceKey
4796 )
4797 except Exception as exception:
4798 print(
4799 "Could not get display profile for active display "
4800 f"device {device.DeviceKey} ({display}):",
4801 exception,
4802 )
4803 return
4804 if correct_profile:
4805 correct_profile = os.path.basename(correct_profile)
4806 device = devices[0]
4807 current_profile = self.devices2profiles[device.DeviceKey][1]
4808 if correct_profile and current_profile != correct_profile and not dry_run:
4809 print(
4810 f"Fixing profile association for {display}:",
4811 current_profile,
4812 "->",
4813 correct_profile,
4814 )
4815 try:
4816 if not is_superuser() and not per_user_profiles_isenabled(
4817 devicekey=device.DeviceKey
4818 ):
4819 # Can only associate profiles to the display if
4820 # per-user-profiles are enabled or if running as admin
4821 enable_per_user_profiles(devicekey=device.DeviceKey)
4822 set_display_profile(
4823 os.path.basename(correct_profile), devicekey=device.DeviceKey
4824 )
4825 except OSError as exception:
4826 print(exception)
4827 else:
4828 self._fixed_profile_associations.add(device.DeviceKey)
4829
4830 def _set_manual_restore(self, event: wx.Event, manual_restore: bool = True) -> None:
4831 """Set the manual restore state for profile loading.
4832
4833 Args:
4834 event (wx.Event): The event that triggered this method.
4835 manual_restore (bool): Whether to set the manual restore state.
4836 """
4837 if event:
4838 print("Menu command:", end=" ")
4839 print("Set calibration state to load profile vcgt")
4840 if self.lock.locked():
4841 print("Waiting to acquire lock...")
4842 with self.lock:
4843 print("Acquired lock")
4844 setcfg("profile_loader.reset_gamma_ramps", 0)
4845 self._manual_restore = manual_restore
4846 self._reset_gamma_ramps = False
4847 print("Releasing lock")
4848 self.taskbar_icon.set_visual_state()
4849 self.writecfg()
4850
4851 def _set_reset_gamma_ramps(
4852 self, event: wx.Event, manual_restore: bool = True
4853 ) -> None:
4854 """Set the calibration state to reset video card gamma ramps.
4855
4856 Args:
4857 event (wx.Event): The event that triggered this method.
4858 manual_restore (bool): Whether to set the manual restore state.
4859 """
4860 if event:
4861 print("Menu command:", end=" ")
4862 print("Set calibration state to reset vcgt")
4863 if self.lock.locked():
4864 print("Waiting to acquire lock...")
4865 with self.lock:
4866 print("Acquired lock")
4867 setcfg("profile_loader.reset_gamma_ramps", 1)
4868 self._manual_restore = manual_restore
4869 self._reset_gamma_ramps = True
4870 print("Releasing lock")
4871 self.taskbar_icon.set_visual_state()
4872 self.writecfg()
4873
4874 def _should_apply_profiles(
4875 self,
4876 enumerate_windows_and_processes: bool = True,
4877 manual_override: int = 2,
4878 ) -> bool:
4879 """Determine if profiles should be applied.
4880
4881 Args:
4882 enumerate_windows_and_processes (bool, optional): Whether to
4883 enumerate windows and processes to check if other software is
4884 running.
4885 manual_override (int, optional): Manual override for profile
4886 loading state:
4887
4888 0: Do not load profiles
4889 1: Load profiles
4890 2: Load profiles with manual restore.
4891
4892 Defaults to 2.
4893
4894 Returns:
4895 bool: True if profiles should be applied, False otherwise.
4896 """
4897 displaycal_running = self._is_displaycal_running()
4898 if displaycal_running:
4899 enumerate_windows_and_processes = False
4900 return (
4901 not self._is_other_running(enumerate_windows_and_processes)
4902 and (not displaycal_running or self._manual_restore == manual_override)
4903 and not self._skip
4904 and (
4905 "--force" in sys.argv[1:]
4906 or self._manual_restore
4907 or (
4908 config.getcfg("profile.load_on_login")
4909 and (
4910 sys.platform != "win32"
4911 or not calibration_management_isenabled()
4912 )
4913 )
4914 )
4915 )
4916
4917 def _toggle_fix_profile_associations(
4918 self, event: wx.Event, parent: wx.Window = None
4919 ) -> bool:
4920 """Toggle the fix profile associations setting.
4921
4922 Args:
4923 event (wx.Event): The event that triggered this method.
4924 parent (wx.Window): The parent window for the dialog (optional).
4925
4926 Returns:
4927 bool: True if the fix profile associations setting is enabled,
4928 False otherwise.
4929 """
4930 if event:
4931 print("Menu command:", end=" ")
4932 print("Toggle fix profile associations", event.IsChecked())
4933 if event.IsChecked():
4934 dlg = FixProfileAssociationsDialog(self, parent)
4935 self.fix_profile_associations_dlg = dlg
4936 result = dlg.ShowModal()
4937 dlg.Destroy()
4938 if result == wx.ID_CANCEL:
4939 print("Cancelled toggling fix profile associations")
4940 return False
4941 if self.lock.locked():
4942 print("Waiting to acquire lock...")
4943 with self.lock:
4944 print("Acquired lock")
4945 setcfg("profile_loader.fix_profile_associations", int(event.IsChecked()))
4946 if event.IsChecked():
4947 self._set_display_profiles()
4948 else:
4949 self._reset_display_profile_associations()
4950 self._manual_restore = True
4951 self.writecfg()
4952 print("Releasing lock")
4953 return event.IsChecked()
4954
4955 def _set_exceptions(self) -> None:
4956 """Set exceptions for profile loading."""
4957 self._exceptions = {}
4958 self._exception_names = set()
4959 exceptions = config.getcfg("profile_loader.exceptions").strip()
4960 if exceptions:
4961 print("Exceptions:")
4962 for exception in exceptions.split(";"):
4963 exception = exception.split(":", 2)
4964 if len(exception) < 3:
4965 # Malformed, ignore
4966 continue
4967 for i in range(2):
4968 try:
4969 exception[i] = int(exception[i])
4970 except Exception:
4971 exception[i] = 0
4972 enabled, reset, path = exception
4973 key = path.lower()
4974 self._exceptions[key] = (enabled, reset, path)
4975 self._exception_names.add(os.path.basename(key))
4976 print(
4977 f"Enabled={bool(enabled)}",
4978 "Action={}".format((reset and "Reset") or "Disable"),
4979 path,
4980 )
4981
4982 def _set_profile_associations(self, event: wx.Event) -> None:
4983 """Open the profile associations dialog.
4984
4985 Args:
4986 event (wx.Event): The event that triggered this method.
4987 """
4988 if event:
4989 print("Menu command:", end=" ")
4990 print("Set profile associations")
4991 dlg = ProfileAssociationsDialog(self)
4992 self.profile_associations_dlg = dlg
4993 dlg.Center()
4994 dlg.ShowModalThenDestroy()
4995
4996 def writecfg(self) -> None:
4997 """Write configuration to the config file."""
4998 config.writecfg(
4999 module="apply-profiles",
5000 options=("argyll.dir", "profile.load_on_login", "profile_loader"),
5001 )
5002
5003
5004 def get_display_name_edid(
5005 device: Device,
5006 moninfo: None | dict = None,
5007 index: None | int = None,
5008 include_adapter: bool = False,
5009 ) -> tuple[str, dict]:
5010 """Return display name and EDID information.
5011
5012 Args:
5013 device (Device): The display device object.
5014 moninfo (None | dict, optional): Monitor information dictionary.
5015 Defaults to None
5016 index (None | int, optional): Index of the display. Defaults to None.
5017 include_adapter (bool, optional): Whether to include adapter
5018 information. Defaults to False.
5019
5020 Returns:
5021 tuple[str, dict]: Display name and EDID information.
5022 """
5023 edid = {}
5024 if device:
5025 display = str(device.DeviceString)
5026 with contextlib.suppress(Exception):
5027 edid = get_edid(device=device)
5028 else:
5029 display = lang.getstr("unknown")
5030 display = edid.get("monitor_name", display)
5031 if moninfo:
5032 m_left, m_top, m_right, m_bottom = moninfo["Monitor"]
5033 m_width = m_right - m_left
5034 m_height = m_bottom - m_top
5035 display = f"{display} @ {m_left:d}, {m_top:d}, {m_width:d}x{m_height:d}"
5036 if moninfo["Flags"] & MONITORINFOF_PRIMARY:
5037 display += " [PRIMARY]"
5038 if moninfo.get("_adapter") and include_adapter:
5039 display += " - {}".format(moninfo["_adapter"].DeviceString)
5040 if index is not None:
5041 display = f"{index + 1:d}. {display}"
5042 return display, edid
5043
5044
5045 def get_profile_desc(
5046 profile_path: str, include_basename_if_different: bool = True
5047 ) -> str:
5048 """Return profile description or path if not available.
5049
5050 Args:
5051 profile_path (str): Path to the ICC profile.
5052 include_basename_if_different (bool, optional): Whether to include the
5053 basename if it is different from the profile description.
5054
5055 Returns:
5056 str: Profile description or path.
5057 """
5058 if not profile_path:
5059 return ""
5060 try:
5061 profile = ICCProfile(profile_path)
5062 profile_desc = profile.getDescription()
5063 except Exception as exception:
5064 if not isinstance(exception, IOError):
5065 exception = traceback.format_exc()
5066 print(f"Could not get description of profile {profile_path}:", exception)
5067 else:
5068 basename = os.path.basename(profile_path)
5069 name = os.path.splitext(basename)[0]
5070 if (
5071 basename != profile_desc
5072 and include_basename_if_different
5073 and name not in (profile_desc, safe_asciize(profile_desc))
5074 ):
5075 return f"{profile_desc} ({basename})"
5076 return profile_desc
5077 return profile_path
5078
5079
5080 def main() -> None:
5081 """Main function for the profile loader application."""
5082 unknown_option = filter_unknown_args()
5083
5084 if "--help" in sys.argv[1:] or unknown_option:
5085 if unknown_option:
5086 print(
5087 f"{os.path.basename(sys.argv[0])}: "
5088 f"unrecognized option `{unknown_option}'"
5089 )
5090 if sys.platform == "win32":
5091 BaseApp._run_exitfuncs()
5092 display_help_message()
5093 elif "-V" in sys.argv[1:] or "--version" in sys.argv[1:]:
5094 print(f"{os.path.basename(sys.argv[0])} {VERSION_STRING}")
5095 else:
5096 if sys.platform == "win32":
5097 setup_profile_loader_task(EXE, EXEDIR, PYDIR)
5098
5099 config.initcfg("apply-profiles")
5100
5101 if (
5102 "--force" not in sys.argv[1:]
5103 and not config.getcfg("profile.load_on_login")
5104 and sys.platform != "win32"
5105 ):
5106 # Early exit incase profile loading has been disabled and isn't forced
5107 sys.exit()
5108
5109 if "--error-dialog" in sys.argv[1:]:
5110 config.setcfg("profile_loader.error.show_msg", 1)
5111 config.writecfg(
5112 module="apply-profiles",
5113 options=("argyll.dir", "profile.load_on_login", "profile_loader"),
5114 )
5115
5116 global lang
5117 from DisplayCAL import localization as lang
5118
5119 lang.init()
5120
5121 ProfileLoader()
5122
5123
5124 def filter_unknown_args() -> None | str:
5125 """Filter unknown command-line arguments.
5126
5127 Returns:
5128 None | str: The first unknown argument found, or None if all arguments
5129 are recognized.
5130 """
5131 unknown_option = None
5132 for arg in sys.argv[1:]:
5133 if (
5134 arg
5135 not in (
5136 "--debug",
5137 "-d",
5138 "--help",
5139 "--force",
5140 "-V",
5141 "--version",
5142 "--skip",
5143 "--test",
5144 "-t",
5145 "--verbose",
5146 "--verbose=1",
5147 "--verbose=2",
5148 "--verbose=3",
5149 "-v",
5150 )
5151 and (
5152 arg not in ("--oneshot", "--task", "--profile-associations")
5153 or sys.platform != "win32"
5154 )
5155 and (
5156 arg not in ("--verify", "--silent", "--error-dialog")
5157 or sys.platform == "win32"
5158 )
5159 ):
5160 unknown_option = arg
5161 break
5162 return unknown_option
5163
5164
5165 def display_help_message() -> None:
5166 """Display help message for the profile loader application."""
5167 print(f"Usage: {os.path.basename(sys.argv[0])} [OPTION]...")
5168 print("Apply profiles to configured display devices and load calibration")
5169 print(f"Version {VERSION_STRING}")
5170 print("")
5171 print("Options:")
5172 print(" --help Output this help text and exit")
5173 print(" --force Force loading of calibration/profile (if it has been")
5174 print(f" disabled in {APPNAME}.ini)")
5175 print(" --skip Skip initial loading of calibration")
5176 if sys.platform == "win32":
5177 print(" --oneshot Exit after loading calibration")
5178 print(" -V, --version Output version information and exit")
5179 print("")
5180 import textwrap
5181
5182 print(
5183 "Configuration options ({}):".format(
5184 os.path.join(CONFIG_HOME, APPBASENAME + "-apply-profiles.ini")
5185 )
5186 )
5187 print("")
5188 for cfgname, cfgdefault in sorted(config.DEFAULTS.items()):
5189 if (
5190 not cfgname.startswith("profile_loader.")
5191 and cfgname != "profile.load_on_login"
5192 ):
5193 continue
5194 # Documentation
5195 key = cfgname.split(".", 1)[1]
5196 cfgdoc = {
5197 "load_on_login": "Apply calibration state on login and preserve",
5198 "buggy_video_drivers": (
5199 "List of buggy video driver names (case "
5200 "insensitive, delimiter: ';')"
5201 ),
5202 "check_gamma_ramps": (
5203 "Check if video card gamma table has "
5204 "changed and reapply calibration state if so"
5205 ),
5206 "exceptions": (
5207 "List of exceptions (case "
5208 "insensitive, delimiter: ';', format: "
5209 "<enabled [0|1]>:<reset video card gamma table [0|1]:"
5210 "<executable path>)"
5211 ),
5212 "fix_profile_associations": "Automatically fix profile asociations",
5213 "ignore_unchanged_gamma_ramps": (
5214 "Ignore unchanged gamma table, i.e. reapply "
5215 "calibration state even if no change (only "
5216 "effective if profile_loader."
5217 "track_other_processes = 0)"
5218 ),
5219 "quantize_bits": "Quantize video card gamma table to <n> bits",
5220 "reset_gamma_ramps": "Reset video card gamma table to linear",
5221 "track_other_processes": (
5222 "Reapply calibration state when other processes launch or exit"
5223 ),
5224 "tray_icon_animation_quality": "Tray icon animation quality, 0 = off",
5225 }.get(key)
5226
5227 if cfgdoc is None:
5228 continue
5229 # Name and valid values
5230 valid = config.VALID_VALUES.get(cfgname)
5231 if valid:
5232 valid = "[{}]".format("|".join(f"{v}" for v in valid))
5233 else:
5234 valid = config.VALID_RANGES.get(cfgname)
5235 if valid:
5236 valid = "[{}..{}]".format(*tuple(valid))
5237 elif isinstance(cfgdefault, int):
5238 # Boolean
5239 valid = "[0|1]"
5240 elif isinstance(cfgdefault, str):
5241 # String
5242 valid = "<string>"
5243 cfgdefault = f"'{cfgdefault}'"
5244 else:
5245 valid = ""
5246 print(cfgname.ljust(45, " "), valid)
5247 cfgdoc += f" [Default: {cfgdefault}]."
5248 for line in textwrap.fill(cfgdoc, 75).splitlines():
5249 print(" " * 4 + line.rstrip())
5250 else:
5251 print(" --verify Verify if calibration was loaded correctly")
5252 print(" --silent Do not show dialog box on error")
5253 print(" --error-dialog Force dialog box on error")
5254 print(" -V, --version Output version information and exit")
5255
5256
5257 if __name__ == "__main__":
5258 main()