Debian Codegraph @

DisplayCAL/display_cal.py

raw
1 """DisplayCAL - display calibration and characterization powered by ArgyllCMS.
2
3 Copyright (C) 2008, 2009 Florian Hoech
4
5 This program is free software;
6 you can redistribute it and/or modify it under the terms of the GNU General
7 Public License as published by the Free Software Foundation;
8 either version 3 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along with
16 this program; if not, see <http://www.gnu.org/licenses/>
17 """
18
19 # Standard modules
20 from __future__ import annotations
21
22 import contextlib
23 import datetime
24 import io
25 import json as json_module
26 import math
27 import os
28 import platform
29 import re
30 import shutil
31 import socket
32 import subprocess as sp
33 import sys
34 import threading
35 import requests
36 import traceback
37 import urllib.error
38 import urllib.parse
39 import urllib.request
40 import webbrowser # Import the webbrowser module for platform-independent results
41 import zipfile
42 from decimal import Decimal
43 from hashlib import md5
44 from io import BytesIO, StringIO
45 from time import localtime, sleep, strftime, strptime, struct_time
46 from typing import TYPE_CHECKING, Callable
47 from zlib import crc32
48
49 from send2trash import send2trash
50
51 # wxPython
52 from wx import xrc
53 from wx.lib import delayedresult, platebtn
54 from wx.lib.art import flagart
55 from wx.lib.scrolledpanel import ScrolledPanel
56
57 # Local Imports
58 from DisplayCAL import (
59 audio,
60 ccmx,
61 colord,
62 colormath,
63 config,
64 floatspin,
65 madvr,
66 report,
67 util_x,
68 xh_bitmapctrls,
69 xh_fancytext,
70 xh_filebrowsebutton,
71 xh_floatspin,
72 xh_hstretchstatbmp,
73 )
74 from DisplayCAL import localization as lang
75 from DisplayCAL.argyll import (
76 check_set_argyll_bin,
77 get_argyll_instrument_config,
78 get_argyll_latest_version,
79 get_argyll_util,
80 get_argyll_version,
81 make_argyll_compatible_path,
82 set_argyll_bin,
83 )
84 from DisplayCAL.argyll_cgats import (
85 cal_to_fake_profile,
86 can_update_cal,
87 extract_cal_from_profile,
88 ti3_to_ti1,
89 verify_ti1_rgb_xyz,
90 )
91 from DisplayCAL.argyll_instruments import get_canonical_instrument_name, instruments
92 from DisplayCAL.argyll_names import VIEWCONDS
93 from DisplayCAL.cgats import (
94 CGATS,
95 CGATSError,
96 CGATSInvalidError,
97 CGATSInvalidOperationError,
98 CGATSKeyError,
99 CGATSTypeError,
100 CGATSValueError,
101 )
102 from DisplayCAL.colormath import (
103 XYZ2CCT,
104 CIEDCCT2xyY,
105 XYZ2Lab,
106 XYZ2xyY,
107 planckianCT2xyY,
108 xyY2CCT,
109 )
110 from DisplayCAL.config import (
111 AUTOSTART,
112 AUTOSTART_HOME,
113 DEFAULTS,
114 ENC,
115 EXE,
116 EXE_EXT,
117 FS_ENC,
118 ISEXE,
119 PROFILE_EXT,
120 PYDIR,
121 RES_FILES,
122 SCRIPT_EXT,
123 get_bitmap,
124 get_ccxx_testchart,
125 get_current_profile,
126 get_data_path,
127 get_display_profile,
128 get_icon,
129 get_total_patches,
130 get_verified_path,
131 getcfg,
132 hascfg,
133 initcfg,
134 is_ccxx_testchart,
135 is_profile,
136 setcfg,
137 setcfg_cond,
138 writecfg,
139 )
140 from DisplayCAL.debughelpers import (
141 getevtobjname,
142 getevttype,
143 handle_error,
144 )
145 from DisplayCAL.edid import PNP_ID_CACHE, get_manufacturer_name
146 from DisplayCAL.icc_profile import (
147 GAMUT_VOLUME_ADOBERGB,
148 GAMUT_VOLUME_SMPTE431_P3,
149 GAMUT_VOLUME_SRGB,
150 ChromaticAdaptionTag,
151 CurveType,
152 DictType,
153 ICCProfile,
154 ICCProfileInvalidError,
155 ICCProfileTag,
156 LUT16Type,
157 TextDescriptionType,
158 TextType,
159 VideoCardGammaTableType,
160 VideoCardGammaType,
161 XYZType,
162 )
163 from DisplayCAL.log import LOGBUFFER
164 from DisplayCAL.meta import (
165 AUTHOR,
166 DEVELOPMENT_HOME_PAGE,
167 DOMAIN,
168 VERSION_STRING,
169 VERSION_TUPLE,
170 GITHUB_API_URL,
171 get_latest_changelog_entry,
172 )
173 from DisplayCAL.meta import (
174 NAME as APPNAME,
175 )
176 from DisplayCAL.options import (
177 DEBUG,
178 FORCE_SKIP_INITIAL_INSTRUMENT_DETECTION,
179 TEST,
180 TEST_UPDATE,
181 VERBOSE,
182 )
183 from DisplayCAL.patterngenerators import WebWinHTTPPatternGeneratorServer
184 from DisplayCAL.util_decimal import float2dec, stripzeros
185 from DisplayCAL.util_dict import dict_sort, swap_dict_keys_values
186 from DisplayCAL.util_io import LineCache, TarFileProper
187 from DisplayCAL.util_list import index_fallback_ignorecase, intlist, natsort
188 from DisplayCAL.util_os import (
189 dlopen,
190 expanduseru,
191 get_program_file,
192 getenvu,
193 is_superuser,
194 launch_file,
195 listdir_re,
196 safe_glob,
197 waccess,
198 which,
199 )
200 from DisplayCAL.util_str import (
201 ellipsis_,
202 make_filename_safe,
203 safe_str,
204 strtr,
205 universal_newlines,
206 wrap,
207 )
208 from DisplayCAL.worker import (
209 Error,
210 FilteredStream,
211 Info,
212 UnloggedError,
213 UnloggedInfo,
214 UnloggedWarning,
215 Warn,
216 Worker,
217 _applycal_bug_workaround,
218 check_argyll_bin,
219 check_create_dir,
220 check_file_isfile,
221 check_ti3,
222 check_ti3_criteria1,
223 check_ti3_criteria2,
224 get_arg,
225 get_argyll_util,
226 get_cfg_option_from_args,
227 get_current_profile_path,
228 get_options_from_cal,
229 get_options_from_profile,
230 get_options_from_ti3,
231 http_request,
232 parse_argument_string,
233 reload_black_videoluts,
234 show_result_dialog,
235 )
236 from DisplayCAL.wx_addons import (
237 CustomEvent,
238 CustomGridCellEvent,
239 IdFactory,
240 PopupMenu,
241 wx,
242 )
243 from DisplayCAL.wx_display_uniformity_frame import DisplayUniformityFrame
244 from DisplayCAL.wx_fixes import (
245 BitmapWithThemedButton,
246 PlateButton,
247 TempXmlResource,
248 ThemedGenButton,
249 get_bitmap_disabled,
250 set_bitmap_labels,
251 set_maxsize,
252 wx_Panel,
253 )
254 from DisplayCAL.wx_lut_3d_frame import LUT3DFrame, LUT3DMixin
255 from DisplayCAL.wx_measure_frame import MeasureFrame, get_default_size
256 from DisplayCAL.wx_report_frame import ReportFrame
257 from DisplayCAL.wx_synth_icc_frame import SynthICCFrame
258 from DisplayCAL.wx_testchart_editor import TestchartEditor
259 from DisplayCAL.wx_visual_whitepoint_editor import VisualWhitepointEditor
260 from DisplayCAL.wx_windows import (
261 AboutDialog,
262 AuiBetterTabArt,
263 BaseApp,
264 BaseFrame,
265 BitmapBackgroundPanel,
266 BitmapBackgroundPanelText,
267 BorderGradientButton,
268 ConfirmDialog,
269 CustomCellBoolRenderer,
270 CustomGrid,
271 FileBrowseBitmapButtonWithChoiceHistory,
272 FileDrop,
273 HtmlWindow,
274 HyperLinkCtrl,
275 InfoDialog,
276 LogWindow,
277 TabButton,
278 TooltipWindow,
279 get_dialogs,
280 )
281
282 if sys.platform == "win32":
283 import winreg
284
285 from DisplayCAL import util_win
286 elif sys.platform == "darwin":
287 from DisplayCAL import util_mac
288
289 try:
290 from DisplayCAL.chromecast_pattern_generator import ChromeCastPatternGenerator
291 except ImportError:
292 from types import NoneType
293
294 ChromeCastPatternGenerator = NoneType
295
296 try:
297 from DisplayCAL.wx_ccxx_plot import CCXXPlot
298 except ImportError:
299 CCXXPlot = None
300
301 try:
302 from DisplayCAL.wx_lut_viewer import LUTFrame
303 except ImportError:
304 LUTFrame = None
305
306 try:
307 from DisplayCAL.wx_profile_info import ProfileInfoFrame
308 except ImportError:
309 ProfileInfoFrame = None
310
311 # wxPython
312 try:
313 # Only wx.lib.aui.AuiNotebook looks reasonable across _all_ platforms.
314 # Other tabbed book controls like wx.Notebook or wx.aui.AuiNotebook are
315 # impossible to get to look right under GTK because there's no way to set
316 # the correct background color for the pages.
317 from wx.lib.agw import aui
318 except ImportError:
319 # Fall back to wx.aui under ancient wxPython versions
320 from wx import aui
321
322 if TYPE_CHECKING:
323 from pathlib import Path
324
325
326 # Set no delay time to open the web page
327 webbrowser.PROCESS_CREATION_DELAY = 0
328
329 APP_IS_UP_TO_DATE = True
330 RELEASE_DATA: dict | None = None
331 COMPRESSED_FILE_EXTENSIONS = (".7z", ".tar.gz", ".tgz", ".zip")
332 ICCPROFILE_FILE_EXTENSIONS = (".icc", ".icm")
333 # Use conservative UI paths by default unless explicitly disabled.
334 SAFE_WX_UI = os.getenv("DISPLAYCAL_UNSAFE_WX_UI", "").strip() != "1"
335
336
337 def debug_print(*args, **kwargs) -> None:
338 """Print debug messages if DEBUG is enabled."""
339 if DEBUG:
340 print(*args, **kwargs)
341
342
343 def verbose_print(*args, **kwargs) -> None:
344 """Print verbose messages if VERBOSE is enabled."""
345 if kwargs.pop("level", 1) <= VERBOSE:
346 print(*args, **kwargs)
347
348
349 def set_platebutton_bitmaps(
350 button: PlateButton, icon_name: str, size: int = 16
351 ) -> None:
352 """Set normal/hover/disabled bitmaps with crash-safe hover color lookup."""
353 hover_suffix = ""
354 if not SAFE_WX_UI:
355 try:
356 hover_suffix = button._color["htxt"].GetAsString(wx.C2S_HTML_SYNTAX)
357 except Exception:
358 hover_suffix = ""
359 button.SetBitmapHover(get_icon(size, icon_name + hover_suffix))
360 button.SetBitmapDisabled(get_bitmap_disabled(get_icon(size, icon_name)))
361
362
363 def show_ccxx_error_dialog(exception: Exception, path: str, parent: wx.Window) -> None:
364 """Show a dialog with the error message from CGATS exception.
365
366 Args:
367 exception (Exception): The CGATS exception that was raised.
368 path (str): The path to the CGATS file.
369 parent (wx.Window): The parent window to show the dialog.
370 """
371 msg = str(exception)
372 if msg.startswith("Malformed"):
373 fn, ext = os.path.splitext(path)
374 msg = lang.getstr("error.malformed_cgats", (ext[1:].upper(), path))
375 show_result_dialog(msg, parent)
376
377
378 def get_download_url(newversion: str) -> str | None:
379 """Return the GitHub release asset download URL for the current platform."""
380 if RELEASE_DATA is None:
381 return None
382 if sys.platform == "win32":
383 machine = platform.machine().lower()
384 if machine in ("arm64", "aarch64"):
385 filename = f"{APPNAME}-{newversion}-Windows-arm64.exe"
386 else:
387 filename = f"{APPNAME}-{newversion}-Windows-x64.exe"
388 elif sys.platform == "darwin":
389 machine = platform.machine().lower()
390 if machine in ("arm64", "aarch64"):
391 filename = f"{APPNAME}-{newversion}-macOS-arm64.dmg"
392 else:
393 filename = f"{APPNAME}-{newversion}-macOS-x86.dmg"
394 else:
395 filename = f"{APPNAME.lower()}-{newversion}.tar.gz"
396 for asset in RELEASE_DATA["assets"]:
397 if asset["name"] == filename:
398 return asset["browser_download_url"]
399 return None
400
401
402 def is_new_update() -> bool | tuple:
403 """Check for new updates on GitHub.
404
405 Returns:
406 bool | tuple: The latest version tuple if a new update is available,
407 False otherwise.
408 """
409 global RELEASE_DATA
410 print("Checking for updates...")
411 headers = {"User-Agent": "DisplayCAL-updater"}
412 try:
413 response = requests.get(
414 f"{GITHUB_API_URL}/releases/latest", headers=headers, timeout=10
415 )
416 response.raise_for_status()
417 except requests.RequestException as e:
418 print(f"Error checking for updates: Network error - {str(e)}")
419 return False
420
421 try:
422 data = response.json()
423 RELEASE_DATA = data
424 latest_version_tuple = tuple(int(n) for n in data["tag_name"].split("."))
425 except (KeyError, ValueError, IndexError) as e:
426 print(f"Error checking for updates: Parsing error - {str(e)}")
427 return False
428
429 current_version = VERSION_TUPLE[:3]
430 if latest_version_tuple > current_version:
431 print("New updates available!")
432 return latest_version_tuple
433 print("No new updates available.")
434 return False
435
436
437 def app_update_check(
438 parent: None | wx.Window = None,
439 silent: bool = False,
440 snapshot: bool = False,
441 argyll: bool = False,
442 ) -> None:
443 """Check for application update. Show an error dialog if a failure occurs.
444
445 Args:
446 parent (None | wx.Window, optional): The parent window for the dialog.
447 silent (bool, optional): If True, suppresses dialog display and
448 only performs the update check.
449 snapshot (bool, optional): If True, the application is a snapshot build.
450 argyll (bool, optional): If True, check for ArgyllCMS update.
451 """
452 global APP_IS_UP_TO_DATE
453 if argyll:
454 if TEST_UPDATE:
455 argyll_version = [0, 0, 0]
456 elif parent and hasattr(parent, "worker"):
457 argyll_version = parent.worker.argyll_version
458 else:
459 argyll_version = intlist(getcfg("argyll.version").split("."))
460 curversion_tuple = tuple(argyll_version)
461 chglog_file = "Argyll/ChangesSummary.html"
462 # Fetch the latest ArgyllCMS version from argyllcms.com
463 latest_argyll_str = get_argyll_latest_version()
464 try:
465 new_version_tuple = tuple(int(n) for n in latest_argyll_str.split("."))
466 except (ValueError, AttributeError):
467 print(lang.getstr("update_check.fail.version", "ArgyllCMS"))
468 if not silent:
469 wx.CallAfter(
470 InfoDialog,
471 parent,
472 msg=lang.getstr("update_check.fail.version", "ArgyllCMS"),
473 ok=lang.getstr("ok"),
474 bitmap=get_icon(32, "dialog-error"),
475 log=False,
476 )
477 return
478 new_version_tuple = (0, 0, 0, 0)
479 if not wx.GetApp():
480 return
481 elif snapshot:
482 # Snapshot — fetch the version file directly from the project domain
483 curversion_tuple = VERSION_TUPLE
484 chglog_file = "SNAPSHOT_CHANGES.html"
485 resp = http_request(
486 parent,
487 DOMAIN,
488 "GET",
489 "/SNAPSHOT_VERSION",
490 failure_msg=lang.getstr("update_check.fail"),
491 silent=silent,
492 )
493 if resp is False:
494 if silent:
495 # Check if we need to run instrument setup
496 wx.CallAfter(
497 parent.check_instrument_setup, check_donation, (parent, snapshot)
498 )
499 return
500 data = resp.read()
501 if not wx.GetApp():
502 return
503 try:
504 new_version_tuple = tuple(int(n) for n in data.decode().split("."))
505 except ValueError:
506 print(lang.getstr("update_check.fail.version", DOMAIN))
507 if not silent:
508 wx.CallAfter(
509 InfoDialog,
510 parent,
511 msg=lang.getstr("update_check.fail.version", DOMAIN),
512 ok=lang.getstr("ok"),
513 bitmap=get_icon(32, "dialog-error"),
514 log=False,
515 )
516 return
517 new_version_tuple = (0, 0, 0, 0)
518 else:
519 # Stable
520 print(lang.getstr("update_check"))
521 curversion_tuple = VERSION_TUPLE
522 chglog_file = "CHANGES.html"
523 resp = is_new_update()
524 if resp is False:
525 if silent:
526 # Check if we need to run instrument setup
527 wx.CallAfter(
528 parent.check_instrument_setup, check_donation, (parent, snapshot)
529 )
530 return
531 # Non-silent with no update available: fall through to the
532 # "up to date" branches below using the current version.
533 resp = curversion_tuple
534 if not wx.GetApp():
535 return
536 new_version_tuple = resp
537
538 if not argyll:
539 APP_IS_UP_TO_DATE = new_version_tuple <= curversion_tuple
540 if new_version_tuple > curversion_tuple:
541 # Get changelog
542 resp = http_request(parent, DOMAIN, "GET", "/" + chglog_file, silent=True)
543 chglog = None
544 if resp:
545 readme = str(resp.read())
546 if argyll:
547 chglog = readme
548 else:
549 chglog = get_latest_changelog_entry(readme)
550 if chglog:
551 chglog = f"""<!DOCTYPE html>
552 <html>
553 <head>
554 <title></title>
555 </head>
556 <body>
557 {chglog}
558 </body>"""
559 if chglog:
560 chglog = re.sub(
561 re.compile(r"<h\d>(.+?)</h\d>", flags=re.I | re.S),
562 r"<p><strong>\1</strong></p>",
563 chglog,
564 )
565 chglog = re.sub(
566 re.compile(r'href="(#[^"]+)"', flags=re.I),
567 rf'href="https://{DOMAIN}/\1"',
568 chglog,
569 )
570
571 if not wx.GetApp():
572 return
573
574 wx.CallAfter(
575 app_update_confirm,
576 parent,
577 new_version_tuple,
578 chglog,
579 snapshot,
580 argyll,
581 silent,
582 )
583 elif not argyll and not snapshot:
584 app_update_check(parent, silent, True)
585 elif not argyll:
586 print(lang.getstr("update_check.uptodate", APPNAME))
587 if check_argyll_bin():
588 app_update_check(parent, silent, argyll=True)
589 elif silent:
590 wx.CallAfter(
591 parent.set_argyll_bin_handler,
592 True,
593 silent,
594 parent.check_instrument_setup,
595 (check_donation, (parent, snapshot)),
596 )
597 else:
598 wx.CallAfter(parent.set_argyll_bin_handler, True)
599 elif not silent:
600 print(lang.getstr("update_check.uptodate", "ArgyllCMS"))
601 wx.CallAfter(
602 app_up_to_date,
603 parent,
604 "ArgyllCMS" if not globals().get("APP_IS_UP_TO_DATE") else APPNAME,
605 )
606 else:
607 print(lang.getstr("update_check.uptodate", "ArgyllCMS"))
608 # Check if we need to run instrument setup
609 wx.CallAfter(parent.check_instrument_setup, check_donation, (parent, snapshot))
610
611
612 def check_donation(parent: wx.Window, snapshot: bool) -> None:
613 """Check if we need to show donation message.
614
615 Show donation popup if user did not choose "don't show again".
616 Reset donation popup after a major update.
617
618 Args:
619 parent (wx.Window): Parent window to show the dialog.
620 snapshot (bool): If True, the application is a snapshot build.
621 """
622 if (
623 not snapshot
624 and VERSION_TUPLE[0] > intlist(getcfg("last_launch", "0.0.0").split("."))[0]
625 ):
626 setcfg("show_donation_message", 1)
627 # store the current version as the last_launch version
628 setcfg("last_launch", VERSION_STRING)
629 if getcfg("show_donation_message"):
630 wx.CallAfter(donation_message, parent)
631
632
633 def app_up_to_date(parent: None | wx.Window = None, appname: str = APPNAME) -> None:
634 """Show a dialog confirming application is up-to-date.
635
636 Args:
637 parent (None | wx.Window, optional): The parent window for the dialog.
638 appname (str, optional): The name of the application to display in the
639 dialog.
640 """
641 dlg = InfoDialog(
642 parent,
643 msg=lang.getstr("update_check.uptodate", appname),
644 ok=lang.getstr("ok"),
645 bitmap=get_icon(32, "dialog-information"),
646 show=False,
647 log=False,
648 )
649 update_check = wx.CheckBox(dlg, -1, lang.getstr("update_check.onstartup"))
650 update_check.SetValue(getcfg("update_check"))
651 dlg.Bind(
652 wx.EVT_CHECKBOX,
653 lambda event: setcfg("update_check", int(event.IsChecked())),
654 id=update_check.GetId(),
655 )
656 dlg.sizer3.Add(update_check, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
657 dlg.sizer0.SetSizeHints(dlg)
658 dlg.sizer0.Layout()
659 dlg.ShowModalThenDestroy()
660 if parent and getattr(parent, "menuitem_app_auto_update_check", None):
661 parent.menuitem_app_auto_update_check.Check(bool(getcfg("update_check")))
662
663
664 def app_update_confirm(
665 parent: None | wx.Window = None,
666 new_version_tuple: tuple = (0, 0, 0, 0),
667 chglog: None | str = None,
668 snapshot: bool = False,
669 argyll: bool = False,
670 silent: bool = False,
671 ) -> None:
672 """Show a dialog confirming application update, with cancel option.
673
674 Args:
675 parent (None | wx.Window, optional): The parent window for the dialog.
676 new_version_tuple (tuple, optional): The new version tuple to display.
677 chglog (str | None, optional): The changelog HTML content.
678 snapshot (bool, optional): If True, the application is a snapshot build.
679 argyll (bool, optional): If True, the update is for ArgyllCMS.
680 silent (bool, optional): If True, suppresses dialog display and
681 only performs the update check.
682 """
683 zeroinstall = False
684 download = argyll and not check_argyll_bin()
685 if zeroinstall or sys.platform in ("darwin", "win32") or argyll:
686 ok = lang.getstr("download" if download else "update_now")
687 alt = lang.getstr("go_to_website")
688 else:
689 ok = lang.getstr("go_to_website")
690 alt = None
691 newversion = ".".join(str(n) for n in new_version_tuple)
692 if argyll:
693 newversion_desc = "ArgyllCMS"
694 try:
695 newversion = get_argyll_latest_version()
696 except Exception as exception:
697 # Keep update flow alive even if version lookup/parsing fails.
698 print(f"Could not determine latest ArgyllCMS version: {exception}")
699 newversion = config.DEFAULTS.get("argyll.version", "unknown")
700 else:
701 newversion_desc = APPNAME
702 newversion_desc += f" {newversion}"
703 if snapshot:
704 newversion_desc += " Beta"
705 if download:
706 msg = "{} {}".format(lang.getstr("download"), newversion_desc)
707 else:
708 msg = lang.getstr("update_check.new_version", newversion_desc)
709 dlg = ConfirmDialog(
710 parent,
711 msg=msg,
712 ok=ok,
713 alt=alt,
714 cancel=lang.getstr("cancel"),
715 bitmap=get_icon(32, "dialog-information"),
716 log=True,
717 )
718 scale = getcfg("app.dpi") / config.get_default_dpi()
719 scale = max(scale, 1)
720 if (
721 argyll
722 and sys.platform not in ("darwin", "win32")
723 and not dlopen("libXss.so")
724 and not dlopen("libXss.so.1")
725 ):
726 sizer = wx.BoxSizer(wx.HORIZONTAL)
727 dlg.sizer3.Insert(0, sizer, flag=wx.BOTTOM | wx.ALIGN_LEFT, border=12)
728 sizer.Add(wx.StaticBitmap(dlg, -1, get_icon(16, "dialog-warning")))
729 warning_text = lang.getstr(
730 "library.not_found.warning", (lang.getstr("libXss.so"), "libXss.so")
731 )
732 warning = wx.StaticText(dlg, -1, warning_text)
733 warning.ForegroundColour = "#F07F00"
734 sizer.Add(warning, flag=wx.LEFT, border=8)
735 warning.Wrap((500 - 16 - 8) * scale)
736 if chglog and not SAFE_WX_UI:
737 htmlwnd = HtmlWindow(
738 dlg, -1, size=(500 * scale, 300 * scale), style=wx.BORDER_THEME
739 )
740 htmlwnd.SetPage(chglog)
741 dlg.sizer3.Add(htmlwnd, 1, flag=wx.TOP | wx.ALIGN_LEFT | wx.EXPAND, border=12)
742 update_check = wx.CheckBox(dlg, -1, lang.getstr("update_check.onstartup"))
743 update_check.SetValue(getcfg("update_check"))
744 dlg.Bind(
745 wx.EVT_CHECKBOX,
746 lambda event: setcfg("update_check", int(event.IsChecked())),
747 id=update_check.GetId(),
748 )
749 dlg.sizer3.Add(update_check, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
750 dlg.sizer0.SetSizeHints(dlg)
751 dlg.sizer0.Layout()
752 dlg.Center()
753 result = dlg.ShowModal()
754 dlg.Destroy()
755 if parent and getattr(parent, "menuitem_app_auto_update_check", None):
756 parent.menuitem_app_auto_update_check.Check(bool(getcfg("update_check")))
757 if result == wx.ID_OK and (
758 zeroinstall or (sys.platform in ("darwin", "win32") or argyll)
759 ):
760 worker = parent.worker if parent and hasattr(parent, "worker") else Worker()
761 # Snapshot or Stable
762 folder = "/snapshot" if snapshot else ""
763 if zeroinstall:
764 return
765 elif not argyll:
766 # Download the update from GitHub based on the user's platform
767 download_url = get_download_url(newversion)
768 if download_url is not None:
769 try:
770 webbrowser.open_new_tab(download_url)
771 except Exception as e:
772 print(f"Error opening web browser for updates: {str(e)}")
773 else:
774 launch_file(f"{DEVELOPMENT_HOME_PAGE}/releases")
775 else:
776 # Download ArgyllCMS or DisplayCAL update
777 if argyll:
778 consumer = worker.process_argyll_download
779 argyll_domain = config.DEFAULTS.get("argyll.domain")
780 machine = platform.machine().lower()
781 if sys.platform == "win32":
782 # Determine 32 or 64 bit OS
783 key = winreg.OpenKey(
784 winreg.HKEY_LOCAL_MACHINE,
785 r"SYSTEM\CurrentControlSet\Control"
786 r"\Session Manager\Environment",
787 )
788 try:
789 value = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE")[0]
790 except OSError:
791 value = "x86"
792 finally:
793 winreg.CloseKey(key)
794 arch = value.lower()
795 if arch in ("arm64", "aarch64"):
796 suffix = "_win_arm64_exe.zip"
797 elif arch in ("amd64", "x86_64"):
798 suffix = "_win64_exe.zip"
799 else:
800 # Assume win32
801 suffix = "_win32_exe.zip"
802 elif sys.platform == "darwin":
803 if machine in ("arm64", "aarch64"):
804 suffix = "_macOS11_arm64_bin.tgz"
805 else:
806 # Keep x86_64 as fallback on Intel and unknown machine ids.
807 suffix = "_osx10.6_x86_64_bin.tgz"
808 # Linux
809 elif (
810 machine in ("x86_64", "amd64")
811 or platform.architecture()[0] == "64bit"
812 ):
813 # Assume x86_64
814 suffix = "_linux_x86_64_bin.tgz"
815 else:
816 # Assume x86
817 suffix = "_linux_x86_bin.tgz"
818 url = f"{argyll_domain}/releases/download/{newversion}/Argyll_V{newversion}{suffix}"
819 else:
820 consumer = worker.process_download
821 # Snapshots are only available as ZIP
822 # or Regular stable versions are available as setup
823 if sys.platform == "win32":
824 suffix = "-win32.zip" if snapshot else "-Setup.exe"
825 else:
826 suffix = ".dmg"
827 url = f"https://{DOMAIN}/{folder}/{APPNAME}-{newversion}{suffix}"
828 worker.start(
829 consumer,
830 worker.download,
831 ckwargs={"exit_": not argyll},
832 wargs=(url,),
833 progress_msg=lang.getstr("downloading"),
834 fancy=False,
835 )
836 return
837 elif result != wx.ID_CANCEL:
838 launch_file(DEVELOPMENT_HOME_PAGE)
839 elif not argyll:
840 # Check for Argyll update
841 if check_argyll_bin():
842 parent.app_update_check_handler(None, silent, True)
843 elif silent:
844 parent.set_argyll_bin_handler(
845 True,
846 silent,
847 parent.check_instrument_setup,
848 (check_donation, (parent, snapshot)),
849 )
850 else:
851 parent.set_argyll_bin_handler(True)
852 return
853 if silent:
854 # Check if we need to run instrument setup
855 parent.check_instrument_setup(check_donation, (parent, snapshot))
856
857
858 def donation_message(parent: None | wx.Window = None) -> None:
859 """Show donation message.
860
861 Args:
862 parent (None | wx.Window, optional): The parent window for the dialog.
863 """
864 dlg = ConfirmDialog(
865 parent,
866 title=lang.getstr("welcome"),
867 msg=lang.getstr("donation_message"),
868 ok=lang.getstr("contribute"),
869 cancel=lang.getstr("not_now"),
870 bitmap=get_bitmap("theme/headericon"),
871 bitmap_margin=0,
872 )
873 header = wx.StaticText(dlg, -1, lang.getstr("donation_header"))
874 font = header.Font
875 font.PointSize += 4
876 header.SetFont(font)
877 if sys.platform != "darwin":
878 header.MinSize = header.GetTextExtent(header.Label)
879 dlg.sizer3.Insert(0, header, flag=wx.BOTTOM | wx.EXPAND, border=14)
880 if sys.platform == "win32":
881 font = dlg.message.Font
882 font.PointSize += 1
883 dlg.message.SetFont(font)
884 dlg.message.MinSize = (-1, -1)
885 chkbox = wx.CheckBox(dlg.buttonpanel, -1, lang.getstr("dialog.do_not_show_again"))
886 dlg.sizer2.Insert(
887 0,
888 chkbox,
889 flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
890 border=max(dlg.sizer3.MinSize[0] - dlg.sizer2.MinSize[0] - chkbox.Size[0], 12),
891 )
892 dlg.sizer2.Insert(0, (88, -1))
893 dlg.buttonpanel.Layout()
894 dlg.sizer0.SetSizeHints(dlg)
895 dlg.sizer0.Layout()
896 if dlg.ShowModal() == wx.ID_OK:
897 launch_file(f"https://{DOMAIN}/#donate")
898 show_again = False
899 else:
900 show_again = not chkbox.Value
901 setcfg("show_donation_message", int(show_again))
902 dlg.Destroy()
903
904
905 def colorimeter_correction_web_check_choose(
906 resp: bytes | str,
907 parent: None | wx.Window = None,
908 ) -> None | CGATS:
909 """Let user choose a colorimeter correction and confirm overwrite.
910
911 Args:
912 resp (bytes | str): The response from the web request containing
913 the colorimeter corrections in JSON format.
914 parent (None | wx.Window, optional): The parent window for the dialog.
915
916 Returns:
917 None | CGATS: Returns a CGATS object if a correction is chosen,
918 otherwise returns None.
919 """
920 if resp is not False:
921 try:
922 json = json_module.load(resp)
923 if not json:
924 raise ValueError
925 except ValueError:
926 InfoDialog(
927 parent,
928 msg=lang.getstr("colorimeter_correction.web_check.failure"),
929 ok=lang.getstr("ok"),
930 bitmap=get_icon(32, "dialog-information"),
931 )
932 return None
933 else:
934 return None
935 dlg = ConfirmDialog(
936 parent,
937 title=lang.getstr("colorimeter_correction.web_check"),
938 msg=lang.getstr("colorimeter_correction.web_check.choose"),
939 ok=lang.getstr("ok"),
940 cancel=lang.getstr("cancel"),
941 bitmap=get_icon(32, "dialog-information"),
942 nowrap=True,
943 )
944 dlg.info = PlateButton(
945 dlg.buttonpanel,
946 -1,
947 lang.getstr("colorimeter_correction.info"),
948 get_icon(16, "info"),
949 )
950 set_platebutton_bitmaps(dlg.info, "info")
951 dlg.sizer2.Insert(0, dlg.info, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=12)
952 dlg.sizer2.Insert(0, (32 + 7, 1))
953 scale = getcfg("app.dpi") / config.get_default_dpi()
954 scale = max(scale, 1)
955 dlg_list_ctrl = wx.ListCtrl(
956 dlg,
957 -1,
958 size=(int(640 * scale), int(150 * scale)),
959 style=wx.LC_REPORT | wx.LC_SINGLE_SEL,
960 name="colorimeter_corrections",
961 )
962 col = IncrementingInt()
963 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("type"))
964 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("description"))
965 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("display"))
966 # dlg_list_ctrl.InsertColumn(int(col), lang.getstr("instrument"))
967 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("reference"))
968 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("spectral_resolution"))
969 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("observer"))
970 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("method"))
971 dlg_list_ctrl.InsertColumn(
972 int(col), "ΔE*00 " + lang.getstr("profile.self_check.avg")
973 )
974 dlg_list_ctrl.InsertColumn(
975 int(col), "ΔE*00 " + lang.getstr("profile.self_check.max")
976 )
977 dlg_list_ctrl.InsertColumn(int(col), lang.getstr("created"))
978 col.i = 0
979 dlg_list_ctrl.SetColumnWidth(int(col), int(75 * scale)) # Type
980 dlg_list_ctrl.SetColumnWidth(int(col), int(415 * scale)) # Desc
981 dlg_list_ctrl.SetColumnWidth(
982 int(col), int(150 * scale)
983 ) # Display manufacturer & model
984 # dlg_list_ctrl.SetColumnWidth(int(col), int(225 * scale)) # Instrument
985 dlg_list_ctrl.SetColumnWidth(int(col), int(90 * scale)) # Ref. instrument
986 dlg_list_ctrl.SetColumnWidth(int(col), int(150 * scale)) # Spectral res
987 dlg_list_ctrl.SetColumnWidth(int(col), int(135 * scale)) # Observer
988 dlg_list_ctrl.SetColumnWidth(int(col), int(135 * scale)) # CCMX fit method
989 dlg_list_ctrl.SetColumnWidth(int(col), int(135 * scale)) # CCMX self check avg
990 dlg_list_ctrl.SetColumnWidth(int(col), int(135 * scale)) # CCMX self check max
991 dlg_list_ctrl.SetColumnWidth(int(col), int(150 * scale)) # Date
992 types = {
993 "CCSS": lang.getstr("spectral").replace(":", ""),
994 "CCMX": lang.getstr("matrix").replace(":", ""),
995 }
996 cgats = {}
997 rows_data = []
998 for item in json:
999 # CGATS is byte string based, make sure to encode Unicode back to UTF-8
1000 # for parsing
1001 # CGATS accepts ``bytes`` data only
1002 cgats_bytes = item.get("cgats", "").encode("utf-8")
1003 try:
1004 ccxx = CGATS(cgats_bytes)
1005 except CGATSError as exception:
1006 print(exception)
1007 cgats_bytes = b""
1008 ccxx = CGATS()
1009 ccxx = ccxx.get(0, ccxx)
1010 ccxx_type = item.get("type", "").upper()
1011 manufacturer = colord.quirk_manufacturer(
1012 item.get("manufacturer") or lang.getstr("unknown")
1013 )
1014 display = item.get("display") or lang.getstr("unknown")
1015 if config.is_virtual_display(display):
1016 display = manufacturer
1017 if not display.lower().startswith(manufacturer.lower()):
1018 display = f"{manufacturer} {display}"
1019 spectral = {}
1020 for key in ("bands", "start_nm", "end_nm"):
1021 try:
1022 v = float(item.get(f"spectral_{key}", 0))
1023 except (TypeError, ValueError):
1024 pass
1025 else:
1026 if v:
1027 spectral[key] = v
1028 if spectral:
1029 spectral_res = "{:.1f}nm, {:.0f}-{:.0f}nm".format(
1030 (spectral["end_nm"] - spectral["start_nm"]) / (spectral["bands"] - 1),
1031 spectral["start_nm"],
1032 spectral["end_nm"],
1033 )
1034 else:
1035 spectral_res = lang.getstr("unknown")
1036 created = item.get("created")
1037 if created:
1038 try:
1039 created = strptime(created)
1040 except ValueError:
1041 datetmp = re.search(
1042 r"\w+ (\w{3}) (\d{2}) (\d{2}(?::[0-5][0-9]){2}) (\d{4})", created
1043 )
1044 if datetmp:
1045 datetmp = "{}-{}-{} {}".format(
1046 datetmp.groups()[3],
1047 {
1048 "Jan": "01",
1049 "Feb": "02",
1050 "Mar": "03",
1051 "Apr": "04",
1052 "May": "05",
1053 "Jun": "06",
1054 "Jul": "07",
1055 "Aug": "08",
1056 "Sep": "09",
1057 "Oct": "10",
1058 "Nov": "11",
1059 "Dec": "12",
1060 }.get(datetmp.groups()[0]),
1061 datetmp.groups()[1],
1062 datetmp.groups()[2],
1063 )
1064 with contextlib.suppress(ValueError):
1065 created = strptime(datetmp, "%Y-%m-%d %H:%M:%S")
1066 if isinstance(created, struct_time):
1067 created = strftime("%Y-%m-%d %H:%M:%S", created)
1068 fit_method = ccxx.queryv1("FIT_METHOD")
1069 if fit_method and fit_method != b"xy":
1070 fit_method = lang.getstr("perceptual")
1071 elif isinstance(fit_method, bytes):
1072 # queryv1() returns bytes; decode so it's consistent with the
1073 # localized str the "perceptual" branch above produces.
1074 fit_method = fit_method.decode("utf-8")
1075 reference_observer = ccxx.queryv1("REFERENCE_OBSERVER")
1076 if isinstance(reference_observer, bytes):
1077 # queryv1() returns bytes, but observers_ab is keyed by str, so
1078 # without decoding this lookup never matches and the "observer"
1079 # column always fell back to "unknown"/"not_applicable".
1080 reference_observer = reference_observer.decode("utf-8")
1081 rows_data.append({
1082 "cgats": cgats_bytes,
1083 "columns": [
1084 types.get(ccxx_type, ccxx_type),
1085 get_canonical_instrument_name(
1086 item.get("description") or lang.getstr("unknown")
1087 ),
1088 display,
1089 get_canonical_instrument_name(
1090 item.get("reference") or lang.getstr("unknown")
1091 ),
1092 spectral_res,
1093 parent.observers_ab.get(
1094 reference_observer,
1095 lang.getstr("unknown" if ccxx_type == "CCMX" else "not_applicable"),
1096 ),
1097 (
1098 fit_method or lang.getstr("unknown")
1099 if ccxx_type == "CCMX"
1100 else lang.getstr("not_applicable")
1101 ),
1102 (
1103 str(ccxx.queryv1("FIT_AVG_DE00") or lang.getstr("unknown"))
1104 if ccxx_type == "CCMX"
1105 else lang.getstr("not_applicable")
1106 ),
1107 (
1108 str(ccxx.queryv1("FIT_MAX_DE00") or lang.getstr("unknown"))
1109 if ccxx_type == "CCMX"
1110 else lang.getstr("not_applicable")
1111 ),
1112 created or lang.getstr("unknown"),
1113 ],
1114 })
1115
1116 sort_state = [None, True] # [column_index, ascending]
1117
1118 def populate_list() -> None:
1119 dlg_list_ctrl.DeleteAllItems()
1120 for idx, row in enumerate(rows_data):
1121 dlg_list_ctrl.InsertStringItem(idx, "")
1122 for col_idx, val in enumerate(row["columns"]):
1123 dlg_list_ctrl.SetStringItem(idx, col_idx, val)
1124 cgats[idx] = row["cgats"]
1125
1126 populate_list()
1127
1128 def show_ccxx_info(event: wx.Event) -> None:
1129 """Show colorimeter correction info dialog.
1130
1131 Args:
1132 event (wx.Event): The event that triggered this function.
1133 """
1134 index = dlg_list_ctrl.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
1135 parent.colorimeter_correction_info_handler(event, cgats[index])
1136
1137 dlg.info.Bind(wx.EVT_BUTTON, show_ccxx_info)
1138 dlg.Bind(
1139 wx.EVT_LIST_ITEM_SELECTED,
1140 lambda event: (dlg.ok.Enable(), dlg.info.Enable()),
1141 dlg_list_ctrl,
1142 )
1143 dlg.Bind(
1144 wx.EVT_LIST_ITEM_DESELECTED,
1145 lambda event: (dlg.ok.Disable(), dlg.info.Disable()),
1146 dlg_list_ctrl,
1147 )
1148 dlg.Bind(
1149 wx.EVT_LIST_ITEM_ACTIVATED, lambda event: dlg.EndModal(wx.ID_OK), dlg_list_ctrl
1150 )
1151
1152 def on_col_click(event: wx.ListEvent) -> None:
1153 clicked_col = event.GetColumn()
1154 if sort_state[0] == clicked_col:
1155 sort_state[1] = not sort_state[1]
1156 else:
1157 sort_state[0] = clicked_col
1158 sort_state[1] = True
1159
1160 def _sort_key(val: str) -> tuple:
1161 try:
1162 return (0, float(val), "")
1163 except ValueError:
1164 return (1, 0.0, val.lower())
1165
1166 rows_data.sort(
1167 key=lambda r: _sort_key(r["columns"][clicked_col]),
1168 reverse=not sort_state[1],
1169 )
1170 populate_list()
1171 dlg.ok.Disable()
1172 dlg.info.Disable()
1173
1174 dlg_list_ctrl.Bind(wx.EVT_LIST_COL_CLICK, on_col_click)
1175 dlg.sizer3.Add(dlg_list_ctrl, 1, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
1176 lstr = lang.getstr("colorimeter_correction.web_check.info")
1177 lstr_en = lang.getstr("colorimeter_correction.web_check.info", lcode="en")
1178 if lstr != lstr_en or lang.getcode() == "en":
1179 info_txt = wx.StaticText(dlg, -1, lstr)
1180 info_txt.Wrap(int(640 * scale))
1181 dlg.sizer3.Add(info_txt, 1, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
1182 if len(cgats) > 1:
1183 # We got several matches
1184 dlg.ok.Disable()
1185 dlg.info.Disable()
1186 else:
1187 item = dlg_list_ctrl.GetItem(0)
1188 dlg_list_ctrl.SetItemState(
1189 item.GetId(), wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED
1190 )
1191 dlg.sizer0.SetSizeHints(dlg)
1192 dlg.sizer0.Layout()
1193 dlg.Center()
1194 result = dlg.ShowWindowModalBlocking()
1195 index = dlg_list_ctrl.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
1196 dlg.Destroy()
1197 if result != wx.ID_OK:
1198 return False
1199 # Important: Do not use parsed CGATS,
1200 # order of keywords may be
1201 # different from raw data so MD5 will be different
1202 return colorimeter_correction_check_overwrite(parent, cgats[index])
1203
1204
1205 def colorimeter_correction_check_overwrite(
1206 parent: wx.Window = None,
1207 cgats: None | bytes = None,
1208 update_comports: bool = False,
1209 ) -> bool:
1210 """Prompt to confirm overwriting a colorimeter correction file if it exists.
1211
1212 Write the file.
1213
1214 Args:
1215 parent (wx.Window): The parent window to show dialogs.
1216 cgats (None | bytes, optional): The CGATS data to write.
1217 update_comports (bool, optional): Whether to update the comports after
1218 writing.
1219
1220 Returns:
1221 bool: True if the file was written successfully, False otherwise.
1222 """
1223 result = check_create_dir(config.get_argyll_data_dir())
1224 if isinstance(result, Exception):
1225 show_result_dialog(result, parent)
1226 return None
1227 path = get_cgats_path(cgats)
1228 if os.path.isfile(path):
1229 dlg = ConfirmDialog(
1230 parent,
1231 msg=lang.getstr("dialog.confirm_overwrite", path),
1232 ok=lang.getstr("ok"),
1233 cancel=lang.getstr("cancel"),
1234 bitmap=get_icon(32, "dialog-warning"),
1235 )
1236 result = dlg.ShowWindowModalBlocking()
1237 dlg.Destroy()
1238 if result != wx.ID_OK:
1239 return False
1240 try:
1241 with open(path, "wb") as cgatsfile:
1242 cgatsfile.write(cgats.rstrip(b"\n") + b"\n")
1243 except OSError as exception:
1244 show_result_dialog(exception, parent)
1245 return False
1246 if getcfg("colorimeter_correction_matrix_file").split(":")[0] != "AUTO":
1247 setcfg("colorimeter_correction_matrix_file", ":" + path)
1248 if update_comports:
1249 cgats = CGATS(cgats)
1250 instrument = cgats.queryv1("INSTRUMENT") or getcfg(
1251 "colorimeter_correction.instrument"
1252 )
1253 if instrument:
1254 instrument = get_canonical_instrument_name(instrument)
1255 else:
1256 instrument = None
1257 if instrument and instrument in parent.worker.instruments:
1258 setcfg("comport.number", parent.worker.instruments.index(instrument) + 1)
1259 parent.update_comports(force=True)
1260 else:
1261 parent.update_colorimeter_correction_matrix_ctrl_items(True)
1262 return True
1263
1264
1265 def get_cgats_measurement_mode(cgats: bytes, instrument: str) -> str:
1266 """Get the measurement mode for the CGATS data.
1267
1268 Args:
1269 cgats (bytes): The CGATS data.
1270 instrument (str): The instrument name.
1271
1272 Returns:
1273 str: The measurement mode.
1274 """
1275 base_id = cgats.queryv1("DISPLAY_TYPE_BASE_ID")
1276 refresh = cgats.queryv1("DISPLAY_TYPE_REFRESH")
1277 mode = None
1278 if base_id:
1279 # IMPORTANT: Make changes aswell in the following locations:
1280 # - DisplayCAL.MainFrame.create_colorimeter_correction_handler
1281 # - DisplayCAL.MainFrame.get_ccxx_measurement_modes
1282 # - DisplayCAL.MainFrame.set_ccxx_measurement_mode
1283 # - worker.Worker.check_add_display_type_base_id
1284 # - worker.Worker.instrument_can_use_ccxx
1285 if instrument in ("ColorHug", "ColorHug2"):
1286 mode = {1: "F", 2: "R"}.get(base_id)
1287 elif instrument == "ColorMunki Smile":
1288 mode = {1: "f"}.get(base_id)
1289 elif instrument == "Colorimtre HCFR":
1290 mode = {1: "R"}.get(base_id)
1291 elif instrument == "K-10":
1292 mode = {1: "F"}.get(base_id)
1293 else:
1294 mode = {1: "l", 2: "c", 3: "g"}.get(base_id)
1295 elif refresh == b"NO":
1296 mode = "l"
1297 elif refresh == b"YES":
1298 mode = "c"
1299 return mode
1300
1301
1302 def get_cgats_path(cgats: bytes) -> str:
1303 """Get the path to save the CGATS file.
1304
1305 Args:
1306 cgats (bytes): The CGATS data.
1307
1308 Returns:
1309 str: The path to save the CGATS file.
1310 """
1311 descriptor = re.search(rb'\nDESCRIPTOR\s+"(.+?)"\n', cgats)
1312 if descriptor:
1313 descriptor = descriptor.groups()[0]
1314 descriptor = descriptor.decode("utf-8")
1315 description = descriptor or lang.getstr("unnamed")
1316 name = make_argyll_compatible_path(description, is_name=True)[:255]
1317 extension = cgats.split()[0].lower().decode("utf-8")
1318 return os.path.join(config.get_argyll_data_dir(), f"{name}.{extension}")
1319
1320
1321 def get_header(
1322 parent: wx.Window,
1323 bitmap: None | wx.Bitmap = None,
1324 label: None | str = None,
1325 size: tuple[int, int] = (-1, 64),
1326 x: int = 80,
1327 y: int = 44,
1328 repeat_sub_bitmap_h: tuple[int, int, int, int] = (220, 0, 2, 64),
1329 ) -> wx.Panel:
1330 """Create a header panel with a bitmap and label.
1331
1332 Args:
1333 parent (wx.Window): The parent window.
1334 bitmap (None | wx.Bitmap, optional): The bitmap to display.
1335 label (None | str, optional): The label to display.
1336 size (tuple, optional): The size of the header panel.
1337 x (int, optional): The x position of the label.
1338 y (int, optional): The y position of the label.
1339 repeat_sub_bitmap_h (tuple, optional): The sub-bitmap height for
1340 repeating.
1341
1342 Returns:
1343 wx.Panel: The header panel.
1344 """
1345 w, h = 222, 64
1346 scale = getcfg("app.dpi") / config.get_default_dpi()
1347 if scale > 1:
1348 size = tuple(math.floor(v * scale) if v > 0 else v for v in size)
1349 x, y = [round(v * scale) if v else v for v in (x, y)]
1350 repeat_sub_bitmap_h = tuple(math.floor(v * scale) for v in repeat_sub_bitmap_h)
1351 w, h = [round(v * scale) for v in (w, h)]
1352 header = BitmapBackgroundPanelText(parent)
1353 header.label_x = x
1354 header.label_y = y
1355 header.scalebitmap = (False,) * 2
1356 header.textshadow = False
1357 header.SetBackgroundColour("#0e59a9")
1358 header.SetForegroundColour("#FFFFFF")
1359 header.SetMaxFontSize(11)
1360 label = label or lang.getstr("header")
1361 if not bitmap:
1362 bitmap = get_bitmap("theme/header", display_missing_icon=False)
1363 if bitmap.Size[0] >= w and bitmap.Size[1] >= h:
1364 bitmap = bitmap.GetSubBitmap((0, 0, w, h))
1365 header.MinSize = size
1366 header.repeat_sub_bitmap_h = repeat_sub_bitmap_h
1367 header.SetBitmap(bitmap)
1368 header.SetLabel(label)
1369 return header
1370
1371
1372 def get_profile_load_on_login_label(os_cal: bool) -> str:
1373 """Get the label for the profile load on login checkbox.
1374
1375 Args:
1376 os_cal (bool): True if the OS calibration is active.
1377
1378 Returns:
1379 str: The label for the profile load on login checkbox.
1380 """
1381 label = lang.getstr("profile.load_on_login")
1382 if sys.platform == "win32" and not os_cal:
1383 lstr = lang.getstr("calibration.preserve")
1384 if lang.getcode() != "de":
1385 lstr = lstr[0].lower() + lstr[1:]
1386 label += " && " + lstr
1387 return label
1388
1389
1390 def upload_colorimeter_correction(
1391 parent: None | wx.Window = None, params: None | dict = None
1392 ) -> None:
1393 """Upload colorimeter correction to online database.
1394
1395 Args:
1396 parent (None | wx.Window): The parent window.
1397 params (None | dict): The parameters for the upload.
1398 """
1399 path = "/index.php"
1400 failure_msg = lang.getstr("colorimeter_correction.upload.failure")
1401 # Check for duplicate
1402 resp = http_request(
1403 parent,
1404 f"colorimetercorrections.{DOMAIN}",
1405 "GET",
1406 path,
1407 # Remove CREATED date for calculating hash
1408 {
1409 "get": True,
1410 "hash": md5( # noqa: S324
1411 re.sub(
1412 rb'\nCREATED\s+".+?"\n', rb"\n\n", bytes(params["cgats"])
1413 ).strip()
1414 ).hexdigest(),
1415 },
1416 silent=True,
1417 )
1418 if resp and resp.read().strip().startswith(b"CC"):
1419 wx.CallAfter(
1420 InfoDialog,
1421 parent,
1422 msg=lang.getstr("colorimeter_correction.upload.exists"),
1423 ok=lang.getstr("ok"),
1424 bitmap=get_icon(32, "dialog-information"),
1425 )
1426 return
1427 # Upload
1428 params["put"] = True
1429 resp = http_request(
1430 parent,
1431 f"colorimetercorrections.{DOMAIN}",
1432 "POST",
1433 path,
1434 params,
1435 failure_msg=failure_msg,
1436 )
1437 if resp is not False:
1438 if resp.status == 201:
1439 wx.CallAfter(
1440 InfoDialog,
1441 parent,
1442 msg=lang.getstr("colorimeter_correction.upload.success"),
1443 ok=lang.getstr("ok"),
1444 bitmap=get_icon(32, "dialog-information"),
1445 )
1446 else:
1447 wx.CallAfter(
1448 InfoDialog,
1449 parent,
1450 msg=b"\n\n".join([failure_msg, resp.read().strip()]),
1451 ok=lang.getstr("ok"),
1452 bitmap=get_icon(32, "dialog-error"),
1453 )
1454
1455
1456 def install_scope_handler(
1457 event: None | wx.Event = None, dlg: None | wx.Dialog = None
1458 ) -> None:
1459 """Enable/disable the install systemwide button and the ok button.
1460
1461 Args:
1462 event (wx.Event, optional): The event that triggered this function.
1463 dlg (wx.Dialog, optional): The dialog to update. If None, uses the
1464 TopLevelParent of the event.
1465 """
1466 dlg = dlg or event.EventObject.TopLevelParent
1467 auth_needed = dlg.install_systemwide.GetValue()
1468 if hasattr(dlg.ok, "SetAuthNeeded"):
1469 dlg.ok.SetAuthNeeded(auth_needed)
1470 if hasattr(dlg, "alt"):
1471 dlg.alt.SetAuthNeeded(auth_needed)
1472 dlg.buttonpanel.Layout()
1473
1474
1475 def webbrowser_open(url: str, new: bool = False) -> bool:
1476 """Open a URL in the web browser.
1477
1478 Args:
1479 url (str): The URL to open.
1480 new (bool, optional): If True, open in a new browser window or tab.
1481 Defaults to False.
1482
1483 Returns:
1484 bool: True if the URL was opened successfully, False otherwise.
1485 """
1486 try:
1487 webbrowser.open(url, new=new)
1488 return True
1489 except Exception as exception:
1490 show_result_dialog(exception)
1491 return False
1492
1493
1494 class Dummy:
1495 """Useful if we need an object to attach arbitrary attributes."""
1496
1497
1498 class IncrementingInt:
1499 """A integer that increments by `step` each time it is used.
1500
1501 Args:
1502 start (int): The starting value of the integer.
1503 stop (int, optional): The value at which to stop incrementing. Defaults
1504 to None.
1505 step (int): The amount to increment by each time. Defaults to 1.
1506 """
1507
1508 def __init__(self, start: int = 0, stop: None | int = None, step: int = 1) -> None:
1509 self.i = start
1510 self.stop = stop
1511 self.step = step
1512
1513 def __int__(self) -> int:
1514 """Return the current value and increment it by `step`.
1515
1516 Returns:
1517 int: The current value before incrementing.
1518 """
1519 i = self.i
1520 if self.stop is None or self.i < self.stop:
1521 self.i += self.step
1522 return i
1523
1524
1525 class ExtraArgsFrame(BaseFrame):
1526 """Extra commandline arguments window.
1527
1528 Args:
1529 parent (wx.Window): The parent window for the ExtraArgsFrame.
1530 """
1531
1532 def __init__(self, parent: wx.Window) -> None:
1533 self.res = TempXmlResource(get_data_path(os.path.join("xrc", "extra.xrc")))
1534 self.res.InsertHandler(xh_floatspin.FloatSpinCtrlXmlHandler())
1535 self.res.InsertHandler(xh_hstretchstatbmp.HStretchStaticBitmapXmlHandler())
1536 self.res.InsertHandler(xh_bitmapctrls.BitmapButton())
1537 self.res.InsertHandler(xh_bitmapctrls.StaticBitmap())
1538 if hasattr(wx, "PreFrame"):
1539 # Classic
1540 pre = wx.PreFrame()
1541 self.res.LoadOnFrame(pre, parent, "extra_args")
1542 self.PostCreate(pre)
1543 else:
1544 # Phoenix
1545 wx.Frame.__init__(self)
1546 self.res.LoadFrame(self, parent, "extra_args")
1547 self.init()
1548 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
1549
1550 self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
1551
1552 self.set_child_ctrls_as_attrs(self)
1553
1554 child = self.environment_label
1555 font = child.Font
1556 font.SetWeight(wx.FONTWEIGHT_BOLD)
1557 child.Font = font
1558
1559 # Bind event handlers
1560 self.Bind(
1561 wx.EVT_TEXT,
1562 self.extra_args_handler,
1563 id=self.extra_args_dispcal_ctrl.GetId(),
1564 )
1565 self.Bind(
1566 wx.EVT_TEXT,
1567 self.extra_args_handler,
1568 id=self.extra_args_dispread_ctrl.GetId(),
1569 )
1570 self.Bind(
1571 wx.EVT_TEXT,
1572 self.extra_args_handler,
1573 id=self.extra_args_spotread_ctrl.GetId(),
1574 )
1575 self.Bind(
1576 wx.EVT_TEXT,
1577 self.extra_args_handler,
1578 id=self.extra_args_specplot_ctrl.GetId(),
1579 )
1580 self.Bind(
1581 wx.EVT_TEXT,
1582 self.extra_args_handler,
1583 id=self.extra_args_colprof_ctrl.GetId(),
1584 )
1585 self.Bind(
1586 wx.EVT_TEXT,
1587 self.extra_args_handler,
1588 id=self.extra_args_collink_ctrl.GetId(),
1589 )
1590 self.Bind(
1591 wx.EVT_TEXT, self.extra_args_handler, id=self.extra_args_targen_ctrl.GetId()
1592 )
1593
1594 self.setup_language()
1595 self.update_controls()
1596
1597 def OnClose(self, event: wx.Event) -> None: # noqa: N802
1598 """Handle the close event for the ExtraArgsFrame.
1599
1600 Args;
1601 event (wx.Event): The close event.
1602 """
1603 self.Hide()
1604
1605 def extra_args_handler(self, event: wx.Event) -> None:
1606 """Handle changes to the extra arguments controls.
1607
1608 Args:
1609 event (wx.Event): The event triggered by a control change.
1610 """
1611 mapping = {
1612 self.extra_args_dispcal_ctrl.GetId(): "extra_args.dispcal",
1613 self.extra_args_dispread_ctrl.GetId(): "extra_args.dispread",
1614 self.extra_args_spotread_ctrl.GetId(): "extra_args.spotread",
1615 self.extra_args_specplot_ctrl.GetId(): "extra_args.specplot",
1616 self.extra_args_colprof_ctrl.GetId(): "extra_args.colprof",
1617 self.extra_args_collink_ctrl.GetId(): "extra_args.collink",
1618 self.extra_args_targen_ctrl.GetId(): "extra_args.targen",
1619 }
1620 pref = mapping.get(event.GetId())
1621 if pref:
1622 ctrl = self.FindWindowById(event.GetId())
1623 value = ctrl.GetValue()
1624 setcfg(pref, value)
1625
1626 def update_controls(self) -> None:
1627 """Update the controls with the current configuration values."""
1628 self.extra_args_dispcal_ctrl.ChangeValue(getcfg("extra_args.dispcal"))
1629 self.extra_args_dispread_ctrl.ChangeValue(getcfg("extra_args.dispread"))
1630 self.extra_args_spotread_ctrl.ChangeValue(getcfg("extra_args.spotread"))
1631 self.extra_args_specplot_ctrl.ChangeValue(getcfg("extra_args.specplot"))
1632 self.extra_args_colprof_ctrl.ChangeValue(getcfg("extra_args.colprof"))
1633 self.extra_args_collink_ctrl.ChangeValue(getcfg("extra_args.collink"))
1634 self.extra_args_targen_ctrl.ChangeValue(getcfg("extra_args.targen"))
1635 self.Sizer.SetSizeHints(self)
1636 self.Sizer.Layout()
1637
1638
1639 class GamapFrame(BaseFrame):
1640 """Gamut mapping options window.
1641
1642 Args:
1643 parent (wx.Window): The parent window for the gamut mapping options.
1644 """
1645
1646 def __init__(self, parent: wx.Window) -> None:
1647 self.res = TempXmlResource(get_data_path(os.path.join("xrc", "gamap.xrc")))
1648 self.res.InsertHandler(
1649 xh_filebrowsebutton.FileBrowseButtonWithHistoryXmlHandler()
1650 )
1651 self.res.InsertHandler(xh_hstretchstatbmp.HStretchStaticBitmapXmlHandler())
1652 self.res.InsertHandler(xh_bitmapctrls.BitmapButton())
1653 self.res.InsertHandler(xh_bitmapctrls.StaticBitmap())
1654 if hasattr(wx, "PreFrame"):
1655 # Classic
1656 pre = wx.PreFrame()
1657 self.res.LoadOnFrame(pre, parent, "gamapframe")
1658 self.PostCreate(pre)
1659 else:
1660 # Phoenix
1661 wx.Frame.__init__(self)
1662 self.res.LoadFrame(self, parent, "gamapframe")
1663 self.init()
1664 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
1665
1666 self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
1667
1668 self.panel = xrc.XRCCTRL(self, "panel")
1669
1670 self.set_child_ctrls_as_attrs(self)
1671
1672 child = self.gamut_mapping_ciecam02_label
1673 font = child.Font
1674 font.SetWeight(wx.FONTWEIGHT_BOLD)
1675 child.Font = font
1676
1677 self.gamap_profile = xrc.XRCCTRL(self, "gamap_profile")
1678 self.gamap_profile.changeCallback = self.gamap_profile_handler
1679 self.gamap_profile.SetHistory(get_data_path("ref", r"\.(icm|icc)$"))
1680 self.gamap_profile.SetMaxFontSize(11)
1681 self.droptarget = FileDrop(self)
1682 self.droptarget.drophandlers = {
1683 ".icc": self.drop_handler,
1684 ".icm": self.drop_handler,
1685 }
1686 self.gamap_profile.SetDropTarget(self.droptarget)
1687
1688 # Bind event handlers
1689 self.Bind(
1690 wx.EVT_CHECKBOX,
1691 self.gamap_perceptual_cb_handler,
1692 id=self.gamap_perceptual_cb.GetId(),
1693 )
1694 self.Bind(
1695 wx.EVT_CHOICE,
1696 self.gamap_perceptual_intent_handler,
1697 id=self.gamap_perceptual_intent_ctrl.GetId(),
1698 )
1699 self.Bind(
1700 wx.EVT_CHECKBOX,
1701 self.gamap_saturation_cb_handler,
1702 id=self.gamap_saturation_cb.GetId(),
1703 )
1704 self.Bind(
1705 wx.EVT_CHOICE,
1706 self.gamap_saturation_intent_handler,
1707 id=self.gamap_saturation_intent_ctrl.GetId(),
1708 )
1709 self.Bind(
1710 wx.EVT_CHOICE,
1711 self.gamap_src_viewcond_handler,
1712 id=self.gamap_src_viewcond_ctrl.GetId(),
1713 )
1714 self.Bind(
1715 wx.EVT_CHOICE,
1716 self.gamap_out_viewcond_handler,
1717 id=self.gamap_out_viewcond_ctrl.GetId(),
1718 )
1719 self.Bind(
1720 wx.EVT_CHOICE,
1721 self.gamap_default_intent_handler,
1722 id=self.gamap_default_intent_ctrl.GetId(),
1723 )
1724 self.Bind(
1725 wx.EVT_CHECKBOX,
1726 self.profile_quality_b2a_ctrl_handler,
1727 id=self.low_quality_b2a_cb.GetId(),
1728 )
1729 self.Bind(
1730 wx.EVT_CHECKBOX,
1731 self.profile_quality_b2a_ctrl_handler,
1732 id=self.b2a_hires_cb.GetId(),
1733 )
1734 for v in config.VALID_VALUES["profile.b2a.hires.size"]:
1735 v = f"{v}x{v}x{v}" if v > -1 else lang.getstr("auto")
1736 self.b2a_size_ctrl.Append(v)
1737 self.Bind(
1738 wx.EVT_CHOICE, self.b2a_size_ctrl_handler, id=self.b2a_size_ctrl.GetId()
1739 )
1740 self.Bind(
1741 wx.EVT_CHECKBOX,
1742 self.profile_quality_b2a_ctrl_handler,
1743 id=self.b2a_smooth_cb.GetId(),
1744 )
1745
1746 self.viewconds_ab = {}
1747 self.viewconds_ba = {}
1748 self.viewconds_out_ab = {}
1749
1750 self.intents_ab = {}
1751 self.intents_ba = {}
1752
1753 self.default_intent_ab = {}
1754 self.default_intent_ba = {}
1755 for i, ri in enumerate(config.VALID_VALUES["gamap_default_intent"]):
1756 self.default_intent_ab[i] = ri
1757 self.default_intent_ba[ri] = i
1758
1759 self.setup_language()
1760 self.update_controls()
1761 self.update_layout()
1762
1763 def OnClose(self, event: wx.Event) -> None: # noqa: N802
1764 """Handle the close event for the gamut mapping options window.
1765
1766 Args:
1767 event (wx.Event): The event that triggered the handler.
1768 """
1769 self.Hide()
1770
1771 def b2a_size_ctrl_handler(self, event: wx.Event) -> None:
1772 """Handle changes to the B2A size control.
1773
1774 Args:
1775 event (wx.Event): The event that triggered the handler.
1776 """
1777 v = config.VALID_VALUES["profile.b2a.hires.size"][
1778 self.b2a_size_ctrl.GetSelection()
1779 ]
1780 if (
1781 v != getcfg("profile.b2a.hires.size")
1782 and self.Parent
1783 and hasattr(self.Parent, "profile_settings_changed")
1784 ):
1785 self.Parent.profile_settings_changed()
1786 setcfg("profile.b2a.hires.size", v)
1787
1788 def drop_handler(self, path: str) -> None:
1789 """Handle dropping a file onto the gamut mapping profile control.
1790
1791 Args:
1792 path (str): The path of the dropped file.
1793 """
1794 self.gamap_profile.SetPath(path)
1795 self.gamap_profile_handler(True)
1796
1797 def gamap_profile_handler(self, event: None | wx.Event = None) -> None:
1798 """Handle changes to the gamut mapping profile.
1799
1800 Args:
1801 event (None | wx.Event): The event that triggered the handler.
1802 """
1803 v = self.gamap_profile.GetPath()
1804 p = bool(v) and os.path.exists(v)
1805 c = self.gamap_perceptual_cb.GetValue() or self.gamap_saturation_cb.GetValue()
1806 if p and c:
1807 try:
1808 profile = ICCProfile(v)
1809 except (OSError, ICCProfileInvalidError):
1810 p = False
1811 InfoDialog(
1812 self,
1813 msg=lang.getstr("profile.invalid") + "\n" + v,
1814 ok=lang.getstr("ok"),
1815 bitmap=get_icon(32, "dialog-error"),
1816 )
1817 self.gamap_profile.SetPath("")
1818 v = None
1819 else:
1820 src_viewcond = getcfg("gamap_src_viewcond")
1821 if event and (
1822 (
1823 src_viewcond in [None, *self.viewconds_out_nondisplay]
1824 and profile.profileClass in (b"mntr", b"spac")
1825 )
1826 or (
1827 src_viewcond not in self.viewconds_out_nondisplay
1828 and profile.profileClass not in (b"mntr", b"spac")
1829 )
1830 ):
1831 # pre-select suitable viewing condition
1832 src_viewcond = "pp" if profile.profileClass == b"prtr" else "mt"
1833 self.gamap_src_viewcond_ctrl.SetStringSelection(
1834 lang.getstr("gamap.viewconds." + src_viewcond)
1835 )
1836 self.gamap_src_viewcond_handler()
1837 if not self.gamap_out_viewcond_ctrl.Selection:
1838 current_profile = get_current_profile(True)
1839 if current_profile:
1840 if current_profile.profileClass == b"prtr":
1841 out_viewcond = "pp"
1842 else:
1843 out_viewcond = "mt"
1844 self.gamap_out_viewcond_ctrl.SetStringSelection(
1845 lang.getstr("gamap.viewconds." + out_viewcond)
1846 )
1847 self.gamap_out_viewcond_handler()
1848 enable_gamap = getcfg("profile.type") in ("l", "x", "X")
1849 self.gamap_perceptual_cb.Enable(enable_gamap)
1850 self.gamap_perceptual_intent_ctrl.Enable(self.gamap_perceptual_cb.GetValue())
1851 self.gamap_saturation_cb.Enable(enable_gamap)
1852 self.gamap_saturation_intent_ctrl.Enable(self.gamap_saturation_cb.GetValue())
1853 self.gamap_profile.Enable(c)
1854 self.gamap_src_viewcond_ctrl.Enable(p and c)
1855 self.gamap_out_viewcond_ctrl.Enable(p and c)
1856 if not ((p and c) or getcfg("profile.b2a.hires")):
1857 setcfg("gamap_default_intent", "p")
1858 self.gamap_default_intent_ctrl.SetSelection(
1859 self.default_intent_ba[getcfg("gamap_default_intent")]
1860 )
1861 self.gamap_default_intent_ctrl.Enable(
1862 (p and c) or (getcfg("profile.b2a.hires") and enable_gamap)
1863 )
1864 if (
1865 v != getcfg("gamap_profile")
1866 and self.Parent
1867 and hasattr(self.Parent, "profile_settings_changed")
1868 ):
1869 self.Parent.profile_settings_changed()
1870 setcfg("gamap_profile", v or None)
1871
1872 def gamap_perceptual_cb_handler(self, event: None | wx.Event = None) -> None:
1873 """Handle changes to the perceptual checkbox.
1874
1875 Args:
1876 event (None | wx.Event): The event that triggered the handler.
1877 """
1878 v = self.gamap_perceptual_cb.GetValue()
1879 if not v:
1880 self.gamap_saturation_cb.SetValue(False)
1881 self.gamap_saturation_cb_handler()
1882 if (
1883 int(v) != getcfg("gamap_perceptual")
1884 and self.Parent
1885 and hasattr(self.Parent, "profile_settings_changed")
1886 ):
1887 self.Parent.profile_settings_changed()
1888 setcfg("gamap_perceptual", int(v))
1889 self.gamap_profile_handler(event)
1890
1891 def gamap_perceptual_intent_handler(self, event: None | wx.Event = None) -> None:
1892 """Handle changes to the perceptual intent control.
1893
1894 Args:
1895 event (None | wx.Event): The event that triggered the handler.
1896 """
1897 v = self.intents_ba[self.gamap_perceptual_intent_ctrl.GetStringSelection()]
1898 if (
1899 v != getcfg("gamap_perceptual_intent")
1900 and self.Parent
1901 and hasattr(self.Parent, "profile_settings_changed")
1902 ):
1903 self.Parent.profile_settings_changed()
1904 setcfg("gamap_perceptual_intent", v)
1905
1906 def gamap_saturation_cb_handler(self, event: None | wx.Event = None) -> None:
1907 """Handle changes to the saturation checkbox.
1908
1909 Args:
1910 event (None | wx.Event): The event that triggered the handler.
1911 """
1912 perc = self.gamap_perceptual_cb.GetValue()
1913 v = self.gamap_saturation_cb.GetValue()
1914 if v:
1915 self.gamap_perceptual_cb.SetValue(True)
1916 self.gamap_perceptual_cb_handler()
1917 if (
1918 int(v) != getcfg("gamap_saturation")
1919 and self.Parent
1920 and hasattr(self.Parent, "profile_settings_changed")
1921 ):
1922 self.Parent.profile_settings_changed()
1923 setcfg("gamap_saturation", int(v))
1924 self.gamap_profile_handler(event and not perc)
1925
1926 def gamap_saturation_intent_handler(self, event: None | wx.Event = None) -> None:
1927 """Handle changes to the saturation intent control.
1928
1929 Args:
1930 event (None | wx.Event): The event that triggered the handler.
1931 """
1932 v = self.intents_ba[self.gamap_saturation_intent_ctrl.GetStringSelection()]
1933 if (
1934 v != getcfg("gamap_saturation_intent")
1935 and self.Parent
1936 and hasattr(self.Parent, "profile_settings_changed")
1937 ):
1938 self.Parent.profile_settings_changed()
1939 setcfg("gamap_saturation_intent", v)
1940
1941 def gamap_src_viewcond_handler(self, event: None | wx.Event = None) -> None:
1942 """Handle changes to the source viewing condition control.
1943
1944 Args:
1945 event (None | wx.Event): The event that triggered the handler.
1946 """
1947 v = self.viewconds_ba[self.gamap_src_viewcond_ctrl.GetStringSelection()]
1948 if (
1949 v != getcfg("gamap_src_viewcond")
1950 and self.Parent
1951 and hasattr(self.Parent, "profile_settings_changed")
1952 ):
1953 self.Parent.profile_settings_changed()
1954 setcfg("gamap_src_viewcond", v)
1955
1956 def gamap_out_viewcond_handler(self, event: None | wx.Event = None) -> None:
1957 """Handle changes to the output viewing condition control.
1958
1959 Args:
1960 event (wx.Event): The event that triggered the handler.
1961 """
1962 lstr = self.gamap_out_viewcond_ctrl.GetStringSelection()
1963 cur = getcfg("gamap_out_viewcond")
1964 v = self.viewconds_ba[lstr]
1965 if v != cur and event and v in self.viewconds_out_nondisplay:
1966 if not show_result_dialog(
1967 Warn(lang.getstr("warning.gamap.out_viewcond.nondisplay", lstr)),
1968 self,
1969 confirm=lang.getstr("ok"),
1970 ):
1971 self.gamap_out_viewcond_ctrl.SetStringSelection(self.viewconds_ab[cur])
1972 return
1973 setcfg("gamap_out_viewcond", v)
1974 if self.Parent and hasattr(self.Parent, "profile_settings_changed"):
1975 self.Parent.profile_settings_changed()
1976
1977 def gamap_default_intent_handler(self, event: None | wx.Event = None) -> None:
1978 """Handle changes to the default intent control.
1979
1980 Args:
1981 event (None | wx.Event): The event that triggered the handler.
1982 """
1983 v = self.gamap_default_intent_ctrl.GetSelection()
1984 if (
1985 self.default_intent_ab[v] != getcfg("gamap_default_intent")
1986 and self.Parent
1987 and hasattr(self.Parent, "profile_settings_changed")
1988 ):
1989 self.Parent.profile_settings_changed()
1990 setcfg("gamap_default_intent", self.default_intent_ab[v])
1991
1992 def profile_quality_b2a_ctrl_handler(self, event: wx.Event) -> None:
1993 """Handle changes to the B2A quality controls.
1994
1995 Args:
1996 event (wx.Event): The event that triggered the handler.
1997 """
1998 if (
1999 event.GetId() == self.low_quality_b2a_cb.GetId()
2000 and self.low_quality_b2a_cb.GetValue()
2001 ):
2002 self.b2a_hires_cb.Enable(False)
2003 else:
2004 self.b2a_hires_cb.Enable(getcfg("profile.type") in ("l", "x", "X"))
2005 hires = self.b2a_hires_cb.GetValue()
2006 self.low_quality_b2a_cb.Enable(not hires)
2007 if hires:
2008 if event.GetId() == self.b2a_smooth_cb.GetId():
2009 setcfg("profile.b2a.hires.smooth", int(self.b2a_smooth_cb.GetValue()))
2010 else:
2011 self.b2a_smooth_cb.SetValue(bool(getcfg("profile.b2a.hires.smooth")))
2012 else:
2013 self.b2a_smooth_cb.SetValue(False)
2014 v = "l" if self.low_quality_b2a_cb.GetValue() else None
2015 if (
2016 v != getcfg("profile.quality.b2a") or hires != getcfg("profile.b2a.hires")
2017 ) and self.Parent:
2018 self.Parent.profile_settings_changed()
2019 setcfg("profile.quality.b2a", v)
2020 setcfg("profile.b2a.hires", int(hires))
2021 self.b2a_size_ctrl.Enable(hires)
2022 self.b2a_smooth_cb.Enable(hires)
2023 self.gamap_profile_handler()
2024 if self.Parent:
2025 self.Parent.update_bpc()
2026 self.Parent.lut3d_update_b2a_controls()
2027 if hasattr(self.Parent, "lut3dframe"):
2028 self.Parent.lut3dframe.update_controls()
2029
2030 def setup_language(self) -> None:
2031 """Substitute translated strings for menus, controls, labels and tooltips."""
2032 BaseFrame.setup_language(self)
2033
2034 self.gamap_profile.dialogTitle = lang.getstr("gamap.profile")
2035 self.gamap_profile.fileMask = lang.getstr("filetype.icc") + "|*.icc;*.icm"
2036
2037 intents = list(config.INTENTS)
2038 if (
2039 self.Parent
2040 and hasattr(self.Parent, "worker")
2041 and self.Parent.worker.argyll_version < [1, 3, 3]
2042 ):
2043 intents.remove("pa")
2044 if (
2045 self.Parent
2046 and hasattr(self.Parent, "worker")
2047 and self.Parent.worker.argyll_version < [1, 8, 3]
2048 ):
2049 intents.remove("lp")
2050 for v in intents:
2051 lstr = lang.getstr(f"gamap.intents.{v}")
2052 self.intents_ab[v] = lstr
2053 self.intents_ba[lstr] = v
2054
2055 self.gamap_perceptual_intent_ctrl.SetItems(list(self.intents_ab.values()))
2056 self.gamap_saturation_intent_ctrl.SetItems(list(self.intents_ab.values()))
2057
2058 self.viewconds_ab[None] = lang.getstr("none")
2059 self.viewconds_ba[lang.getstr("none")] = None
2060 self.viewconds_out_nondisplay = ["pp", "pe", "pc", "pcd", "ob", "cx"]
2061 # if False:
2062 # # NEVER - filter dest viewing conditions
2063 # self.viewconds_out_ignore = self.viewconds_out_nondisplay
2064 # else:
2065 viewconds_out_ignore = []
2066
2067 for v in VIEWCONDS:
2068 if (
2069 self.Parent
2070 and hasattr(self.Parent, "worker")
2071 and (
2072 (v == "pc" and self.Parent.worker.argyll_version < [1, 1, 1])
2073 or (v == "tv" and self.Parent.worker.argyll_version < [1, 6, 0])
2074 )
2075 ):
2076 continue
2077 lstr = lang.getstr(f"gamap.viewconds.{v}")
2078 self.viewconds_ab[v] = lstr
2079 self.viewconds_ba[lstr] = v
2080 if v not in viewconds_out_ignore:
2081 self.viewconds_out_ab[v] = lstr
2082
2083 self.gamap_src_viewcond_ctrl.SetItems(list(self.viewconds_ab.values()))
2084 self.gamap_out_viewcond_ctrl.SetItems(
2085 [lang.getstr("none"), *self.viewconds_out_ab.values()]
2086 )
2087
2088 self.gamap_default_intent_ctrl.SetItems(
2089 [
2090 lang.getstr("gamap.intents." + v)
2091 for v in config.VALID_VALUES["gamap_default_intent"]
2092 ]
2093 )
2094
2095 def update_controls(self) -> None:
2096 """Update controls with values from the configuration."""
2097 # B2A quality
2098 enable_gamap = getcfg("profile.type") in ("l", "x", "X")
2099 enable_b2a_extra = getcfg("profile.type") in ("l", "x", "X")
2100 b2a_hires = enable_b2a_extra and bool(getcfg("profile.b2a.hires"))
2101 self.low_quality_b2a_cb.SetValue(
2102 enable_gamap
2103 and getcfg("profile.quality.b2a") in ("l", "n")
2104 and not b2a_hires
2105 )
2106 self.low_quality_b2a_cb.Enable(enable_gamap and not b2a_hires)
2107 self.b2a_hires_cb.SetValue(b2a_hires)
2108 self.b2a_hires_cb.Enable(
2109 enable_b2a_extra and not self.low_quality_b2a_cb.GetValue()
2110 )
2111 self.b2a_size_ctrl.SetSelection(
2112 config.VALID_VALUES["profile.b2a.hires.size"].index(
2113 getcfg("profile.b2a.hires.size")
2114 )
2115 )
2116 self.b2a_size_ctrl.Enable(b2a_hires)
2117 self.b2a_smooth_cb.SetValue(
2118 b2a_hires and bool(getcfg("profile.b2a.hires.smooth"))
2119 )
2120 self.b2a_smooth_cb.Enable(b2a_hires)
2121
2122 # CIECAM02
2123 self.gamap_profile.SetPath(getcfg("gamap_profile"))
2124 self.gamap_perceptual_cb.SetValue(
2125 enable_gamap and bool(getcfg("gamap_perceptual"))
2126 )
2127 self.gamap_perceptual_intent_ctrl.SetStringSelection(
2128 self.intents_ab.get(
2129 getcfg("gamap_perceptual_intent"),
2130 self.intents_ab.get(DEFAULTS["gamap_perceptual_intent"]),
2131 )
2132 )
2133 self.gamap_saturation_cb.SetValue(
2134 enable_gamap and bool(getcfg("gamap_saturation"))
2135 )
2136 self.gamap_saturation_intent_ctrl.SetStringSelection(
2137 self.intents_ab.get(
2138 getcfg("gamap_saturation_intent"),
2139 self.intents_ab.get(DEFAULTS["gamap_saturation_intent"]),
2140 )
2141 )
2142 self.gamap_src_viewcond_ctrl.SetStringSelection(
2143 self.viewconds_ab.get(
2144 getcfg("gamap_src_viewcond", False),
2145 self.viewconds_ab.get(DEFAULTS.get("gamap_src_viewcond")),
2146 )
2147 )
2148 self.gamap_out_viewcond_ctrl.SetStringSelection(
2149 self.viewconds_ab.get(
2150 getcfg("gamap_out_viewcond"),
2151 self.viewconds_ab.get(DEFAULTS.get("gamap_out_viewcond")),
2152 )
2153 )
2154
2155 self.gamap_profile_handler()
2156
2157
2158 class MainFrame(ReportFrame, BaseFrame, LUT3DMixin):
2159 """Display calibrator main application window.
2160
2161 Args:
2162 worker (Worker): The worker instance to handle background tasks.
2163 """
2164
2165 def __init__(self, worker: Worker) -> None:
2166 # XYZbpout will be set to the blackpoint of the selected profile. This is
2167 # used to determine if 3D LUT or measurement report black output offset
2168 # controls should be shown. Set an initial value slightly above zero so
2169 # output offset controls are shown if the selected profile doesn't exist
2170 # and "Create 3D LUT after profiling" is disabled.
2171 self.XYZbpout = [0.001, 0.001, 0.001]
2172 # Check for required resource files and get pre-canned testcharts
2173 self.dist_testcharts = []
2174 self.dist_testchart_names = []
2175 self.menubar = None
2176 missing = []
2177 for filename in RES_FILES:
2178 path, ext = (
2179 get_data_path(os.path.sep.join(filename.split("/"))),
2180 os.path.splitext(filename)[1],
2181 )
2182 if not path or not os.path.isfile(path):
2183 missing.append(filename)
2184 elif ext.lower() == ".ti1":
2185 self.dist_testcharts.append(path)
2186 self.dist_testchart_names.append(os.path.basename(path))
2187 if missing:
2188 wx.CallAfter(
2189 show_result_dialog,
2190 lang.getstr("resources.notfound.warning")
2191 + "\n"
2192 + str("\n".join(missing)),
2193 self,
2194 )
2195
2196 # Initialize GUI
2197 self.res = TempXmlResource(get_data_path(os.path.join("xrc", "main.xrc")))
2198 self.res.InsertHandler(xh_fancytext.StaticFancyTextCtrlXmlHandler())
2199 self.res.InsertHandler(xh_floatspin.FloatSpinCtrlXmlHandler())
2200 self.res.InsertHandler(xh_hstretchstatbmp.HStretchStaticBitmapXmlHandler())
2201 self.res.InsertHandler(xh_bitmapctrls.BitmapButton())
2202 self.res.InsertHandler(xh_bitmapctrls.StaticBitmap())
2203 if hasattr(wx, "PreFrame"):
2204 # Classic
2205 pre = wx.PreFrame()
2206 self.res.LoadOnFrame(pre, None, "mainframe")
2207 self.PostCreate(pre)
2208 else:
2209 # Phoenix
2210 wx.Frame.__init__(self)
2211 self.res.LoadFrame(self, None, "mainframe")
2212 self.init()
2213 self.worker = worker
2214 self.worker.owner = self
2215 result = self.worker.create_tempdir()
2216 if isinstance(result, Exception):
2217 print(result)
2218 self.init_frame()
2219 self.init_defaults()
2220 self.set_child_ctrls_as_attrs(self)
2221 self.init_infoframe()
2222 self.init_measureframe()
2223 self.init_menus()
2224 self.init_controls()
2225 self.show_advanced_options_handler()
2226 self.setup_language()
2227 self.update_displays(update_ccmx_items=False)
2228 self.update_comports()
2229 self.mr_init_controls()
2230 # If a previous session crashed during a CCXX measurement, the config
2231 # retains testchart.file set to the CCXX testchart and backup keys set,
2232 # causing is_ccxx_testchart() to return True and hiding the correction
2233 # section. Restore backed-up values before update_controls() runs.
2234 self.restore_measurement_mode()
2235 self.restore_testchart()
2236 self.update_controls(update_ccmx_items=False)
2237 scrollrate_x = 2 if self.calpanel.VirtualSize[0] > self.calpanel.Size[0] else 0
2238 self.calpanel.SetScrollRate(scrollrate_x, 2)
2239 x, y = getcfg("position.x", False), getcfg("position.y", False)
2240 if None not in (x, y):
2241 self.SetSaneGeometry(x, y)
2242 self.set_size(True, True)
2243 if None in (x, y):
2244 self.Center()
2245 self.Bind(wx.EVT_MOVE, self.OnMove, self)
2246 verbose_print(lang.getstr("success"))
2247
2248 # Check for and load default calibration
2249 if len(self.worker.displays):
2250 if getcfg("calibration.file", False):
2251 # Load LUT curves from last used .cal file
2252 self.load_cal(silent=True)
2253 else:
2254 # Load LUT curves from current display profile (if any, and
2255 # if it contains curves)
2256 self.load_display_profile_cal(None)
2257
2258 self.init_timers()
2259 verbose_print(lang.getstr("ready"))
2260
2261 def log(self) -> None:
2262 """Append log buffer contents to the log window."""
2263 # We do this after all initialization because the log.log() function
2264 # expects the window to be fully created and accessible via
2265 # wx.GetApp().frame.infoframe
2266 if not hasattr(self, "logoffset"):
2267 # Skip the very first line, which is just '=' * 80
2268 self.logoffset = 1
2269 else:
2270 self.logoffset = 0
2271 LOGBUFFER.seek(0)
2272 msg = "".join(
2273 [line.decode("UTF-8", "replace") for line in LOGBUFFER][self.logoffset :]
2274 ).rstrip()
2275 LOGBUFFER.truncate(0)
2276 if msg:
2277 self.infoframe.Log(msg)
2278
2279 def init_defaults(self) -> None:
2280 """Initialize GUI-specific defaults."""
2281 DEFAULTS.update(
2282 {
2283 "position.info.x": self.GetDisplay().ClientArea[0] + 30,
2284 "position.info.y": self.GetDisplay().ClientArea[1] + 30,
2285 "position.lut_viewer.x": self.GetDisplay().ClientArea[0] + 40,
2286 "position.lut_viewer.y": self.GetDisplay().ClientArea[1] + 40,
2287 "position.progress.x": self.GetDisplay().ClientArea[0] + 30,
2288 "position.progress.y": self.GetDisplay().ClientArea[1] + 30,
2289 "position.x": self.GetDisplay().ClientArea[0] + 20,
2290 "position.y": self.GetDisplay().ClientArea[1] + 20,
2291 }
2292 )
2293
2294 self.recent_cals = getcfg("recent_cals").split(os.pathsep)
2295 while "" in self.recent_cals:
2296 self.recent_cals.remove("")
2297 self.recent_cals.insert(0, "")
2298
2299 self.presets = []
2300 presets = get_data_path("presets", r".*\.(?:icc|icm)$")
2301 if isinstance(presets, list):
2302 self.presets = natsort(presets)
2303 self.presets.reverse()
2304 for preset in self.presets:
2305 if preset in self.recent_cals:
2306 self.recent_cals.remove(preset)
2307 self.recent_cals.insert(1, preset)
2308
2309 self.static_labels = []
2310
2311 self.updatingctrls = False
2312
2313 # Left side - internal enumeration, right side - commmandline
2314 self.whitepoint_colortemp_loci_ab = {0: "t", 1: "T"}
2315
2316 # Left side - commmandline, right side - internal enumeration
2317 self.whitepoint_colortemp_loci_ba = {"t": 0, "T": 1}
2318
2319 # Left side - commmandline, right side - internal enumeration
2320 self.quality_ab = {1: "v", 2: "l", 3: "m", 4: "h", 5: "u"}
2321 self.quality_b2a_ab = {0: "n", 1: "l", 2: "m", 3: "h", 4: "u"}
2322
2323 # Left side - commmandline, right side - internal enumeration
2324 self.quality_ba = swap_dict_keys_values(self.quality_ab)
2325
2326 self.testchart_defaults = config.TESTCHART_DEFAULTS
2327 self.testcharts = []
2328 self.testchart_names = []
2329
2330 # Left side - commmandline, right side - .cal file
2331 self.trc_ab = {"l": "L_STAR", "709": "REC709", "s": "sRGB", "240": "SMPTE240M"}
2332
2333 # Left side - .cal file, right side - commmandline
2334 self.trc_ba = swap_dict_keys_values(self.trc_ab)
2335
2336 # Left side - internal enumeration, right side - commmandline
2337 self.trc_types_ab = {0: "g", 1: "G"}
2338
2339 # Left side - commmandline, right side - internal enumeration
2340 self.trc_types_ba = swap_dict_keys_values(self.trc_types_ab)
2341
2342 self.trc_presets = ["1.8", "2.0", "2.2", "2.4"]
2343
2344 self.whitepoint_presets = ["5000", "5500", "6000", "6500"]
2345
2346 def init_frame(self) -> None:
2347 """Initialize the main window and its event handlers.
2348
2349 Controls are initialized in a separate step (see init_controls).
2350
2351 """
2352 # UGLY HACK: This 'print' call fixes a GTK assertion and
2353 # segfault under Arch Linux when setting the window title
2354 print("")
2355 title = f"{APPNAME} {VERSION_STRING}"
2356 self.SetTitle(title)
2357 self.SetMaxSize((-1, -1))
2358 self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
2359 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
2360 self.Bind(wx.EVT_SIZE, self.OnResize, self)
2361 self.Bind(wx.EVT_DISPLAY_CHANGED, self.check_update_controls)
2362 self.droptarget = FileDrop(self)
2363 self.droptarget.drophandlers = {
2364 ".7z": self.cal_drop_handler,
2365 ".cal": self.cal_drop_handler,
2366 ".ccmx": self.ccxx_drop_handler,
2367 ".ccss": self.ccxx_drop_handler,
2368 ".icc": self.cal_drop_handler,
2369 ".icm": self.cal_drop_handler,
2370 ".tar.gz": self.cal_drop_handler,
2371 ".ti1": self.ti1_drop_handler,
2372 ".ti3": self.ti3_drop_handler,
2373 ".tgz": self.cal_drop_handler,
2374 ".zip": self.cal_drop_handler,
2375 }
2376
2377 # Main panel
2378 self.panel = xrc.XRCCTRL(self, "panel")
2379 self.panel.SetDropTarget(self.droptarget)
2380
2381 # Header
2382 # Its width also determines the initial min width of the main window
2383 # after SetSizeHints and Layout
2384 self.headerbordertop = xrc.XRCCTRL(self, "headerbordertop")
2385 self.header = get_header(self.panel)
2386 self.headerpanel = xrc.XRCCTRL(self, "headerpanel")
2387 self.headerpanel.ContainingSizer.Insert(1, self.header, flag=wx.EXPAND)
2388 y = 64
2389 w = 80
2390 h = 120
2391 scale = max(getcfg("app.dpi") / config.get_default_dpi(), 1)
2392 if scale > 1:
2393 y, w, h = [math.floor(v * scale) for v in (y, w, h)]
2394 self.header_btm = BitmapBackgroundPanel(self.headerpanel, size=(w, -1))
2395 self.header_btm.BackgroundColour = "#0e59a9"
2396 self.header_btm.scalebitmap = False, False
2397 header_bmp = get_bitmap("theme/header", display_missing_icon=False)
2398 if header_bmp.Size[0] >= w and header_bmp.Size[1] >= h + y:
2399 header_bmp = header_bmp.GetSubBitmap((0, y, w, h))
2400 self.header_btm.SetBitmap(header_bmp)
2401 self.headerpanel.Sizer.Insert(0, self.header_btm, flag=wx.ALIGN_TOP | wx.EXPAND)
2402 # separator = BitmapBackgroundPanel(self.panel, size=(-1, 1))
2403 # separator.SetBackgroundColour(
2404 # wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
2405 # )
2406 # self.panel.Sizer.Insert(2, separator, flag=wx.EXPAND)
2407
2408 # Calibration settings panel
2409 self.calpanel = xrc.XRCCTRL(self, "calpanel")
2410 self.display_instrument_panel = xrc.XRCCTRL(self, "display_instrument_panel")
2411 self.calibration_settings_panel = xrc.XRCCTRL(
2412 self, "calibration_settings_panel"
2413 )
2414 self.profile_settings_panel = xrc.XRCCTRL(self, "profile_settings_panel")
2415 self.lut3d_settings_panel = xrc.XRCCTRL(self, "lut3d_settings_panel")
2416
2417 # Verification / measurement report
2418 res = TempXmlResource(get_data_path(os.path.join("xrc", "report.xrc")))
2419 res.InsertHandler(xh_fancytext.StaticFancyTextCtrlXmlHandler())
2420 res.InsertHandler(xh_filebrowsebutton.FileBrowseButtonWithHistoryXmlHandler())
2421 res.InsertHandler(xh_hstretchstatbmp.HStretchStaticBitmapXmlHandler())
2422 res.InsertHandler(xh_bitmapctrls.BitmapButton())
2423 res.InsertHandler(xh_bitmapctrls.StaticBitmap())
2424 self.mr_settings_panel = res.LoadPanel(self.calpanel, "panel")
2425 self.calpanel.Sizer.__init__() # fixes #507
2426 self.calpanel.Sizer.Add(self.mr_settings_panel, 1, flag=wx.EXPAND)
2427
2428 # Make info panels use theme color
2429 for panel_name in [
2430 "display_instrument_info_panel",
2431 "calibration_settings_info_panel",
2432 "profile_settings_info_panel",
2433 "lut3d_settings_info_panel",
2434 "mr_settings_info_panel",
2435 ]:
2436 panel = xrc.XRCCTRL(self, panel_name)
2437 panel.BackgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
2438 for child in panel.Children:
2439 if isinstance(child, wx.Panel):
2440 child.BackgroundColour = panel.BackgroundColour
2441 setattr(self, panel_name, panel)
2442
2443 # Show display type help
2444 btn = PlateButton(
2445 self.display_instrument_info_panel,
2446 -1,
2447 "info.display_tech.show",
2448 get_icon(16, "info"),
2449 )
2450 set_platebutton_bitmaps(btn, "info")
2451 self.display_instrument_info_panel.Sizer.Add((0, int(14 * scale)))
2452 self.display_instrument_info_panel.Sizer.Add(
2453 btn, flag=wx.LEFT, border=int((16 + 32 + 7) * scale)
2454 )
2455 self.display_instrument_info_panel.Sizer.Add((0, int(12 * scale)))
2456 self.display_tech_info_show_btn = btn
2457
2458 # Button panel
2459 self.buttonpanel = xrc.XRCCTRL(self, "buttonpanel")
2460 sizer = self.buttonpanel.ContainingSizer
2461 if hasattr(sizer, "GetItemIndex"):
2462 # wxPython 2.8.12+
2463 # separator = BitmapBackgroundPanel(self.panel, size=(-1, 1))
2464 # separator.SetBackgroundColour(
2465 # wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
2466 # )
2467 # sizer.Insert(sizer.GetItemIndex(self.buttonpanel), separator,
2468 # flag=wx.EXPAND)
2469 self.buttonpanelheader = BitmapBackgroundPanel(
2470 self.panel, size=(-1, int(15 * scale))
2471 )
2472 # bmp = get_bitmap("theme/gradient", False)
2473 bmp = get_bitmap("theme/shadow-bordertop", display_missing_icon=False)
2474 # if bmp.Size[0] >= 8 and bmp.Size[1] >= 96:
2475 # bmp = bmp.GetSubBitmap(
2476 # (0, 1, 8, 15)
2477 # ).ConvertToImage().Mirror(False).ConvertToBitmap()
2478 # image = bmp.ConvertToImage()
2479 # databuffer = image.GetDataBuffer()
2480 # for i, byte in enumerate(databuffer):
2481 # if byte > "\0":
2482 # databuffer[i] = chr(int(min(round(ord(byte) *
2483 # (255.0 / 223.0)), 255)))
2484 # bmp = image.ConvertToBitmap()
2485 self.buttonpanelheader.SetBitmap(bmp)
2486 sizer.Insert(
2487 sizer.GetItemIndex(self.buttonpanel),
2488 self.buttonpanelheader,
2489 flag=wx.EXPAND,
2490 )
2491 # bgcolor = self.buttonpanel.BackgroundColour
2492 # self.buttonpanel.SetBackgroundColour(wx.Colour(*[int(v * .93)
2493 # for v in bgcolor[:3]]))
2494 self.buttonpanel.SetBackgroundColour(self.buttonpanel.BackgroundColour)
2495 self.buttonpanelheader.SetBackgroundColour(
2496 self.buttonpanel.BackgroundColour
2497 )
2498 self.buttonpanelheader.blend = True
2499
2500 # Tab panel
2501 self.tabpanel = xrc.XRCCTRL(self, "tabpanel")
2502 sizer = self.tabpanel.ContainingSizer
2503 if hasattr(sizer, "GetItemIndex"):
2504 # wxPython 2.8.12+
2505 # separator = BitmapBackgroundPanel(self.panel, size=(-1, 1))
2506 # separator.SetBackgroundColour(
2507 # wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
2508 # )
2509 # sizer.Insert(sizer.GetItemIndex(self.tabpanel) + 1, separator,
2510 # flag=wx.EXPAND)
2511 # self.tabpanelheader = BitmapBackgroundPanel(self.panel,
2512 # size=(-1, 15))
2513 self.tabpanelheader = BitmapBackgroundPanel(self.panel, size=(-1, 14))
2514 # self.tabpanelfooter = BitmapBackgroundPanel(self.panel,
2515 # size=(-1, 15))
2516 # bmp = get_bitmap("theme/gradient", False)
2517 # if bmp.Size[0] >= 8 and bmp.Size[1] >= 96:
2518 # sub = bmp.GetSubBitmap((0, 1, 8, 15)).ConvertToImage()
2519 # bmp = sub.Mirror(False).ConvertToBitmap()
2520 # image2 = bmp.ConvertToImage()
2521 # databuffer = image2.GetDataBuffer()
2522 # for i, byte in enumerate(databuffer):
2523 # if byte > "\0":
2524 # databuffer[i] = chr(int(min(round((ord(byte) - 153) *
2525 # (255.0 / 70.0)), 255)))
2526 # bmp = image2.ConvertToBitmap()
2527 # self.tabpanelheader.SetBitmap(bmp)
2528 # bmp = image.Mirror(False).ConvertToBitmap()
2529 # self.tabpanelfooter.SetBitmap(bmp)
2530 sizer.Insert(
2531 sizer.GetItemIndex(self.tabpanel), self.tabpanelheader, flag=wx.EXPAND
2532 )
2533 # sizer.Insert(sizer.GetItemIndex(self.tabpanel) + 1,
2534 # self.tabpanelfooter, flag=wx.EXPAND)
2535 self.tabpanel.BackgroundColour = "#202020"
2536 self.tabpanel.ForegroundColour = "#EEEEEE"
2537 self.tabpanelheader.SetBackgroundColour(self.tabpanel.BackgroundColour)
2538 self.tabpanelheader.blend = True
2539 # self.tabpanelfooter.SetBackgroundColour(self.tabpanel.BackgroundColour)
2540 # self.tabpanelfooter.blend = True
2541
2542 # Add tab buttons
2543 self.display_instrument_btn = TabButton(
2544 self.tabpanel,
2545 -1,
2546 label="display-instrument",
2547 bmp=get_icon(32, "display-instrument"),
2548 style=platebtn.PB_STYLE_TOGGLE,
2549 )
2550 self.display_instrument_btn.Bind(wx.EVT_TOGGLEBUTTON, self.tab_select_handler)
2551 self.tabpanel.Sizer.Insert(
2552 1, self.display_instrument_btn, flag=wx.LEFT, border=16
2553 )
2554 self.calibration_settings_btn = TabButton(
2555 self.tabpanel,
2556 -1,
2557 label="calibration",
2558 bmp=get_icon(32, "calibration"),
2559 style=platebtn.PB_STYLE_TOGGLE,
2560 )
2561 self.calibration_settings_btn.Bind(wx.EVT_TOGGLEBUTTON, self.tab_select_handler)
2562 self.tabpanel.Sizer.Insert(
2563 2, self.calibration_settings_btn, flag=wx.LEFT, border=32
2564 )
2565 self.profile_settings_btn = TabButton(
2566 self.tabpanel,
2567 -1,
2568 label="profiling",
2569 bmp=get_icon(32, "profiling"),
2570 style=platebtn.PB_STYLE_TOGGLE,
2571 )
2572 self.profile_settings_btn.Bind(wx.EVT_TOGGLEBUTTON, self.tab_select_handler)
2573 self.tabpanel.Sizer.Insert(
2574 3, self.profile_settings_btn, flag=wx.LEFT, border=32
2575 )
2576 self.lut3d_settings_btn = TabButton(
2577 self.tabpanel,
2578 -1,
2579 label="3dlut",
2580 bmp=get_icon(32, "3dlut"),
2581 style=platebtn.PB_STYLE_TOGGLE,
2582 )
2583 self.lut3d_settings_btn.Bind(wx.EVT_TOGGLEBUTTON, self.tab_select_handler)
2584 self.tabpanel.Sizer.Insert(
2585 4, self.lut3d_settings_btn, flag=wx.LEFT | wx.RIGHT, border=32
2586 )
2587 self.mr_settings_btn = TabButton(
2588 self.tabpanel,
2589 -1,
2590 label="verification",
2591 bmp=get_icon(32, "dialog-ok"),
2592 style=platebtn.PB_STYLE_TOGGLE,
2593 )
2594 self.mr_settings_btn.Bind(wx.EVT_TOGGLEBUTTON, self.tab_select_handler)
2595 self.tabpanel.Sizer.Insert(5, self.mr_settings_btn, flag=wx.RIGHT, border=16)
2596 for btn in (
2597 self.display_instrument_btn,
2598 self.calibration_settings_btn,
2599 self.profile_settings_btn,
2600 self.lut3d_settings_btn,
2601 self.mr_settings_btn,
2602 ):
2603 set_bitmap_labels(btn, True, False, False)
2604 btn.SetPressColor(wx.Colour(0x66, 0x66, 0x66))
2605 btn.SetLabelColor(self.tabpanel.ForegroundColour, wx.WHITE)
2606 self.tab_select_handler(self.display_instrument_btn)
2607
2608 self.profile_info = {}
2609 self.measureframes = []
2610 self.ccxx_plot_windows = {}
2611
2612 def init_timers(self) -> None:
2613 """Setup the timers for display/instrument detection and profile name."""
2614 self.update_profile_name_timer = wx.Timer(self)
2615 self.Bind(
2616 wx.EVT_TIMER, self.update_profile_name, self.update_profile_name_timer
2617 )
2618
2619 # Global key handler
2620 self._key_is_down = None
2621 self.check_keydown_timer = wx.Timer(self)
2622 self.Bind(wx.EVT_TIMER, self.check_keydown, self.check_keydown_timer)
2623
2624 # macOS only: watch for the OS clobbering the VideoLUT to black after a
2625 # calibration was loaded/installed (issue #694) and re-load it. Only
2626 # fires while idle (not measuring), so it can't disturb a measurement.
2627 self.lut_watch_timer = wx.Timer(self)
2628 self.Bind(wx.EVT_TIMER, self.check_lut_clobbered, self.lut_watch_timer)
2629
2630 def check_keydown(self, event: wx.TimerEvent) -> None:
2631 """Check if the ALT key is pressed and update the measurement report button.
2632
2633 Args:
2634 event (wx.TimerEvent): The timer event triggered by the timer.
2635 """
2636 if self._key_is_down != wx.WXK_ALT and wx.GetKeyState(wx.WXK_ALT):
2637 self._key_is_down = wx.WXK_ALT
2638 self.measurement_report_btn.Label = lang.getstr("self_check_report")
2639 self.measurement_report_btn.Refresh()
2640 elif self._key_is_down == wx.WXK_ALT and not wx.GetKeyState(wx.WXK_ALT):
2641 self._key_is_down = None
2642 self.measurement_report_btn.Label = lang.getstr("measurement_report")
2643 self.measurement_report_btn.Refresh()
2644
2645 def OnMove(self, event: wx.Event = None) -> None: # noqa: N802
2646 """Handle the window move event.
2647
2648 Args:
2649 event (wx.Event, optional): The move event triggered by the user.
2650 """
2651 # When moving, check if we are on another screen and resize if needed.
2652 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
2653 x, y = self.GetScreenPosition()
2654 setcfg("position.x", x)
2655 setcfg("position.y", y)
2656 display_client_rect = self.GetDisplay().ClientArea
2657 if (
2658 getattr(self, "display_client_rect", display_client_rect)
2659 != display_client_rect
2660 ):
2661 # We just moved to this workspace
2662 if sys.platform not in ("darwin", "win32"):
2663 # Linux
2664 if os.getenv("XDG_SESSION_TYPE") == "wayland":
2665 # Client-side decorations
2666 safety_margin = 0
2667 else:
2668 # Assume server-side decorations
2669 safety_margin = 40
2670 else:
2671 safety_margin = 20
2672 resize = False
2673 if (
2674 self.Size[0] > display_client_rect[2]
2675 or self.Size[1] > display_client_rect[3] - safety_margin
2676 ):
2677 # Our size is too large for that workspace, adjust
2678 resize = True
2679 elif self.Size[0] < (
2680 self.Size[0] - self.calpanel.Size[0] + self.calpanel.VirtualSize[0]
2681 ) or self.Size[1] < (
2682 self.Size[1] - self.calpanel.Size[1] + self.calpanel.VirtualSize[1]
2683 ):
2684 # Our full size fits on that workspace
2685 resize = True
2686 if resize:
2687 wx.CallAfter(self.set_size, True)
2688 self.display_client_rect = display_client_rect
2689 if event:
2690 event.Skip()
2691
2692 def OnResize(self, event: wx.Event) -> None: # noqa: N802
2693 """Handle the window resize event.
2694
2695 Args:
2696 event (wx.Event): The resize event triggered by the user.
2697 """
2698 # Hide the header bitmap on small screens
2699 scale = getcfg("app.dpi") / config.get_default_dpi()
2700 scale = max(scale, 1)
2701 self.header.GetContainingSizer().Show(self.header, self.Size[1] > 480 * scale)
2702 if not hasattr(self, "header_btm_bmp"):
2703 self.header_btm_bmp = self.header_btm.GetBitmap()
2704 self.header_btm_min_bmp = get_bitmap(
2705 "theme/header_minimal", display_missing_icon=False
2706 )
2707 if self.Size[1] > 480 * scale:
2708 if self.header_btm.GetBitmap() is not self.header_btm_bmp:
2709 self.header_btm.SetBitmap(self.header_btm_bmp)
2710 elif self.header_btm.GetBitmap() is not self.header_btm_min_bmp:
2711 self.header_btm.SetBitmap(self.header_btm_min_bmp)
2712 event.Skip()
2713
2714 def cal_drop_handler(self, path: str) -> None:
2715 """Handle drag'n'drop for .cal files.
2716
2717 Settings and calibration are loaded from dropped files.
2718
2719 Args:
2720 path (str): The path to the dropped .cal file.
2721 """
2722 if not self.worker.is_working():
2723 self.load_cal_handler(None, path)
2724
2725 def ccxx_drop_handler(self, path: str) -> None:
2726 """Handle drag'n'drop for .ccmx/.ccss files.
2727
2728 Args:
2729 path (str): The path to the dropped .ccmx or .ccss file.
2730 """
2731 if not self.worker.is_working():
2732 self.colorimeter_correction_matrix_ctrl_handler(None, path)
2733
2734 def ti1_drop_handler(self, path: str) -> None:
2735 """Handle drag'n'drop for .ti1 files.
2736
2737 Dropped files are added to the testchart chooser and selected.
2738
2739 Args:
2740 path (str): The path to the dropped .ti1 file.
2741 """
2742 if not self.worker.is_working():
2743 self.testchart_btn_handler(None, path)
2744
2745 def ti3_drop_handler(self, path: str) -> None:
2746 """Handle drag'n'drop for .ti3 files.
2747
2748 Dropped files are used to create an ICC profile.
2749
2750 Args:
2751 path (str): The path to the dropped .ti3 file.
2752 """
2753 if not self.worker.is_working():
2754 self.create_profile_handler(None, path)
2755
2756 def init_gamapframe(self) -> None:
2757 """Create & initialize the gamut mapping options window and its controls."""
2758 self.gamapframe = GamapFrame(self)
2759
2760 def init_infoframe(self, show: None | bool = None) -> None:
2761 """Create & initialize the info (log) window and its controls.
2762
2763 Args:
2764 show (None | bool, optional): Whether to show the info frame
2765 immediately. Defaults to None, which means it will not be shown
2766 unless the user has set the "show_info_frame" configuration
2767 option to True.
2768 """
2769 self.infoframe = LogWindow(self)
2770 self.infoframe.Bind(wx.EVT_CLOSE, self.infoframe_close_handler, self.infoframe)
2771 self.infoframe.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
2772 if show:
2773 self.infoframe_toggle_handler(show=show)
2774
2775 def init_lut3dframe(self) -> None:
2776 """Create & initialize the 3D LUT creation window and its controls."""
2777 self.lut3dframe = LUT3DFrame(self)
2778
2779 def init_reportframe(self) -> None:
2780 """Initialize the measurement report creation window."""
2781 self.reportframe = ReportFrame(self)
2782 self.reportframe.measurement_report_btn.Bind(
2783 wx.EVT_BUTTON, self.measurement_report_handler
2784 )
2785
2786 def init_synthiccframe(self) -> None:
2787 """Create & initialize the 3D LUT creation window and its controls."""
2788 # Avoid messing with main configuration (e.g. when not running standalone)
2789 # because we share HDR settings with 3D LUT HDR settings
2790 SynthICCFrame.cfg = config.configparser.RawConfigParser()
2791 config.initcfg("synthprofile", SynthICCFrame.cfg)
2792 self.synthiccframe = SynthICCFrame()
2793
2794 def infoframe_close_handler(self, event: wx.Event) -> None:
2795 """Handle the info frame close event.
2796
2797 Args:
2798 event (wx.Event): The close event triggered by the user.
2799 """
2800 self.infoframe_toggle_handler(event)
2801
2802 def setup_language(self) -> None:
2803 """Substitute translated strings for menus, controls, labels and tooltips."""
2804 # Set language specific defaults
2805 lang.update_defaults()
2806
2807 # Translate controls and labels
2808 BaseFrame.setup_language(self)
2809
2810 settings = [lang.getstr("settings.new")]
2811 for cal in self.recent_cals[1:]:
2812 lstr = lang.getstr(os.path.basename(cal))
2813 if cal == getcfg("calibration.file", False) and getcfg("settings.changed"):
2814 lstr = "* " + lstr
2815 settings.append(lstr)
2816 self.calibration_file_ctrl.SetItems(settings)
2817 self.setup_observer_ctrl()
2818 self.whitepoint_ctrl.SetItems(
2819 [
2820 lang.getstr("as_measured"),
2821 lang.getstr("whitepoint.colortemp"),
2822 lang.getstr("whitepoint.xy"),
2823 ]
2824 )
2825
2826 self.whitepoint_colortemp_loci = [
2827 lang.getstr("whitepoint.colortemp.locus.daylight"),
2828 lang.getstr("whitepoint.colortemp.locus.blackbody"),
2829 ]
2830 self.whitepoint_colortemp_locus_ctrl.SetItems(self.whitepoint_colortemp_loci)
2831
2832 self.luminance_ctrl.SetItems(
2833 [lang.getstr("as_measured"), lang.getstr("custom")]
2834 )
2835
2836 self.black_luminance_ctrl.SetItems(
2837 [lang.getstr("as_measured"), lang.getstr("custom")]
2838 )
2839
2840 self.trc_ctrl.SetItems(
2841 [
2842 lang.getstr("as_measured"),
2843 "Gamma 2.2",
2844 lang.getstr("trc.lstar"),
2845 lang.getstr("trc.rec709"),
2846 lang.getstr("trc.rec1886"),
2847 lang.getstr("trc.smpte240m"),
2848 lang.getstr("trc.srgb"),
2849 lang.getstr("custom"),
2850 ]
2851 )
2852
2853 self.trc_types = [
2854 lang.getstr("trc.type.relative"),
2855 lang.getstr("trc.type.absolute"),
2856 ]
2857 self.trc_type_ctrl.SetItems(self.trc_types)
2858
2859 self.update_profile_type_ctrl_items()
2860
2861 self.default_testchart_names = []
2862 for testcharts in list(self.testchart_defaults.values()):
2863 for chart in list(testcharts.values()):
2864 chart = lang.getstr(chart)
2865 if chart not in self.default_testchart_names:
2866 self.default_testchart_names.append(chart)
2867
2868 items = [
2869 lang.getstr("testchart." + v)
2870 for v in config.VALID_VALUES["testchart.patch_sequence"]
2871 ]
2872 self.testchart_patch_sequence_ctrl.Items = items
2873
2874 self.lut3d_setup_language()
2875 self.mr_setup_language()
2876
2877 def get_min_height(self) -> int:
2878 """Calculate minimum panel height.
2879
2880 Returns:
2881 int: The minimum required height.
2882 """
2883 if sys.platform not in ("darwin", "win32"):
2884 # Linux
2885 # Client-side decorations in Wayland, server-side decorations in X11
2886 safety_margin = 0 if os.getenv("XDG_SESSION_TYPE") == "wayland" else 40
2887 else:
2888 safety_margin = 20
2889
2890 # Use display size
2891 display_area_free_height = (
2892 self.GetDisplay().ClientArea[3]
2893 + self.ClientSize[1]
2894 - self.Size[1]
2895 - safety_margin
2896 )
2897
2898 # Use element heights
2899 header_border_top_height = self.headerbordertop.Size[1]
2900 header_height = self.header.Size[1]
2901 header_panel_height = self.headerpanel.Sizer.MinSize[1]
2902 tab_panel_header_height = 0
2903 tab_panel_height = self.tabpanel.Sizer.MinSize[1]
2904 tab_panel_footer_height = 0
2905 display_instrument_panel = self.display_instrument_panel.Sizer.MinSize[1]
2906 button_panel_header_height = 0
2907 button_panel_height = self.buttonpanel.Sizer.MinSize[1]
2908 if getattr(self, "tabpanelheader", None):
2909 tab_panel_header_height = self.tabpanelheader.Size[1] + 1
2910
2911 if getattr(self, "tabpanelfooter", None):
2912 tab_panel_footer_height = self.tabpanelfooter.Size[1] + 1
2913
2914 if getattr(self, "buttonpanelheader", None):
2915 button_panel_header_height = self.buttonpanelheader.Size[1] + 1
2916
2917 per_element_heights = (
2918 header_border_top_height
2919 + header_height
2920 + header_panel_height
2921 + 1
2922 + tab_panel_header_height
2923 + tab_panel_height
2924 + tab_panel_footer_height
2925 + display_instrument_panel
2926 + button_panel_header_height
2927 + button_panel_height
2928 )
2929
2930 return min(
2931 display_area_free_height,
2932 per_element_heights,
2933 )
2934
2935 def set_size(self, set_height: bool = False, fit_width: bool = False) -> None:
2936 """Set the size of the main window.
2937
2938 Args:
2939 set_height (bool, optional): If True, set the height to the minimum
2940 required height.
2941 fit_width (bool, optional): If True, adjust the width to fit the
2942 content. If False, keep the current width.
2943 """
2944 self.SetMinSize((0, 0))
2945 borders_tb = self.Size[1] - self.ClientSize[1]
2946 height = self.get_min_height() if set_height else self.ClientSize[1]
2947 borders_lr = self.Size[0] - self.ClientSize[0]
2948 scale = getcfg("app.dpi") / config.get_default_dpi()
2949 margin = wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X)
2950 header_min_h = 64
2951 if scale > 1:
2952 header_min_h = round(header_min_h * scale)
2953 self.mr_settings_panel.Freeze()
2954 sim_show = self.simulation_profile_cb.IsShown()
2955 self.simulation_profile_cb.Show()
2956 devlink_show = self.devlink_profile_cb.IsShown()
2957 self.devlink_profile_cb.Show()
2958 size = (
2959 min(
2960 max(self.GetDisplay().ClientArea[2] - borders_lr, 0),
2961 max(
2962 max(
2963 self.display_instrument_panel.Sizer.MinSize[0],
2964 self.calibration_settings_panel.Sizer.MinSize[0],
2965 self.profile_settings_panel.Sizer.MinSize[0],
2966 self.lut3d_settings_panel.Sizer.MinSize[0],
2967 self.mr_settings_panel.Sizer.MinSize[0],
2968 )
2969 + margin,
2970 self.tabpanel.GetSizer().GetMinSize()[0],
2971 ),
2972 ),
2973 height,
2974 )
2975 self.simulation_profile_cb.Show(sim_show)
2976 self.devlink_profile_cb.Show(devlink_show)
2977 self.mr_settings_panel.Thaw()
2978 self.SetMaxSize((-1, -1))
2979 if not self.IsMaximized() and not self.IsIconized():
2980 self.ClientSize = (
2981 size[0] if fit_width else max(size[0], self.ClientSize[0]),
2982 size[1],
2983 )
2984 minsize = (
2985 self.ClientSize[0],
2986 self.ClientSize[1] - self.calpanel.GetSize()[1] + header_min_h,
2987 )
2988 if hasattr(self, "MinClientSize"):
2989 self.MinClientSize = minsize
2990 else:
2991 self.MinSize = (minsize[0] + borders_lr, minsize[1] + borders_tb)
2992 if os.getenv("XDG_SESSION_TYPE") == "wayland":
2993 self.MaxSize = self.Size
2994 wx.CallAfter(set_maxsize, self, (-1, -1))
2995 if self.IsShown():
2996 self.calpanel.Layout()
2997
2998 def update_profile_type_ctrl(self) -> None:
2999 """Update the profile type control based on the current Argyll version."""
3000 self.profile_type_ctrl.SetSelection(
3001 self.profile_types_ba.get(
3002 getcfg("profile.type"),
3003 self.profile_types_ba.get(DEFAULTS["profile.type"], 0),
3004 )
3005 )
3006
3007 def update_profile_type_ctrl_items(self) -> None:
3008 """Update profile type choices based on Argyll version."""
3009 self.profile_types = [
3010 lang.getstr("profile.type.lut.lab"),
3011 lang.getstr("profile.type.shaper_matrix"),
3012 lang.getstr("profile.type.single_shaper_matrix"),
3013 lang.getstr("profile.type.gamma_matrix"),
3014 lang.getstr("profile.type.single_gamma_matrix"),
3015 ]
3016 self.profile_types_ab = {}
3017 profile_types_index = 0
3018 if self.worker.argyll_version[0:3] > [1, 1, 0] or (
3019 self.worker.argyll_version[0:3] == [1, 1, 0]
3020 and "Beta" not in self.worker.argyll_version_string
3021 and "RC1" not in self.worker.argyll_version_string
3022 and "RC2" not in self.worker.argyll_version_string
3023 and "RC3" not in self.worker.argyll_version_string
3024 ):
3025 # Argyll 1.1.0_RC3 had a bug when using -aX
3026 # which was fixed in 1.1.0_RC4
3027 self.profile_types.insert(
3028 profile_types_index, lang.getstr("profile.type.lut_matrix.xyz")
3029 )
3030 # XYZ LUT + accurate matrix
3031 self.profile_types_ab[profile_types_index] = "X"
3032 profile_types_index += 1
3033 if ([1, 1, 0] < self.worker.argyll_version[0:3] < [2, 0, 2]) or (
3034 self.worker.argyll_version[0:3] == [1, 1, 0]
3035 and "Beta" not in self.worker.argyll_version_string
3036 and "RC1" not in self.worker.argyll_version_string
3037 and "RC2" not in self.worker.argyll_version_string
3038 ):
3039 # Windows wants matrix tags in XYZ LUT profiles,
3040 # which is satisfied with Argyll >= 1.1.0_RC3
3041 self.profile_types.insert(
3042 profile_types_index,
3043 lang.getstr("profile.type.lut_rg_swapped_matrix.xyz"),
3044 )
3045 # XYZ LUT + dummy matrix (R <-> G swapped)
3046 self.profile_types_ab[profile_types_index] = "x"
3047 profile_types_index += 1
3048 else:
3049 self.profile_types.insert(
3050 profile_types_index, lang.getstr("profile.type.lut.xyz")
3051 )
3052 self.profile_types_ab[profile_types_index] = "x" # XYZ LUT
3053 profile_types_index += 1
3054 self.profile_type_ctrl.SetItems(self.profile_types)
3055 self.profile_types_ab[profile_types_index] = "l"
3056 self.profile_types_ab[profile_types_index + 1] = "s"
3057 self.profile_types_ab[profile_types_index + 2] = "S"
3058 self.profile_types_ab[profile_types_index + 3] = "g"
3059 self.profile_types_ab[profile_types_index + 4] = "G"
3060 self.profile_types_ba = swap_dict_keys_values(self.profile_types_ab)
3061
3062 def init_measureframe(self) -> None:
3063 """Create & initialize the measurement window and its controls."""
3064 self.measureframe = MeasureFrame(self, -1)
3065
3066 def init_menus(self) -> None:
3067 """Initialize the menus and menuitem event handlers."""
3068 menu_xrc_path = get_data_path(os.path.join("xrc", "mainmenu.xrc"))
3069 use_popup_menu = False
3070 if use_popup_menu:
3071 with open(menu_xrc_path, "rb") as xrc_file:
3072 xrc_xml = xrc_file.read().decode()
3073 xrc_xml = xrc_xml.replace('<object class="wxMenuBar" name="menu">', "")
3074 xrc_xml = xrc_xml.replace("</object>\n</resource>", "</resource>")
3075 res = xrc.XmlResource()
3076 res.LoadFromBuffer(xrc_xml)
3077 self.menubar = PopupMenu(self.header)
3078 for label in ("file", "options", "tools", "language", "help"):
3079 menu_label = f"menu.{label}"
3080 menu_name = "wxID_HELP" if label == "help" else menu_label
3081 menu = res.LoadMenu(menu_name)
3082 self.menubar.Append(menu, menu_label)
3083 self.header.Bind(wx.EVT_RIGHT_UP, lambda e: self.menubar.popup())
3084 else:
3085 res = xrc.XmlResource(menu_xrc_path)
3086 self.menubar = res.LoadMenuBar(self, "menu")
3087 if sys.platform == "darwin":
3088 # https://github.com/eoyilmaz/displaycal-py3/issues/303
3089 # set the menubar as the common menu bar,
3090 # otherwise it will be hidden when the measurement window is
3091 # shown
3092 wx.MenuBar.MacSetCommonMenuBar(self.menubar)
3093
3094 file_ = self.menubar.GetMenu(self.menubar.FindMenu("menu.file"))
3095 menuitem = file_.FindItemById(file_.FindItem("calibration.load"))
3096 self.Bind(wx.EVT_MENU, self.load_cal_handler, menuitem)
3097 menuitem = file_.FindItemById(file_.FindItem("testchart.set"))
3098 self.Bind(wx.EVT_MENU, self.testchart_btn_handler, menuitem)
3099 self.menuitem_testchart_edit = file_.FindItemById(
3100 file_.FindItem("testchart.edit")
3101 )
3102 self.Bind(
3103 wx.EVT_MENU, self.create_testchart_btn_handler, self.menuitem_testchart_edit
3104 )
3105 menuitem = file_.FindItemById(file_.FindItem("profile.set_save_path"))
3106 self.Bind(wx.EVT_MENU, self.profile_save_path_btn_handler, menuitem)
3107 self.menuitem_profile_info = file_.FindItemById(file_.FindItem("profile.info"))
3108 self.Bind(wx.EVT_MENU, self.profile_info_handler, self.menuitem_profile_info)
3109 self.menuitem_create_profile = file_.FindItemById(
3110 file_.FindItem("create_profile")
3111 )
3112 self.Bind(
3113 wx.EVT_MENU, self.create_profile_handler, self.menuitem_create_profile
3114 )
3115 self.menuitem_create_profile_from_edid = file_.FindItemById(
3116 file_.FindItem("create_profile_from_edid")
3117 )
3118 self.Bind(
3119 wx.EVT_MENU,
3120 self.create_profile_from_edid,
3121 self.menuitem_create_profile_from_edid,
3122 )
3123 self.menuitem_install_display_profile = file_.FindItemById(
3124 file_.FindItem("install_display_profile")
3125 )
3126 self.Bind(
3127 wx.EVT_MENU,
3128 self.select_install_profile_handler,
3129 self.menuitem_install_display_profile,
3130 )
3131 self.menuitem_profile_share = file_.FindItemById(
3132 file_.FindItem("profile.share")
3133 )
3134 self.Bind(wx.EVT_MENU, self.profile_share_handler, self.menuitem_profile_share)
3135 if sys.platform != "darwin" or wx.VERSION >= (2, 9):
3136 file_.AppendSeparator()
3137 self.menuitem_prefs = file_.Append(
3138 (
3139 -1
3140 if wx.VERSION < (2, 9) or sys.platform != "darwin"
3141 else wx.ID_PREFERENCES
3142 ),
3143 "&" + "menuitem.set_argyll_bin",
3144 )
3145 self.Bind(wx.EVT_MENU, self.set_argyll_bin_handler, self.menuitem_prefs)
3146 if sys.platform != "darwin" or wx.VERSION >= (2, 9):
3147 file_.AppendSeparator()
3148 self.menuitem_quit = file_.Append(
3149 -1 if wx.VERSION < (2, 9) else wx.ID_EXIT, "&menuitem.quit\tCtrl+Q"
3150 )
3151 self.Bind(wx.EVT_MENU, self.OnClose, self.menuitem_quit)
3152
3153 options = self.menubar.GetMenu(self.menubar.FindMenu("menu.options"))
3154 self.menuitem_advanced_options = options.FindItemById(
3155 options.FindItem("advanced")
3156 )
3157 options_advanced = self.menuitem_advanced_options.SubMenu
3158 self.menu_advanced_options = options_advanced
3159 self.menuitem_skip_legacy_serial_ports = options_advanced.FindItemById(
3160 options_advanced.FindItem("skip_legacy_serial_ports")
3161 )
3162 self.Bind(
3163 wx.EVT_MENU,
3164 self.skip_legacy_serial_ports_handler,
3165 self.menuitem_skip_legacy_serial_ports,
3166 )
3167 self.menuitem_use_separate_lut_access = options_advanced.FindItemById(
3168 options_advanced.FindItem("use_separate_lut_access")
3169 )
3170 if sys.platform not in ("darwin", "win32") or TEST:
3171 self.Bind(
3172 wx.EVT_MENU,
3173 self.use_separate_lut_access_handler,
3174 self.menuitem_use_separate_lut_access,
3175 )
3176 else:
3177 options_advanced.RemoveItem(self.menuitem_use_separate_lut_access)
3178 self.menuitem_do_not_use_video_lut = options_advanced.FindItemById(
3179 options_advanced.FindItem("calibration.do_not_use_video_lut")
3180 )
3181 self.Bind(
3182 wx.EVT_MENU,
3183 self.do_not_use_video_lut_handler,
3184 self.menuitem_do_not_use_video_lut,
3185 )
3186 self.menuitem_allow_skip_sensor_cal = options_advanced.FindItemById(
3187 options_advanced.FindItem("allow_skip_sensor_cal")
3188 )
3189 self.Bind(
3190 wx.EVT_MENU,
3191 self.allow_skip_sensor_cal_handler,
3192 self.menuitem_allow_skip_sensor_cal,
3193 )
3194 self.menuitem_show_advanced_options = options.FindItemById(
3195 options.FindItem("show_advanced_options")
3196 )
3197 self.Bind(
3198 wx.EVT_MENU,
3199 self.show_advanced_options_handler,
3200 self.menuitem_show_advanced_options,
3201 )
3202 self.menuitem_enable_3dlut_tab = options.FindItemById(
3203 options.FindItem("3dlut.tab.enable")
3204 )
3205 self.Bind(
3206 wx.EVT_MENU, self.enable_3dlut_tab_handler, self.menuitem_enable_3dlut_tab
3207 )
3208 menuitem = options_advanced.FindItemById(
3209 options_advanced.FindItem("extra_args")
3210 )
3211 self.Bind(wx.EVT_MENU, self.extra_args_handler, menuitem)
3212 self.menuitem_enable_argyll_debug = options_advanced.FindItemById(
3213 options_advanced.FindItem("enable_argyll_debug")
3214 )
3215 self.Bind(
3216 wx.EVT_MENU,
3217 self.enable_argyll_debug_handler,
3218 self.menuitem_enable_argyll_debug,
3219 )
3220 self.menuitem_enable_dry_run = options_advanced.FindItemById(
3221 options_advanced.FindItem("dry_run")
3222 )
3223 self.Bind(
3224 wx.EVT_MENU, self.enable_dry_run_handler, self.menuitem_enable_dry_run
3225 )
3226 self.menuitem_startup_sound = options.FindItemById(
3227 options.FindItem("startup_sound.enable")
3228 )
3229 self.Bind(
3230 wx.EVT_MENU, self.startup_sound_enable_handler, self.menuitem_startup_sound
3231 )
3232 self.menuitem_use_simple_splash = None
3233 if (use_simple_splash_menu_id := options.FindItem("splash.simple")) is not None:
3234 self.menuitem_use_simple_splash = options.FindItemById(
3235 use_simple_splash_menu_id
3236 )
3237 self.Bind(
3238 wx.EVT_MENU,
3239 self.use_simple_splash_handler,
3240 self.menuitem_use_simple_splash,
3241 )
3242 self.menuitem_use_fancy_progress = options.FindItemById(
3243 options.FindItem("use_fancy_progress")
3244 )
3245 self.Bind(
3246 wx.EVT_MENU,
3247 self.use_fancy_progress_handler,
3248 self.menuitem_use_fancy_progress,
3249 )
3250 menuitem = options.FindItemById(options.FindItem("restore_defaults"))
3251 self.Bind(wx.EVT_MENU, self.restore_defaults_handler, menuitem)
3252
3253 tools = self.menubar.GetMenu(self.menubar.FindMenu("menu.tools"))
3254 tools_vcgt = tools.FindItemById(
3255 tools.FindItem("video_card_gamma_table")
3256 ).SubMenu
3257 tools_reports = tools.FindItemById(tools.FindItem("report")).SubMenu
3258 tools_advanced = tools.FindItemById(tools.FindItem("advanced")).SubMenu
3259 tools_instrument = tools.FindItemById(tools.FindItem("instrument")).SubMenu
3260 tools_ccxx = tools.FindItemById(
3261 tools.FindItem("colorimeter_correction_matrix_file")
3262 ).SubMenu
3263
3264 self.menuitem_load_lut_from_cal_or_profile = tools_vcgt.FindItemById(
3265 tools_vcgt.FindItem("calibration.load_from_cal_or_profile")
3266 )
3267 self.Bind(
3268 wx.EVT_MENU,
3269 self.load_profile_cal_handler,
3270 self.menuitem_load_lut_from_cal_or_profile,
3271 )
3272 self.menuitem_load_lut_from_display_profile = tools_vcgt.FindItemById(
3273 tools_vcgt.FindItem("calibration.load_from_display_profile")
3274 )
3275 self.Bind(
3276 wx.EVT_MENU,
3277 self.load_display_profile_cal,
3278 self.menuitem_load_lut_from_display_profile,
3279 )
3280 self.menuitem_lut_reset = tools_vcgt.FindItemById(
3281 tools_vcgt.FindItem("calibration.reset")
3282 )
3283 self.Bind(wx.EVT_MENU, self.reset_cal, self.menuitem_lut_reset)
3284
3285 self.menuitem_measurement_report = tools_reports.FindItemById(
3286 tools_reports.FindItem("measurement_report")
3287 )
3288 self.Bind(
3289 wx.EVT_MENU,
3290 self.measurement_report_handler,
3291 self.menuitem_measurement_report,
3292 )
3293 self.menuitem_report_uncalibrated = tools_reports.FindItemById(
3294 tools_reports.FindItem("report.uncalibrated")
3295 )
3296 self.Bind(
3297 wx.EVT_MENU,
3298 self.report_uncalibrated_handler,
3299 self.menuitem_report_uncalibrated,
3300 )
3301 self.menuitem_report_calibrated = tools_reports.FindItemById(
3302 tools_reports.FindItem("report.calibrated")
3303 )
3304 self.Bind(
3305 wx.EVT_MENU, self.report_calibrated_handler, self.menuitem_report_calibrated
3306 )
3307 self.menuitem_calibration_verify = tools_reports.FindItemById(
3308 tools_reports.FindItem("calibration.verify")
3309 )
3310 self.Bind(
3311 wx.EVT_MENU,
3312 self.verify_calibration_handler,
3313 self.menuitem_calibration_verify,
3314 )
3315 menuitem = tools_reports.FindItemById(
3316 tools_reports.FindItem("measurement_report.update")
3317 )
3318 self.Bind(wx.EVT_MENU, self.update_measurement_report, menuitem)
3319 self.menuitem_measure_uniformity = tools_reports.FindItemById(
3320 tools_reports.FindItem("report.uniformity")
3321 )
3322 self.Bind(
3323 wx.EVT_MENU,
3324 self.measure_uniformity_handler,
3325 self.menuitem_measure_uniformity,
3326 )
3327
3328 self.menuitem_measure_testchart = tools_advanced.FindItemById(
3329 tools_advanced.FindItem("measure.testchart")
3330 )
3331 self.Bind(wx.EVT_MENU, self.measure_handler, self.menuitem_measure_testchart)
3332 self.menuitem_specplot_run = None
3333 if (specplot_run_menu_id := tools_advanced.FindItem("specplot.run")) is not None:
3334 self.menuitem_specplot_run = tools_advanced.FindItemById(
3335 specplot_run_menu_id
3336 )
3337 self.Bind(wx.EVT_MENU, self.specplot_handler, self.menuitem_specplot_run)
3338
3339 self.menuitem_profile_hires_b2a = tools_advanced.FindItemById(
3340 tools_advanced.FindItem("profile.b2a.hires")
3341 )
3342 self.Bind(
3343 wx.EVT_MENU, self.profile_hires_b2a_handler, self.menuitem_profile_hires_b2a
3344 )
3345
3346 self.menuitem_measurement_file_check = tools_advanced.FindItemById(
3347 tools_advanced.FindItem("measurement_file.check_sanity")
3348 )
3349 self.Bind(
3350 wx.EVT_MENU,
3351 self.measurement_file_check_handler,
3352 self.menuitem_measurement_file_check,
3353 )
3354
3355 self.menuitem_measurement_file_check_auto = tools_advanced.FindItemById(
3356 tools_advanced.FindItem("measurement_file.check_sanity.auto")
3357 )
3358 self.Bind(
3359 wx.EVT_MENU,
3360 self.measurement_file_check_auto_handler,
3361 self.menuitem_measurement_file_check_auto,
3362 )
3363
3364 self.menuitem_choose_colorimeter_correction = tools_ccxx.FindItemById(
3365 tools_ccxx.FindItem("colorimeter_correction_matrix_file.choose")
3366 )
3367 self.Bind(
3368 wx.EVT_MENU,
3369 self.colorimeter_correction_matrix_ctrl_handler,
3370 self.menuitem_choose_colorimeter_correction,
3371 )
3372 self.menuitem_colorimeter_correction_web = tools_ccxx.FindItemById(
3373 tools_ccxx.FindItem("colorimeter_correction.web_check")
3374 )
3375 self.Bind(
3376 wx.EVT_MENU,
3377 self.colorimeter_correction_web_handler,
3378 self.menuitem_colorimeter_correction_web,
3379 )
3380 self.menuitem_import_colorimeter_correction = tools_ccxx.FindItemById(
3381 tools_ccxx.FindItem("colorimeter_correction.import")
3382 )
3383 self.Bind(
3384 wx.EVT_MENU,
3385 self.import_colorimeter_corrections_handler,
3386 self.menuitem_import_colorimeter_correction,
3387 )
3388 self.menuitem_create_colorimeter_correction = tools_ccxx.FindItemById(
3389 tools_ccxx.FindItem("colorimeter_correction.create")
3390 )
3391 self.Bind(
3392 wx.EVT_MENU,
3393 self.create_colorimeter_correction_handler,
3394 self.menuitem_create_colorimeter_correction,
3395 )
3396 self.menuitem_upload_colorimeter_correction = tools_ccxx.FindItemById(
3397 tools_ccxx.FindItem("colorimeter_correction.upload")
3398 )
3399 self.Bind(
3400 wx.EVT_MENU,
3401 self.upload_colorimeter_correction_handler,
3402 self.menuitem_upload_colorimeter_correction,
3403 )
3404
3405 self.menuitem_synthicc_create = tools_advanced.FindItemById(
3406 tools_advanced.FindItem("synthicc.create")
3407 )
3408 self.Bind(
3409 wx.EVT_MENU, self.synthicc_create_handler, self.menuitem_synthicc_create
3410 )
3411
3412 self.menuitem_install_argyll_instrument_conf = tools_instrument.FindItemById(
3413 tools_instrument.FindItem("argyll.instrument.configuration_files.install")
3414 )
3415 self.menuitem_uninstall_argyll_instrument_conf = tools_instrument.FindItemById(
3416 tools_instrument.FindItem("argyll.instrument.configuration_files.uninstall")
3417 )
3418 if sys.platform in ("darwin", "win32") and not TEST:
3419 tools_instrument.RemoveItem(self.menuitem_install_argyll_instrument_conf)
3420 tools_instrument.RemoveItem(self.menuitem_uninstall_argyll_instrument_conf)
3421 else:
3422 # Linux may need instrument access being setup
3423 self.Bind(
3424 wx.EVT_MENU,
3425 self.install_argyll_instrument_conf,
3426 self.menuitem_install_argyll_instrument_conf,
3427 )
3428 self.Bind(
3429 wx.EVT_MENU,
3430 self.uninstall_argyll_instrument_conf,
3431 self.menuitem_uninstall_argyll_instrument_conf,
3432 )
3433 self.menuitem_install_argyll_instrument_drivers = tools_instrument.FindItemById(
3434 tools_instrument.FindItem("argyll.instrument.drivers.install")
3435 )
3436 self.menuitem_uninstall_argyll_instrument_drivers = (
3437 tools_instrument.FindItemById(
3438 tools_instrument.FindItem("argyll.instrument.drivers.uninstall")
3439 )
3440 )
3441 if sys.platform == "win32" or TEST:
3442 # Windows may need an Argyll CMS instrument driver
3443 self.Bind(
3444 wx.EVT_MENU,
3445 self.install_argyll_instrument_drivers,
3446 self.menuitem_install_argyll_instrument_drivers,
3447 )
3448 else:
3449 # Other OS do not need an Argyll CMS instrument driver
3450 tools_instrument.RemoveItem(self.menuitem_install_argyll_instrument_drivers)
3451 if (sys.platform == "win32" and sys.getwindowsversion() >= (6,)) or TEST:
3452 # Windows Vista and newer can uninstall Argyll CMS instrument driver
3453 self.Bind(
3454 wx.EVT_MENU,
3455 self.uninstall_argyll_instrument_drivers,
3456 self.menuitem_uninstall_argyll_instrument_drivers,
3457 )
3458 else:
3459 # Other OS cannot uninstall Argyll CMS instrument driver
3460 tools_instrument.RemoveItem(
3461 self.menuitem_uninstall_argyll_instrument_drivers
3462 )
3463 self.menuitem_enable_spyder2 = tools_instrument.FindItemById(
3464 tools_instrument.FindItem("enable_spyder2")
3465 )
3466 self.Bind(
3467 wx.EVT_MENU, self.enable_spyder2_handler, self.menuitem_enable_spyder2
3468 )
3469 self.menuitem_calibrate_instrument = tools_instrument.FindItemById(
3470 tools_instrument.FindItem("calibrate_instrument")
3471 )
3472 self.Bind(
3473 wx.EVT_MENU,
3474 self.calibrate_instrument_handler,
3475 self.menuitem_calibrate_instrument,
3476 )
3477 menuitem = tools.FindItemById(tools.FindItem("detect_displays_and_ports"))
3478 self.Bind(wx.EVT_MENU, self.check_update_controls, menuitem)
3479 self.menuitem_show_lut = tools.FindItemById(
3480 tools.FindItem("calibration.show_lut")
3481 )
3482 self.Bind(wx.EVT_MENU, self.init_lut_viewer, self.menuitem_show_lut)
3483 self.menuitem_show_log = tools.FindItemById(tools.FindItem("infoframe.toggle"))
3484 self.Bind(wx.EVT_MENU, self.infoframe_toggle_handler, self.menuitem_show_log)
3485 self.menuitem_log_autoshow = tools.FindItemById(tools.FindItem("log.autoshow"))
3486 self.Bind(
3487 wx.EVT_MENU, self.infoframe_autoshow_handler, self.menuitem_log_autoshow
3488 )
3489
3490 languages = self.menubar.GetMenu(self.menubar.FindMenu("menu.language"))
3491 llist = [
3492 (lang.LDICT[lcode].get("!language", ""), lcode) for lcode in lang.LDICT
3493 ]
3494 llist.sort()
3495 # Map language code to ISO 3166-1 alpha-2 country code
3496 lmap = {"en": "us", "ko": "kr", "ukr": "ua", "zh_hk": "cn", "zh_cn": "cn"}
3497 for lstr, lcode in llist:
3498 menuitem = languages.Append(-1, "&" + lstr, kind=wx.ITEM_RADIO)
3499 if (lcode2 := lmap.get(lcode, lcode).upper()) in flagart.catalog and (
3500 sys.platform in ("darwin", "win32")
3501 or menuitem.GetKind() == wx.ITEM_NORMAL
3502 ):
3503 # This can fail under Linux with wxPython 3.0
3504 # because only normal menu items can have bitmaps
3505 # there. Working fine on all other platforms.
3506 pyimg = flagart.catalog[lcode2]
3507 if pyimg.Image.IsOk():
3508 bmp = pyimg.GetBitmap()
3509 if bmp.IsOk():
3510 menuitem.SetBitmap(bmp)
3511 if lang.getcode() == lcode:
3512 menuitem.Check()
3513 font = menuitem.Font
3514 font.SetWeight(wx.FONTWEIGHT_BOLD)
3515 menuitem.SetFont(font)
3516 # Map numerical event id to language string
3517 lang.LDICT[lcode].menuitem_id = menuitem.GetId()
3518 self.Bind(wx.EVT_MENU, self.set_language_handler, menuitem)
3519
3520 help_action = self.menubar.GetMenu(self.menubar.FindMenu("menu.help"))
3521 self.menuitem_about = help_action.Append(
3522 -1 if wx.VERSION < (2, 9) else wx.ID_ABOUT, "&menu.about"
3523 )
3524 self.Bind(wx.EVT_MENU, self.aboutdialog_handler, self.menuitem_about)
3525 self.menuitem_readme = help_action.FindItemById(help_action.FindItem("readme"))
3526 self.menuitem_readme.Enable(isinstance(get_data_path("README.html"), str))
3527 self.Bind(wx.EVT_MENU, self.readme_handler, self.menuitem_readme)
3528 self.menuitem_license = help_action.FindItemById(
3529 help_action.FindItem("license")
3530 )
3531 self.menuitem_license.Enable(
3532 isinstance(get_data_path("LICENSE.txt"), str)
3533 or os.path.isfile("/usr/share/common-licenses/GPL-3")
3534 )
3535 self.Bind(wx.EVT_MENU, self.license_handler, self.menuitem_license)
3536 menuitem = help_action.FindItemById(help_action.FindItem("go_to_website"))
3537 self.Bind(
3538 wx.EVT_MENU, lambda event: launch_file(f"https://{DOMAIN}/"), menuitem
3539 )
3540 menuitem = help_action.FindItemById(help_action.FindItem("help_support"))
3541 self.Bind(wx.EVT_MENU, self.help_support_handler, menuitem)
3542 menuitem = help_action.FindItemById(help_action.FindItem("bug_report"))
3543 self.Bind(wx.EVT_MENU, self.bug_report_handler, menuitem)
3544 self.menuitem_app_auto_update_check = help_action.FindItemById(
3545 help_action.FindItem("update_check.onstartup")
3546 )
3547 self.Bind(
3548 wx.EVT_MENU,
3549 self.app_auto_update_check_handler,
3550 self.menuitem_app_auto_update_check,
3551 )
3552 menuitem = help_action.FindItemById(help_action.FindItem("update_check"))
3553 self.Bind(wx.EVT_MENU, self.app_update_check_handler, menuitem)
3554
3555 if sys.platform == "darwin":
3556 wx.GetApp().SetMacAboutMenuItemId(self.menuitem_about.GetId())
3557 wx.GetApp().SetMacPreferencesMenuItemId(self.menuitem_prefs.GetId())
3558 wx.GetApp().SetMacExitMenuItemId(self.menuitem_quit.GetId())
3559 wx.GetApp().SetMacHelpMenuTitleName(lang.getstr("menu.help"))
3560 if use_popup_menu:
3561 self.menubar.bind_keys()
3562
3563 def update_menus(self) -> None:
3564 """Enable/disable menu items based on available Argyll functionality."""
3565 self.menuitem_testchart_edit.Enable(self.create_testchart_btn.Enabled)
3566 self.menuitem_measure_testchart.Enable(
3567 bool(self.worker.displays) and bool(self.worker.instruments)
3568 )
3569 if self.menuitem_specplot_run:
3570 self.menuitem_specplot_run.Enable(self.worker.argyll_version > [0, 0, 0])
3571 self.menuitem_create_profile.Enable(bool(self.worker.displays))
3572 edid = self.worker.get_display_edid()
3573 self.menuitem_create_profile_from_edid.Enable(
3574 bool(
3575 self.worker.displays
3576 and edid
3577 and edid.get("monitor_name", edid.get("ascii", edid["product_id"]))
3578 and edid["red_x"]
3579 and edid["red_y"]
3580 and edid["green_x"]
3581 and edid["green_y"]
3582 and edid["blue_x"]
3583 and edid["blue_y"]
3584 )
3585 )
3586 self.menuitem_profile_hires_b2a.Enable(self.worker.argyll_version > [0, 0, 0])
3587 self.menuitem_install_display_profile.Enable(
3588 bool(self.worker.displays) and not config.is_virtual_display()
3589 )
3590 calibration_loading_supported = self.worker.calibration_loading_supported
3591 self.menuitem_load_lut_from_cal_or_profile.Enable(
3592 bool(self.worker.displays) and calibration_loading_supported
3593 )
3594 self.menuitem_load_lut_from_display_profile.Enable(
3595 bool(self.worker.displays) and calibration_loading_supported
3596 )
3597 self.menuitem_skip_legacy_serial_ports.Check(
3598 bool(getcfg("skip_legacy_serial_ports"))
3599 )
3600 if sys.platform not in ("darwin", "win32") or TEST:
3601 has_separate_lut_access = self.worker.has_separate_lut_access()
3602 self.menuitem_use_separate_lut_access.Check(
3603 has_separate_lut_access or bool(getcfg("use_separate_lut_access"))
3604 )
3605 self.menuitem_use_separate_lut_access.Enable(not has_separate_lut_access)
3606 has_lut_access = self.worker.has_lut_access()
3607 do_not_use_video_lut = self.worker.argyll_version >= [1, 3, 3] and (
3608 not has_lut_access or not getcfg("calibration.use_video_lut")
3609 )
3610 self.menuitem_do_not_use_video_lut.Check(do_not_use_video_lut)
3611 self.menuitem_do_not_use_video_lut.Enable(
3612 self.worker.argyll_version >= [1, 3, 3] and has_lut_access
3613 )
3614 self.menuitem_allow_skip_sensor_cal.Check(bool(getcfg("allow_skip_sensor_cal")))
3615 self.menuitem_calibrate_instrument.Enable(
3616 bool(self.worker.get_instrument_features().get("sensor_cal"))
3617 )
3618 self.menuitem_enable_3dlut_tab.Check(bool(getcfg("3dlut.tab.enable")))
3619 self.menuitem_enable_argyll_debug.Check(bool(getcfg("argyll.debug")))
3620 self.menuitem_enable_dry_run.Check(bool(getcfg("dry_run")))
3621 self.menuitem_startup_sound.Check(bool(getcfg("startup_sound.enable")))
3622 if self.menuitem_use_simple_splash:
3623 self.menuitem_use_simple_splash.Check(bool(getcfg("splash.simple")))
3624 self.menuitem_use_fancy_progress.Check(bool(getcfg("use_fancy_progress")))
3625 self.menuitem_advanced_options.Enable(bool(getcfg("show_advanced_options")))
3626 spyd2en = get_argyll_util("spyd2en")
3627 spyder2_firmware_exists = self.worker.spyder2_firmware_exists()
3628 if sys.platform not in ("darwin", "win32") or TEST:
3629 installed = get_argyll_instrument_config("installed")
3630 installable = get_argyll_instrument_config()
3631 # Only enable if not yet installed and installable
3632 self.menuitem_install_argyll_instrument_conf.Enable(
3633 bool(not installed and installable)
3634 )
3635 # Only enable if installed and (re-)installable
3636 self.menuitem_uninstall_argyll_instrument_conf.Enable(
3637 bool(installed and installable)
3638 )
3639 self.menuitem_enable_spyder2.Enable(bool(spyd2en))
3640 self.menuitem_enable_spyder2.Check(bool(spyd2en) and spyder2_firmware_exists)
3641 self.menuitem_show_lut.Enable(
3642 bool(LUTFrame) and self.worker.argyll_version > [0, 0, 0]
3643 )
3644 self.menuitem_show_lut.Check(bool(getcfg("lut_viewer.show")))
3645 if hasattr(self, "lut_viewer"):
3646 self.lut_viewer.update_controls()
3647 self.menuitem_lut_reset.Enable(
3648 bool(self.worker.displays) and calibration_loading_supported
3649 )
3650 mr_enable = (
3651 bool(self.worker.displays)
3652 and bool(self.worker.instruments)
3653 and getcfg("calibration.file", False) not in self.presets[1:]
3654 )
3655 self.menuitem_measurement_report.Enable(mr_enable)
3656 self.menuitem_report_calibrated.Enable(
3657 bool(self.worker.displays)
3658 and bool(self.worker.instruments)
3659 and not config.is_non_argyll_display()
3660 )
3661 self.menuitem_report_uncalibrated.Enable(
3662 bool(self.worker.displays)
3663 and bool(self.worker.instruments)
3664 and not config.is_non_argyll_display()
3665 )
3666 self.menuitem_calibration_verify.Enable(
3667 bool(self.worker.displays)
3668 and bool(self.worker.instruments)
3669 and not config.is_non_argyll_display()
3670 )
3671 self.mr_settings_btn.Enable(
3672 bool(self.worker.displays) and bool(self.worker.instruments)
3673 )
3674 self.menuitem_measure_uniformity.Enable(
3675 bool(self.worker.displays) and bool(self.worker.instruments)
3676 )
3677 self.menuitem_measurement_file_check_auto.Check(
3678 bool(getcfg("ti3.check_sanity.auto"))
3679 )
3680 self.menuitem_create_colorimeter_correction.Enable(
3681 bool(get_argyll_util("ccxxmake"))
3682 )
3683 self.menuitem_show_log.Check(bool(getcfg("log.show")))
3684 self.menuitem_log_autoshow.Enable(not bool(getcfg("log.show")))
3685 self.menuitem_log_autoshow.Check(bool(getcfg("log.autoshow")))
3686 self.menuitem_app_auto_update_check.Check(bool(getcfg("update_check")))
3687
3688 def init_controls(self) -> None:
3689 """Initialize the main window controls and their event handlers."""
3690 for child in (
3691 self.display_box_label,
3692 self.instrument_box_label,
3693 self.calibration_settings_label,
3694 self.profile_settings_label,
3695 self.lut3d_settings_label,
3696 self.mr_settings_label,
3697 ):
3698 font = child.Font
3699 font.SetWeight(wx.FONTWEIGHT_BOLD)
3700 child.Font = font
3701
3702 # Settings file controls
3703 # ======================
3704
3705 # Settings file dropdown
3706 self.Bind(
3707 wx.EVT_CHOICE,
3708 self.calibration_file_ctrl_handler,
3709 id=self.calibration_file_ctrl.GetId(),
3710 )
3711 self.Bind(
3712 wx.EVT_BUTTON, self.load_cal_handler, id=self.calibration_file_btn.GetId()
3713 )
3714 self.Bind(
3715 wx.EVT_BUTTON,
3716 self.create_session_archive_handler,
3717 id=self.create_session_archive_btn.GetId(),
3718 )
3719 self.Bind(
3720 wx.EVT_BUTTON,
3721 self.delete_calibration_handler,
3722 id=self.delete_calibration_btn.GetId(),
3723 )
3724 self.Bind(
3725 wx.EVT_BUTTON,
3726 self.install_profile_handler,
3727 id=self.install_profile_btn.GetId(),
3728 )
3729 self.Bind(
3730 wx.EVT_BUTTON, self.profile_info_handler, id=self.profile_info_btn.GetId()
3731 )
3732
3733 # Update calibration checkbox
3734 self.Bind(
3735 wx.EVT_CHECKBOX,
3736 self.calibration_update_ctrl_handler,
3737 id=self.calibration_update_cb.GetId(),
3738 )
3739
3740 # Display
3741 self.Bind(
3742 wx.EVT_CHOICE, self.display_ctrl_handler, id=self.display_ctrl.GetId()
3743 )
3744 self.Bind(
3745 wx.EVT_CHOICE,
3746 self.display_lut_ctrl_handler,
3747 id=self.display_lut_ctrl.GetId(),
3748 )
3749 self.Bind(
3750 wx.EVT_BUTTON,
3751 self.display_lut_link_ctrl_handler,
3752 id=self.display_lut_link_ctrl.GetId(),
3753 )
3754
3755 # Instrument
3756 self.Bind(
3757 wx.EVT_CHOICE, self.comport_ctrl_handler, id=self.comport_ctrl.GetId()
3758 )
3759 self.Bind(
3760 wx.EVT_CHOICE,
3761 self.measurement_mode_ctrl_handler,
3762 id=self.measurement_mode_ctrl.GetId(),
3763 )
3764 self.Bind(
3765 wx.EVT_BUTTON,
3766 self.check_update_controls,
3767 id=self.detect_displays_and_ports_btn.GetId(),
3768 )
3769
3770 # Display update delay & settle time
3771 min_val, max_val = config.VALID_RANGES["measure.min_display_update_delay_ms"]
3772 self.min_display_update_delay_ms.SetRange(min_val, max_val)
3773
3774 min_val, max_val = config.VALID_RANGES["measure.display_settle_time_mult"]
3775 self.display_settle_time_mult.SetDigits(
3776 len(str(stripzeros(min_val)).split(".")[-1])
3777 )
3778 self.display_settle_time_mult.SetIncrement(min_val)
3779 self.display_settle_time_mult.SetRange(min_val, max_val)
3780 self.Bind(
3781 wx.EVT_CHECKBOX,
3782 self.display_delay_handler,
3783 id=self.override_min_display_update_delay_ms.GetId(),
3784 )
3785 self.Bind(
3786 wx.EVT_TEXT,
3787 self.display_delay_handler,
3788 id=self.min_display_update_delay_ms.GetId(),
3789 )
3790 self.Bind(
3791 wx.EVT_CHECKBOX,
3792 self.display_delay_handler,
3793 id=self.override_display_settle_time_mult.GetId(),
3794 )
3795 self.Bind(
3796 floatspin.EVT_FLOATSPIN,
3797 self.display_delay_handler,
3798 id=self.display_settle_time_mult.GetId(),
3799 )
3800
3801 # frame insertion
3802 self.ffp_insertion.Bind(
3803 wx.EVT_CHECKBOX,
3804 lambda event: (
3805 setcfg("patterngenerator.ffp_insertion", event.GetInt())
3806 or self.update_ffp_insertion_ctrl()
3807 or self.update_estimated_measurement_times()
3808 ),
3809 )
3810 min_val, max_val = config.VALID_RANGES[
3811 "patterngenerator.ffp_insertion.interval"
3812 ]
3813 self.ffp_insertion_interval.SetRange(min_val, max_val)
3814 self.ffp_insertion_interval.Bind(
3815 floatspin.EVT_FLOATSPIN,
3816 lambda event: (
3817 setcfg("patterngenerator.ffp_insertion.interval", event.GetValue())
3818 or self.update_estimated_measurement_times()
3819 ),
3820 )
3821 min_val, max_val = config.VALID_RANGES[
3822 "patterngenerator.ffp_insertion.duration"
3823 ]
3824 self.ffp_insertion_duration.SetRange(min_val, max_val)
3825 self.ffp_insertion_duration.Bind(
3826 floatspin.EVT_FLOATSPIN,
3827 lambda event: (
3828 setcfg("patterngenerator.ffp_insertion.duration", event.GetValue())
3829 or self.update_estimated_measurement_times()
3830 ),
3831 )
3832 self.ffp_insertion_level.Bind(
3833 wx.EVT_SPINCTRL,
3834 lambda event: setcfg(
3835 "patterngenerator.ffp_insertion.level", event.GetPosition() / 100.0
3836 ),
3837 )
3838
3839 # Output levels
3840 self.output_levels_auto.Bind(wx.EVT_RADIOBUTTON, self.output_levels_handler)
3841 self.output_levels_full_range.Bind(
3842 wx.EVT_RADIOBUTTON, self.output_levels_handler
3843 )
3844 self.output_levels_limited_range.Bind(
3845 wx.EVT_RADIOBUTTON, self.output_levels_handler
3846 )
3847
3848 # Observer
3849 self.observer_ctrl.Bind(wx.EVT_CHOICE, self.observer_ctrl_handler)
3850
3851 # Colorimeter correction matrix
3852 self.Bind(
3853 wx.EVT_CHOICE,
3854 self.colorimeter_correction_matrix_ctrl_handler,
3855 id=self.colorimeter_correction_matrix_ctrl.GetId(),
3856 )
3857 self.Bind(
3858 wx.EVT_BUTTON,
3859 self.colorimeter_correction_matrix_ctrl_handler,
3860 id=self.colorimeter_correction_matrix_btn.GetId(),
3861 )
3862 self.Bind(
3863 wx.EVT_BUTTON,
3864 self.colorimeter_correction_info_handler,
3865 id=self.colorimeter_correction_info_btn.GetId(),
3866 )
3867 self.Bind(
3868 wx.EVT_BUTTON,
3869 self.colorimeter_correction_web_handler,
3870 id=self.colorimeter_correction_web_btn.GetId(),
3871 )
3872 self.colorimeter_correction_create_btn.Bind(
3873 wx.EVT_BUTTON, self.create_colorimeter_correction_handler
3874 )
3875
3876 # Display tech info
3877 self.Bind(
3878 wx.EVT_BUTTON,
3879 self.display_tech_info_show_handler,
3880 id=self.display_tech_info_show_btn.Id,
3881 )
3882
3883 # Calibration settings
3884 # ====================
3885
3886 # Whitepoint
3887 self.Bind(
3888 wx.EVT_CHOICE, self.whitepoint_ctrl_handler, id=self.whitepoint_ctrl.GetId()
3889 )
3890 self.Bind(
3891 wx.EVT_COMBOBOX,
3892 self.whitepoint_ctrl_handler,
3893 id=self.whitepoint_colortemp_textctrl.GetId(),
3894 )
3895 self.whitepoint_colortemp_textctrl.SetItems(self.whitepoint_presets)
3896 self.whitepoint_colortemp_textctrl.Bind(
3897 wx.EVT_KILL_FOCUS, self.whitepoint_ctrl_handler
3898 )
3899 self.Bind(
3900 wx.EVT_CHOICE,
3901 self.whitepoint_colortemp_locus_ctrl_handler,
3902 id=self.whitepoint_colortemp_locus_ctrl.GetId(),
3903 )
3904 self.whitepoint_x_textctrl.Bind(
3905 floatspin.EVT_FLOATSPIN, self.whitepoint_ctrl_handler
3906 )
3907 self.whitepoint_y_textctrl.Bind(
3908 floatspin.EVT_FLOATSPIN, self.whitepoint_ctrl_handler
3909 )
3910 self.Bind(
3911 wx.EVT_BUTTON,
3912 self.ambient_measure_handler,
3913 id=self.whitepoint_measure_btn.GetId(),
3914 )
3915 self.Bind(
3916 wx.EVT_BUTTON,
3917 self.visual_whitepoint_editor_handler,
3918 id=self.visual_whitepoint_editor_btn.GetId(),
3919 )
3920
3921 # White luminance
3922 self.Bind(
3923 wx.EVT_CHOICE, self.luminance_ctrl_handler, id=self.luminance_ctrl.GetId()
3924 )
3925 self.luminance_textctrl.Bind(
3926 floatspin.EVT_FLOATSPIN, self.luminance_ctrl_handler
3927 )
3928 self.Bind(
3929 wx.EVT_CHECKBOX,
3930 self.whitelevel_drift_compensation_handler,
3931 id=self.whitelevel_drift_compensation.GetId(),
3932 )
3933 self.Bind(
3934 wx.EVT_BUTTON,
3935 self.luminance_measure_handler,
3936 id=self.luminance_measure_btn.GetId(),
3937 )
3938 self.Bind(
3939 wx.EVT_BUTTON,
3940 self.ambient_measure_handler,
3941 id=self.ambient_luminance_measure_btn.GetId(),
3942 )
3943
3944 # Black luminance
3945 self.Bind(
3946 wx.EVT_CHOICE,
3947 self.black_luminance_ctrl_handler,
3948 id=self.black_luminance_ctrl.GetId(),
3949 )
3950 self.black_luminance_textctrl.Bind(
3951 floatspin.EVT_FLOATSPIN, self.black_luminance_ctrl_handler
3952 )
3953 self.Bind(
3954 wx.EVT_CHECKBOX,
3955 self.blacklevel_drift_compensation_handler,
3956 id=self.blacklevel_drift_compensation.GetId(),
3957 )
3958 self.Bind(
3959 wx.EVT_BUTTON,
3960 self.luminance_measure_handler,
3961 id=self.black_luminance_measure_btn.GetId(),
3962 )
3963
3964 # Tonal response curve (TRC)
3965 self.Bind(wx.EVT_CHOICE, self.trc_ctrl_handler, id=self.trc_ctrl.GetId())
3966 self.trc_textctrl.SetItems(self.trc_presets)
3967 self.trc_textctrl.SetValue(str(DEFAULTS["gamma"]))
3968 self.Bind(wx.EVT_COMBOBOX, self.trc_ctrl_handler, id=self.trc_textctrl.GetId())
3969 self.trc_textctrl.Bind(wx.EVT_KILL_FOCUS, self.trc_ctrl_handler)
3970 self.Bind(
3971 wx.EVT_CHOICE, self.trc_type_ctrl_handler, id=self.trc_type_ctrl.GetId()
3972 )
3973
3974 # Viewing condition adjustment for ambient in Lux
3975 self.Bind(
3976 wx.EVT_CHECKBOX,
3977 self.ambient_viewcond_adjust_ctrl_handler,
3978 id=self.ambient_viewcond_adjust_cb.GetId(),
3979 )
3980 self.ambient_viewcond_adjust_textctrl.Bind(
3981 floatspin.EVT_FLOATSPIN, self.ambient_viewcond_adjust_ctrl_handler
3982 )
3983 self.Bind(
3984 wx.EVT_BUTTON,
3985 self.ambient_measure_handler,
3986 id=self.ambient_measure_btn.GetId(),
3987 )
3988
3989 # Black level output offset
3990 self.Bind(
3991 wx.EVT_SLIDER,
3992 self.black_output_offset_ctrl_handler,
3993 id=self.black_output_offset_ctrl.GetId(),
3994 )
3995 self.Bind(
3996 wx.EVT_TEXT,
3997 self.black_output_offset_ctrl_handler,
3998 id=self.black_output_offset_intctrl.GetId(),
3999 )
4000
4001 # Black point hue correction
4002 self.Bind(
4003 wx.EVT_CHECKBOX,
4004 self.black_point_correction_auto_handler,
4005 id=self.black_point_correction_auto_cb.GetId(),
4006 )
4007 self.Bind(
4008 wx.EVT_SLIDER,
4009 self.black_point_correction_ctrl_handler,
4010 id=self.black_point_correction_ctrl.GetId(),
4011 )
4012 self.Bind(
4013 wx.EVT_TEXT,
4014 self.black_point_correction_ctrl_handler,
4015 id=self.black_point_correction_intctrl.GetId(),
4016 )
4017
4018 # Black point correction rate
4019 self.Bind(
4020 wx.EVT_SLIDER,
4021 self.black_point_rate_ctrl_handler,
4022 id=self.black_point_rate_ctrl.GetId(),
4023 )
4024 self.Bind(
4025 floatspin.EVT_FLOATSPIN,
4026 self.black_point_rate_ctrl_handler,
4027 id=self.black_point_rate_floatctrl.GetId(),
4028 )
4029
4030 # Calibration quality
4031 self.Bind(
4032 wx.EVT_SLIDER,
4033 self.calibration_quality_ctrl_handler,
4034 id=self.calibration_quality_ctrl.GetId(),
4035 )
4036
4037 # Interactive display adjustment
4038 self.Bind(
4039 wx.EVT_CHECKBOX,
4040 self.interactive_display_adjustment_ctrl_handler,
4041 id=self.interactive_display_adjustment_cb.GetId(),
4042 )
4043
4044 # Profiling settings
4045 # ==================
4046
4047 # Testchart file
4048 self.Bind(
4049 wx.EVT_CHOICE, self.testchart_ctrl_handler, id=self.testchart_ctrl.GetId()
4050 )
4051 self.Bind(
4052 wx.EVT_BUTTON, self.testchart_btn_handler, id=self.testchart_btn.GetId()
4053 )
4054 self.Bind(
4055 wx.EVT_BUTTON,
4056 self.create_testchart_btn_handler,
4057 id=self.create_testchart_btn.GetId(),
4058 )
4059 self.testchart_patches_amount_ctrl.SetRange(
4060 config.VALID_VALUES["testchart.auto_optimize"][1],
4061 config.VALID_VALUES["testchart.auto_optimize"][-1],
4062 )
4063 self.testchart_patches_amount_ctrl.Bind(
4064 wx.EVT_SLIDER, self.testchart_patches_amount_ctrl_handler
4065 )
4066
4067 # Patch sequence
4068 self.Bind(
4069 wx.EVT_CHOICE,
4070 self.testchart_patch_sequence_ctrl_handler,
4071 id=self.testchart_patch_sequence_ctrl.GetId(),
4072 )
4073
4074 # Profile quality
4075 self.Bind(
4076 wx.EVT_SLIDER,
4077 self.profile_quality_ctrl_handler,
4078 id=self.profile_quality_ctrl.GetId(),
4079 )
4080
4081 # Profile type
4082 self.Bind(
4083 wx.EVT_CHOICE,
4084 self.profile_type_ctrl_handler,
4085 id=self.profile_type_ctrl.GetId(),
4086 )
4087
4088 # Advanced (gamut mapping)
4089 self.Bind(wx.EVT_BUTTON, self.gamap_btn_handler, id=self.gamap_btn.GetId())
4090
4091 # Black point compensation
4092 self.Bind(
4093 wx.EVT_CHECKBOX,
4094 self.black_point_compensation_ctrl_handler,
4095 id=self.black_point_compensation_cb.GetId(),
4096 )
4097
4098 # Profile name
4099 self.Bind(
4100 wx.EVT_TEXT,
4101 self.profile_name_ctrl_handler,
4102 id=self.profile_name_textctrl.GetId(),
4103 )
4104 self.profile_name_info_btn.Bind(
4105 wx.EVT_BUTTON, self.profile_name_info_btn_handler
4106 )
4107 self.profile_name_info_btn.SetToolTipString(lang.getstr("profile.name"))
4108 self.Bind(
4109 wx.EVT_BUTTON,
4110 self.profile_save_path_btn_handler,
4111 id=self.profile_save_path_btn.GetId(),
4112 )
4113
4114 # 3D LUT controls
4115 # ===============
4116
4117 self.lut3d_create_cb.Bind(wx.EVT_CHECKBOX, self.lut3d_create_cb_handler)
4118 self.lut3d_init_input_profiles()
4119 self.lut3d_input_profile_ctrl.Bind(
4120 wx.EVT_CHOICE, self.lut3d_input_colorspace_handler
4121 )
4122 self.lut3d_bind_event_handlers()
4123
4124 # Main buttons
4125 # ============
4126
4127 for btn_name in (
4128 "calibrate_btn",
4129 "calibrate_and_profile_btn",
4130 "profile_btn",
4131 "lut3d_create_btn",
4132 "measurement_report_btn",
4133 ):
4134 btn = getattr(self, btn_name)
4135 # wx.Button does not look correct when a custom background color is
4136 # set because the button label background inherits the button
4137 # background. Replace with ThemedGenButton which does not have
4138 # that issue
4139 subst = BorderGradientButton(
4140 parent=btn.Parent,
4141 bitmap=get_icon(16, "start"),
4142 label=btn.Label,
4143 name=btn.Name,
4144 )
4145 subst.SetBackgroundColour(btn.Parent.BackgroundColour)
4146 if sys.platform == "win32":
4147 subst.SetTopStartColour(
4148 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
4149 )
4150 subst.SetTopEndColour(
4151 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
4152 ) # Not used
4153 subst.SetBottomStartColour(
4154 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
4155 ) # Not used
4156 subst.SetBottomEndColour(
4157 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
4158 )
4159 else:
4160 subst.SetTopStartColour(
4161 wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
4162 )
4163 subst.SetBottomEndColour(
4164 wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
4165 )
4166 subst.SetForegroundColour(
4167 wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT)
4168 )
4169 subst.SetPressedTopColour(
4170 wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
4171 )
4172 subst.SetPressedBottomColour(
4173 wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
4174 )
4175 setattr(self, btn_name, subst)
4176 btn.ContainingSizer.Replace(btn, subst)
4177 btn.Destroy()
4178
4179 self.Bind(
4180 wx.EVT_BUTTON, self.calibrate_btn_handler, id=self.calibrate_btn.GetId()
4181 )
4182 self.Bind(
4183 wx.EVT_BUTTON,
4184 self.calibrate_and_profile_btn_handler,
4185 id=self.calibrate_and_profile_btn.GetId(),
4186 )
4187 self.Bind(wx.EVT_BUTTON, self.profile_btn_handler, id=self.profile_btn.GetId())
4188 self.lut3d_create_btn.Bind(wx.EVT_BUTTON, self.lut3d_create_handler)
4189 self.measurement_report_btn.Bind(wx.EVT_BUTTON, self.measurement_report_handler)
4190
4191 def set_language_handler(self, event: wx.Event) -> None:
4192 """Set a new language globally and on-the-fly.
4193
4194 Args:
4195 event (wx.Event): The event that triggered this handler.
4196 """
4197 for lcode in lang.LDICT:
4198 if lang.LDICT[lcode].menuitem_id != event.GetId():
4199 continue
4200 # Get the previously marked menu item
4201 menuitem = self.menubar.FindItemById(lang.LDICT[lang.getcode()].menuitem_id)
4202 if hasattr(self, "tcframe"):
4203 if not self.tcframe.tc_close_handler():
4204 # Do not change language, mark previous menu item
4205 menuitem.Check()
4206 return
4207 self.tcframe.Destroy()
4208 del self.tcframe
4209 # Set the previously marked menu item's font weight to normal
4210 font = menuitem.Font
4211 font.SetWeight(wx.FONTWEIGHT_NORMAL)
4212 menuitem.SetFont(font)
4213 # Set the currently marked menu item's font weight to bold
4214 menuitem = self.menubar.FindItemById(lang.LDICT[lcode].menuitem_id)
4215 font = menuitem.Font
4216 font.SetWeight(wx.FONTWEIGHT_BOLD)
4217 menuitem.SetFont(font)
4218 setcfg("lang", lcode)
4219 writecfg()
4220 self.panel.Freeze()
4221 self.header.SetLabel(lang.getstr("header"))
4222 self.setup_language()
4223 if hasattr(self, "extra_args"):
4224 self.extra_args.Sizer.SetSizeHints(self.extra_args)
4225 self.extra_args.Sizer.Layout()
4226 if hasattr(self, "gamapframe"):
4227 self.gamapframe.panel.Freeze()
4228 self.gamapframe.setup_language()
4229 self.gamapframe.update_layout()
4230 self.gamapframe.panel.Thaw()
4231 if getattr(self, "lut3dframe", None):
4232 self.lut3dframe.panel.Freeze()
4233 self.lut3dframe.setup_language()
4234 self.lut3dframe.update_controls()
4235 self.lut3dframe.update_layout()
4236 self.lut3dframe.panel.Thaw()
4237 if getattr(self, "reportframe", None):
4238 self.reportframe.panel.Freeze()
4239 self.reportframe.setup_language()
4240 self.reportframe.update_controls()
4241 self.reportframe.update_layout()
4242 self.reportframe.panel.Thaw()
4243 if getattr(self, "synthiccframe", None):
4244 self.synthiccframe.panel.Freeze()
4245 self.synthiccframe.setup_language()
4246 self.synthiccframe.update_controls()
4247 self.synthiccframe.update_layout()
4248 self.synthiccframe.panel.Thaw()
4249 self.update_measurement_modes()
4250 self.update_controls()
4251 self.update_displays()
4252 self.set_testcharts()
4253 self.update_layout()
4254 self.panel.Thaw()
4255 if hasattr(self, "aboutdialog"):
4256 self.aboutdialog.Destroy()
4257 del self.aboutdialog
4258 log_txt = self.infoframe.log_txt.GetValue().encode("UTF-8", "replace")
4259 if log_txt:
4260 # Remember current log window contents
4261 if not self.infoframe.IsShownOnScreen():
4262 # Append buffer of non-shown log window
4263 LOGBUFFER.seek(0)
4264 log_txt += LOGBUFFER.read()
4265 LOGBUFFER.truncate(0)
4266 LOGBUFFER.write(log_txt)
4267 self.infoframe.Destroy()
4268 self.init_infoframe(show=getcfg("log.show"))
4269 if sys.platform in ("darwin", "win32") or ISEXE:
4270 self.measureframe.Destroy()
4271 self.init_measureframe()
4272 if hasattr(self, "lut_viewer"):
4273 self.lut_viewer.Destroy()
4274 del self.lut_viewer
4275 if getcfg("lut_viewer.show"):
4276 # Using wx.CallAfter fixes wrong positioning under wxGTK
4277 # with wxPython 3
4278 wx.CallAfter(self.init_lut_viewer, show=True)
4279 if hasattr(self, "profile_name_tooltip_window"):
4280 self.profile_name_tooltip_window.Destroy()
4281 del self.profile_name_tooltip_window
4282 if hasattr(self, "display_tech_info_tooltip_window"):
4283 self.display_tech_info_tooltip_window.Destroy()
4284 del self.display_tech_info_tooltip_window
4285 for progress_wnd in self.worker.progress_wnds:
4286 if progress_wnd:
4287 progress_wnd.Destroy()
4288 wx.CallAfter(self.Raise)
4289 if isinstance(getattr(sys, "_appsocket", None), socket.socket):
4290 threading.Thread(
4291 target=self.set_remote_language,
4292 name="Scripting.SetClientLanguage",
4293 ).start()
4294 break
4295
4296 def set_remote_language(self) -> None:
4297 """Set the language of all running standalone tools (if supported)."""
4298 # Set language of all running standalone tools (if supported)
4299 app_ip, app_port = sys._appsocket.getsockname()
4300 for host in self.get_scripting_hosts():
4301 ip_port, name = host.split(None, 1)
4302 ip, port = ip_port.split(":", 1)
4303 port = int(port)
4304 if ip == app_ip and port == app_port:
4305 continue
4306 try:
4307 conn = self.connect(ip, port)
4308 if isinstance(conn, Exception):
4309 print("Warning - couldn't connect to", ip_port, f"({name}):", conn)
4310 continue
4311 conn.send_command("getappname")
4312 remote_appname = conn.get_single_response()
4313 if remote_appname == APPNAME:
4314 print("Warning - connected to self, skipping")
4315 del conn
4316 continue
4317 conn.send_command(f"setlanguage {lang.getcode()}")
4318 response = conn.get_single_response()
4319 if response not in ("ok", "invalid"):
4320 print(
4321 "Warning - couldn't set language for",
4322 name,
4323 f"({ip_port}):",
4324 response,
4325 )
4326 if remote_appname == f"{APPNAME}-apply-profiles":
4327 # Update notification text of profile loader
4328 conn.send_command(
4329 "notify '{}' silent sticky".format(
4330 lang.getstr(
4331 "app.detected.calibration_loading_disabled", APPNAME
4332 )
4333 )
4334 )
4335 response = conn.get_single_response()
4336 if response != "ok":
4337 print(
4338 "Warning - couldn't update profile loader "
4339 "notification text:",
4340 response,
4341 )
4342 del conn
4343 except Exception as exception:
4344 print(
4345 "Warning - error while trying to set language for",
4346 name,
4347 f"({ip_port})",
4348 exception,
4349 )
4350
4351 def update_layout(self) -> None:
4352 """Update main window layout."""
4353 self.set_size(True, True)
4354
4355 def restore_defaults_handler(
4356 self,
4357 event: None | wx.Event = None,
4358 include: tuple = (),
4359 exclude: tuple = (),
4360 override: None | dict = None,
4361 ) -> None:
4362 """Restore default settings.
4363
4364 Args:
4365 event (wx.Event): The event that triggered this handler, if any.
4366 include (tuple): Settings to include in the restore operation.
4367 exclude (tuple): Settings to exclude from the restore operation.
4368 override (dict): Settings to override with specific values.
4369 """
4370 if event:
4371 dlg = ConfirmDialog(
4372 self,
4373 msg=lang.getstr("app.confirm_restore_defaults"),
4374 ok=lang.getstr("ok"),
4375 cancel=lang.getstr("cancel"),
4376 bitmap=get_bitmap("theme/icons/32x32/dialog-warning"),
4377 )
4378 result = dlg.ShowModal()
4379 dlg.Destroy()
4380 if result != wx.ID_OK:
4381 return
4382 if getcfg("settings.changed"):
4383 self.settings_discard_changes()
4384 skip = [
4385 "allow_skip_sensor_cal",
4386 "app.allow_network_clients",
4387 "app.port",
4388 "argyll.dir",
4389 "argyll.version",
4390 "calibration.autoload",
4391 "calibration.black_point_rate.enabled",
4392 "calibration.file.previous",
4393 "calibration.update",
4394 "colorimeter_correction.instrument",
4395 "colorimeter_correction.instrument.reference",
4396 "colorimeter_correction.measurement_mode",
4397 "colorimeter_correction.measurement_mode.reference",
4398 "colorimeter_correction.measurement_mode.reference.projector",
4399 "colorimeter_correction_matrix_file",
4400 "comport.number",
4401 "copyright",
4402 "dimensions.measureframe.whitepoint.visual_editor",
4403 "display.number",
4404 "display.technology",
4405 "display_lut.link",
4406 "display_lut.number",
4407 "displays",
4408 "dry_run",
4409 "enumerate_ports.auto",
4410 "gamma",
4411 "iccgamut.surface_detail",
4412 "instruments",
4413 "lang",
4414 "last_3dlut_path",
4415 "last_cal_path",
4416 "last_cal_or_icc_path",
4417 "last_colorimeter_ti3_path",
4418 "last_filedialog_path",
4419 "last_icc_path",
4420 "last_reference_ti3_path",
4421 "last_testchart_export_path",
4422 "last_ti1_path",
4423 "last_ti3_path",
4424 "last_vrml_path",
4425 "log.show",
4426 "lut_viewer.show",
4427 "lut_viewer.show_actual_lut",
4428 "measurement_mode",
4429 "measurement_mode.projector",
4430 "measurement.name.expanded",
4431 "measurement.play_sound",
4432 "measurement.save_path",
4433 "multiprocessing.max_cpus",
4434 "patterngenerator.apl",
4435 "patterngenerator.resolve",
4436 "patterngenerator.resolve.port",
4437 "profile.b2a.hires.diagpng",
4438 "profile.create_gamut_views",
4439 "profile.install_scope",
4440 "profile.license",
4441 "profile.load_on_login",
4442 "profile.name",
4443 "profile.name.expanded",
4444 "profile.save_path",
4445 "profile_loader.check_gamma_ramps",
4446 "profile_loader.error.show_msg",
4447 "profile_loader.exceptions",
4448 "profile_loader.fix_profile_associations",
4449 "profile_loader.known_apps",
4450 "profile_loader.known_window_classes",
4451 "profile_loader.reset_gamma_ramps",
4452 "profile_loader.use_madhcnet",
4453 "profile_loader.verify_calibration",
4454 "profile.update",
4455 "position.x",
4456 "position.y",
4457 "position.info.x",
4458 "position.info.y",
4459 "position.lut_viewer.x",
4460 "position.lut_viewer.y",
4461 "position.lut3dframe.x",
4462 "position.lut3dframe.y",
4463 "position.synthiccframe.x",
4464 "position.synthiccframe.y",
4465 "position.profile_info.x",
4466 "position.profile_info.y",
4467 "position.progress.x",
4468 "position.progress.y",
4469 "position.reportframe.x",
4470 "position.reportframe.y",
4471 "position.scripting.x",
4472 "position.scripting.y",
4473 "position.tcgen.x",
4474 "position.tcgen.y",
4475 "recent_cals",
4476 "report.pack_js",
4477 "settings.changed",
4478 "show_advanced_options",
4479 "show_donation_message",
4480 "skip_legacy_serial_ports",
4481 "skip_scripts",
4482 "sudo.preserve_environment",
4483 "tc_precond_profile",
4484 "tc_vrml_cie",
4485 "tc_vrml_cie_colorspace",
4486 "tc_vrml_device",
4487 "tc_vrml_device_colorspace",
4488 "tc.show",
4489 "uniformity.measure.continuous",
4490 "untethered.measure.auto",
4491 "untethered.measure.manual.delay",
4492 "untethered.max_delta.chroma",
4493 "untethered.min_delta",
4494 "untethered.min_delta.lightness",
4495 "update_check",
4496 "webserver.portnumber",
4497 "whitepoint.visual_editor.bg_v",
4498 "whitepoint.visual_editor.b",
4499 "whitepoint.visual_editor.g",
4500 "whitepoint.visual_editor.r",
4501 "x3dom.cache",
4502 "x3dom.embed",
4503 ]
4504 override_default = {
4505 "app.dpi": None,
4506 "calibration.black_luminance": None,
4507 "calibration.luminance": None,
4508 "gamap_src_viewcond": None,
4509 "gamap_out_viewcond": None,
4510 "testchart.file": "auto",
4511 "trc": DEFAULTS["gamma"],
4512 "whitepoint.colortemp": None,
4513 "whitepoint.x": None,
4514 "whitepoint.y": None,
4515 "3dlut.whitepoint.x": None,
4516 "3dlut.whitepoint.y": None,
4517 }
4518 if override:
4519 override_default.update(override)
4520 override = override_default
4521 for name in DEFAULTS:
4522 if (
4523 name not in skip
4524 and name not in override
4525 and (
4526 len(include) == 0
4527 or False in [name.find(item) != 0 for item in include]
4528 )
4529 and (
4530 len(exclude) == 0
4531 or (False not in [name.find(item) != 0 for item in exclude])
4532 )
4533 ):
4534 if name.endswith(".backup") and name == "measurement_mode.backup":
4535 setcfg("measurement_mode", getcfg("measurement_mode.backup"))
4536 default = None
4537 verbose_print(f"Restoring {name} to {DEFAULTS[name]}", level=3)
4538 setcfg(name, default)
4539 for name in override:
4540 if (
4541 len(include) == 0 or False in [name.find(item) != 0 for item in include]
4542 ) and (
4543 len(exclude) == 0
4544 or (False not in [name.find(item) != 0 for item in exclude])
4545 ):
4546 setcfg(name, override[name])
4547 if event:
4548 writecfg()
4549 self.update_displays()
4550 self.update_controls()
4551 self.update_menus()
4552 if hasattr(self, "tcframe"):
4553 self.tcframe.tc_update_controls()
4554
4555 def cal_changed(self, setchanged: bool = True) -> None:
4556 """Called internally when calibration settings controls are changed.
4557
4558 Exceptions are the calibration quality and interactive display
4559 adjustment controls, which do not cause a 'calibration changed' event.
4560
4561 Args:
4562 setchanged (bool, optional): If True, sets the 'settings.changed'
4563 config option to 1, indicating that the settings have changed.
4564 Defaults to True.
4565 """
4566 if self.updatingctrls or not self.IsShownOnScreen():
4567 return
4568 # update_controls which is called from cal_changed might cause a
4569 # another cal_changed call, in which case we can skip it
4570 debug_print("[D] cal_changed")
4571 if setchanged:
4572 setcfg("settings.changed", 1)
4573 self.worker.options_dispcal = []
4574 if getcfg("calibration.file", False):
4575 setcfg("calibration.file", None)
4576 # Load LUT curves from current display profile (if any, and if
4577 # it contains curves)
4578 self.load_display_profile_cal(None)
4579 self.calibration_file_ctrl.SetStringSelection(lang.getstr("settings.new"))
4580 self.calibration_file_ctrl.SetToolTip(None)
4581 self.create_session_archive_btn.Disable()
4582 self.delete_calibration_btn.Disable()
4583 self.install_profile_btn.Disable()
4584 do_update_controls = self.calibration_update_cb.GetValue()
4585 self.calibration_update_cb.SetValue(False)
4586 setcfg("calibration.update", 0)
4587 self.calibration_update_cb.Disable()
4588 setcfg("profile.update", 0)
4589 if do_update_controls:
4590 self.update_controls()
4591 self.settings_discard_changes(keep_changed_state=True)
4592
4593 def update_displays(
4594 self, update_ccmx_items: bool = False, set_height: bool = False
4595 ) -> None:
4596 """Update the display selector controls.
4597
4598 Args:
4599 update_ccmx_items (bool, optional): If True, updates the
4600 colorimeter correction matrix items in the colorimeter
4601 correction matrix control.
4602 set_height (bool, optional): If True, sets the height of the main
4603 panel to the best virtual size after updating the displays.
4604 """
4605 debug_print("[D] update_displays")
4606 self.panel.Freeze()
4607 self.displays = []
4608 for item in self.worker.displays:
4609 self.displays.append(
4610 item.replace("[PRIMARY]", lang.getstr("display.primary"))
4611 )
4612 self.displays[-1] = lang.getstr(self.displays[-1])
4613 self.display_ctrl.SetItems(self.displays)
4614 self.display_ctrl.Enable(bool(self.worker.displays))
4615 display_lut_sizer = self.display_ctrl.GetContainingSizer()
4616 display_sizer = self.display_lut_link_ctrl.GetContainingSizer()
4617 comport_sizer = self.comport_ctrl.GetContainingSizer()
4618 if sys.platform not in ("darwin", "win32") or TEST:
4619 use_lut_ctrl = self.worker.has_separate_lut_access() or bool(
4620 getcfg("use_separate_lut_access")
4621 )
4622 self.GetMenuBar()
4623 menuitem = self.menu_advanced_options.FindItemById(
4624 self.menu_advanced_options.FindItem(
4625 lang.getstr("use_separate_lut_access")
4626 )
4627 )
4628 menuitem.Check(use_lut_ctrl)
4629 else:
4630 use_lut_ctrl = False
4631 if use_lut_ctrl:
4632 self.display_lut_ctrl.Clear()
4633 for i, disp in enumerate(self.displays):
4634 if self.worker.lut_access[i]:
4635 self.display_lut_ctrl.Append(disp)
4636 comport_sizer.SetCols(1)
4637 comport_sizer.SetRows(2)
4638 else:
4639 comport_sizer.SetCols(2)
4640 comport_sizer.SetRows(1)
4641 setcfg("display_lut.link", 1)
4642 display_lut_sizer.Show(self.display_label, use_lut_ctrl)
4643 display_lut_sizer.Show(self.display_lut_label, use_lut_ctrl)
4644 display_lut_sizer.Show(self.display_lut_ctrl, use_lut_ctrl)
4645 display_sizer.Show(self.display_lut_link_ctrl, use_lut_ctrl)
4646 self.get_set_display(update_ccmx_items)
4647 self.calpanel.Layout()
4648 self.panel.Thaw()
4649 if self.IsShown():
4650 self.set_size(set_height)
4651 self.update_scrollbars()
4652
4653 def update_scrollbars(self) -> None:
4654 """Update the scrollbars of the main panel."""
4655 self.Freeze()
4656 self.calpanel.SetVirtualSize(self.calpanel.GetBestVirtualSize())
4657 self.Thaw()
4658
4659 def update_comports(self, force: bool = False) -> None:
4660 """Update the comport selector control.
4661
4662 Args:
4663 force (bool, optional): If True, forces the update even if the
4664 comport selector is already populated with the current
4665 instruments.
4666 """
4667 self.comport_ctrl.Freeze()
4668 self.comport_ctrl.SetItems(
4669 [
4670 lang.getstr(
4671 "instrument.{}".format(
4672 instrument.lower().replace(" ", "_").replace(",", "")
4673 ),
4674 default=instrument,
4675 )
4676 for instrument in self.worker.instruments
4677 ]
4678 )
4679 if self.worker.instruments:
4680 self.comport_ctrl.SetSelection(
4681 min(
4682 max(0, len(self.worker.instruments) - 1),
4683 max(0, int(getcfg("comport.number")) - 1),
4684 )
4685 )
4686 self.comport_ctrl.Enable(bool(self.worker.instruments))
4687 self.comport_ctrl.Thaw()
4688 self.comport_ctrl_handler(force=force)
4689
4690 def update_measurement_mode(self) -> None:
4691 """Update the measurement mode control."""
4692 measurement_mode = getcfg("measurement_mode")
4693 instrument_features = self.worker.get_instrument_features()
4694 if (
4695 instrument_features.get("adaptive_mode")
4696 and (
4697 self.worker.argyll_version[0:3] > [1, 1, 0]
4698 or (
4699 self.worker.argyll_version[0:3] == [1, 1, 0]
4700 and "Beta" not in self.worker.argyll_version_string
4701 and "RC1" not in self.worker.argyll_version_string
4702 and "RC2" not in self.worker.argyll_version_string
4703 )
4704 )
4705 and getcfg("measurement_mode.adaptive")
4706 ):
4707 measurement_mode += "V"
4708 if instrument_features.get("highres_mode") and getcfg(
4709 "measurement_mode.highres"
4710 ):
4711 measurement_mode += "H"
4712 self.measurement_mode_ctrl.SetSelection(
4713 min(
4714 self.measurement_modes_ba[self.get_instrument_type()].get(
4715 measurement_mode, 1
4716 ),
4717 len(self.measurement_mode_ctrl.GetItems()) - 1,
4718 )
4719 )
4720
4721 def get_measurement_modes(
4722 self,
4723 instrument_name: str,
4724 instrument_type: str,
4725 cfgname: str = "measurement_mode",
4726 ) -> tuple[str, dict, dict, dict]:
4727 """Get the measurement modes for the given instrument.
4728
4729 Args:
4730 instrument_name (str): Name of the instrument.
4731 instrument_type (str): Type of the instrument (e.g., "spect",
4732 "colorimeter").
4733 cfgname (str, optional): Configuration name for the measurement
4734 mode.
4735
4736 Returns:
4737 tuple[str, dict, dict, dict]: A tuple containing two dictionaries:
4738 - `measurement_mode`: A string representing the current
4739 measurement mode.
4740 - `measurement_modes`: A dictionary mapping instrument types to
4741 lists of measurement modes.
4742 - `measurement_modes_ab`: A dictionary mapping instrument types
4743 to lists of abbreviated measurement modes.
4744 - `measurement_modes_ba`: A dictionary mapping measurement
4745 modes to their corresponding indices in the
4746 `measurement_modes` list.
4747 """
4748 measurement_mode = getcfg(cfgname)
4749 # if self.get_instrument_type() == "spect":
4750 # measurement_mode = strtr(measurement_mode, {"c": "", "l": ""})
4751 if instrument_name != "DTP92":
4752 measurement_modes = {
4753 instrument_type: [
4754 lang.getstr("measurement_mode.refresh"),
4755 lang.getstr("measurement_mode.lcd"),
4756 ]
4757 }
4758 measurement_modes_ab = {instrument_type: ["c", "l"]}
4759 else:
4760 measurement_modes = {
4761 instrument_type: [lang.getstr("measurement_mode.refresh")]
4762 }
4763 measurement_modes_ab = {instrument_type: ["c"]}
4764 instrument_features = self.worker.get_instrument_features(instrument_name)
4765 if (
4766 instrument_name in ("Spyder4", "Spyder5")
4767 and self.worker.spyder4_cal_exists()
4768 ):
4769 # Spyder4 Argyll CMS >= 1.3.6
4770 # Spyder5 Argyll CMS >= 1.7.0
4771 # See http://www.argyllcms.com/doc/instruments.html#spyd4
4772 # for description of supported modes
4773 measurement_modes[instrument_type].extend(
4774 [
4775 lang.getstr("measurement_mode.lcd.ccfl"),
4776 lang.getstr("measurement_mode.lcd.wide_gamut.ccfl"),
4777 lang.getstr("measurement_mode.lcd.white_led"),
4778 lang.getstr("measurement_mode.lcd.wide_gamut.rgb_led"),
4779 lang.getstr("measurement_mode.lcd.ccfl.2"),
4780 ]
4781 )
4782 if self.worker.argyll_version >= [1, 5, 0]:
4783 measurement_modes_ab[instrument_type].extend(["f", "L", "e", "B", "x"])
4784 else:
4785 measurement_modes_ab[instrument_type].extend(["3", "4", "5", "6", "7"])
4786 elif instrument_name == "SpyderX":
4787 # Argyll SpyderX modes:
4788 # l General [Default,CB1] (LCD/CCFL)
4789 # e Standard LED (LCD/white LED)
4790 # b Wide Gamut LED (LCD/RGB LED)
4791 # i GB LED (LCD/GB-R Phosphor LED)
4792 measurement_modes[instrument_type] = [
4793 lang.getstr("measurement_mode.generic"),
4794 lang.getstr("measurement_mode.lcd.white_led"),
4795 lang.getstr("measurement_mode.lcd.wide_gamut.led"),
4796 lang.getstr("measurement_mode.lcd.wide_gamut.gb_led"),
4797 ]
4798 measurement_modes_ab[instrument_type] = ["l", "e", "b", "i"]
4799 elif instrument_name == "SpyderX2":
4800 # Argyll SpyderX2 modes: SpyderX plus high brightness
4801 measurement_modes[instrument_type] = [
4802 lang.getstr("measurement_mode.generic"),
4803 lang.getstr("measurement_mode.lcd.white_led"),
4804 lang.getstr("measurement_mode.lcd.wide_gamut.led"),
4805 lang.getstr("measurement_mode.lcd.wide_gamut.gb_led"),
4806 lang.getstr("measurement_mode.lcd.high_brightness", "High brightness"),
4807 ]
4808 measurement_modes_ab[instrument_type] = ["l", "e", "b", "i", "h"]
4809 elif instrument_name == "Spyder 2024":
4810 # Argyll Spyder/SpyderPro 2024 modes: SpyderX2 plus OLED and Mini-LED
4811 measurement_modes[instrument_type] = [
4812 lang.getstr("measurement_mode.generic"),
4813 lang.getstr("measurement_mode.lcd.white_led"),
4814 lang.getstr("measurement_mode.lcd.wide_gamut.led"),
4815 lang.getstr("measurement_mode.lcd.wide_gamut.gb_led"),
4816 lang.getstr("measurement_mode.lcd.high_brightness", "High brightness"),
4817 lang.getstr("measurement_mode.lcd.oled", "OLED"),
4818 lang.getstr("measurement_mode.lcd.mini_led", "Mini-LED"),
4819 ]
4820 measurement_modes_ab[instrument_type] = ["l", "e", "b", "i", "h", "o", "m"]
4821 elif instrument_name in ("ColorHug", "ColorHug2"):
4822 # Argyll CMS 1.3.6, spectro/colorhug.c, colorhug_disptypesel
4823 # Note: projector mode (-yp) is not the same as ColorMunki
4824 # projector mode! (-p)
4825 # ColorHug2 needs Argyll CMS 1.7
4826 measurement_modes[instrument_type].extend(
4827 [
4828 lang.getstr("projector"),
4829 lang.getstr("measurement_mode.lcd.white_led"),
4830 lang.getstr("measurement_mode.factory"),
4831 lang.getstr("measurement_mode.raw"),
4832 lang.getstr("auto"),
4833 ]
4834 )
4835 measurement_modes_ab[instrument_type].extend(["p", "e", "F", "R", "auto"])
4836 elif instrument_name == "DTP94" and self.worker.argyll_version >= [1, 5, 0]:
4837 # Argyll CMS 1.5.x introduces new measurement mode
4838 measurement_modes[instrument_type].extend(
4839 [lang.getstr("measurement_mode.generic")]
4840 )
4841 measurement_modes_ab[instrument_type].append("g")
4842 elif instrument_name == "ColorMunki Smile":
4843 # Only supported in Argyll CMS 1.5.x and newer
4844 measurement_modes[instrument_type] = [
4845 lang.getstr("measurement_mode.lcd.ccfl"),
4846 lang.getstr("measurement_mode.lcd.white_led"),
4847 ]
4848 measurement_modes_ab[instrument_type] = ["f", "e"]
4849 elif instrument_name == "Colorimtre HCFR" and self.worker.argyll_version >= [
4850 1,
4851 5,
4852 0,
4853 ]:
4854 # Argyll CMS 1.5.x introduces new measurement mode
4855 measurement_modes[instrument_type].extend(
4856 [lang.getstr("measurement_mode.raw")]
4857 )
4858 measurement_modes_ab[instrument_type].append("R")
4859 elif instrument_name == "K-10" or not instrument_features:
4860 # K-10 and 'unknown' instruments
4861 measurement_modes[instrument_type] = []
4862 measurement_modes_ab[instrument_type] = []
4863 for mode, desc in self.worker.get_instrument_measurement_modes().items():
4864 measurement_modes[instrument_type].append(lang.getstr(desc))
4865 measurement_modes_ab[instrument_type].append(mode)
4866 if (
4867 instrument_name == "K-10"
4868 and measurement_mode not in measurement_modes_ab[instrument_type]
4869 ):
4870 measurement_mode = "F"
4871 if instrument_features.get("projector_mode") and self.worker.argyll_version >= [
4872 1,
4873 1,
4874 0,
4875 ]:
4876 # Projector mode introduced in Argyll 1.1.0 Beta
4877 measurement_modes[instrument_type].append(lang.getstr("projector"))
4878 measurement_modes_ab[instrument_type].append("p")
4879 if measurement_mode not in measurement_modes_ab[instrument_type]:
4880 if measurement_modes_ab[instrument_type]:
4881 measurement_mode = measurement_modes_ab[instrument_type][0]
4882 else:
4883 measurement_mode = DEFAULTS["measurement_mode"]
4884 if instrument_features.get("adaptive_mode") and (
4885 self.worker.argyll_version[0:3] > [1, 1, 0]
4886 or (
4887 self.worker.argyll_version[0:3] == [1, 1, 0]
4888 and "Beta" not in self.worker.argyll_version_string
4889 and "RC1" not in self.worker.argyll_version_string
4890 and "RC2" not in self.worker.argyll_version_string
4891 )
4892 ):
4893 # Adaptive mode introduced in Argyll 1.1.0 RC3
4894 for key in iter(measurement_modes):
4895 instrument_modes = list(measurement_modes[key])
4896 for i, mode in reversed(
4897 list(zip(list(range(len(instrument_modes))), instrument_modes))
4898 ):
4899 if mode == lang.getstr("default"):
4900 mode = lang.getstr("measurement_mode.adaptive")
4901 else:
4902 mode = "{} {}".format(
4903 mode,
4904 lang.getstr("measurement_mode.adaptive"),
4905 )
4906 measurement_modes[key].insert(i + 1, mode)
4907 modesig = measurement_modes_ab[key][i]
4908 measurement_modes_ab[key].insert(i + 1, (modesig or "") + "V")
4909 if getcfg(f"{cfgname}.adaptive"):
4910 measurement_mode += "V"
4911 if instrument_features.get("highres_mode"):
4912 for key in iter(measurement_modes):
4913 instrument_modes = list(measurement_modes[key])
4914 for i, mode in reversed(
4915 list(zip(list(range(len(instrument_modes))), instrument_modes))
4916 ):
4917 if mode == lang.getstr("default"):
4918 mode = lang.getstr("measurement_mode.highres")
4919 else:
4920 mode = "{} {}".format(
4921 mode, lang.getstr("measurement_mode.highres")
4922 )
4923 measurement_modes[key].insert(i + 1, mode)
4924 modesig = measurement_modes_ab[key][i]
4925 measurement_modes_ab[key].insert(i + 1, (modesig or "") + "H")
4926 if getcfg(f"{cfgname}.highres"):
4927 measurement_mode += "H"
4928 measurement_modes_ab = dict(
4929 list(
4930 zip(
4931 list(measurement_modes_ab.keys()),
4932 [
4933 dict(
4934 list(
4935 zip(
4936 list(range(len(measurement_modes_ab[key]))),
4937 measurement_modes_ab[key],
4938 )
4939 )
4940 )
4941 for key in measurement_modes_ab
4942 ],
4943 )
4944 )
4945 )
4946 measurement_modes_ba = dict(
4947 list(
4948 zip(
4949 list(measurement_modes_ab.keys()),
4950 [
4951 swap_dict_keys_values(measurement_modes_ab[key])
4952 for key in measurement_modes_ab
4953 ],
4954 )
4955 )
4956 )
4957 return (
4958 measurement_mode,
4959 measurement_modes,
4960 measurement_modes_ab,
4961 measurement_modes_ba,
4962 )
4963
4964 def update_measurement_modes(self) -> None:
4965 """Populate the measurement mode control."""
4966 instrument_name = self.worker.get_instrument_name()
4967 instrument_type = self.get_instrument_type()
4968 (
4969 measurement_mode,
4970 measurement_modes,
4971 measurement_modes_ab,
4972 measurement_modes_ba,
4973 ) = self.get_measurement_modes(instrument_name, instrument_type)
4974 self.measurement_modes_ab = measurement_modes_ab
4975 self.measurement_modes_ba = measurement_modes_ba
4976 self.measurement_mode_ctrl.Freeze()
4977 self.measurement_mode_ctrl.SetItems(measurement_modes[instrument_type])
4978 self.measurement_mode_ctrl.SetSelection(
4979 min(
4980 self.measurement_modes_ba[instrument_type].get(measurement_mode, 1),
4981 len(measurement_modes[instrument_type]) - 1,
4982 )
4983 )
4984 measurement_mode = self.get_measurement_mode() or "l"
4985 if measurement_mode != "auto":
4986 measurement_mode = measurement_mode[0]
4987 setcfg("measurement_mode", measurement_mode)
4988 self.measurement_mode_ctrl.Enable(
4989 bool(self.worker.instruments) and bool(measurement_modes[instrument_type])
4990 )
4991 self.measurement_mode_ctrl.Thaw()
4992
4993 def update_colorimeter_correction_matrix_ctrl(self) -> None:
4994 """Show or hide the colorimeter correction matrix controls."""
4995 self.panel.Freeze()
4996 self.update_adjustment_controls()
4997 self.worker.get_instrument_features()
4998 show_control = (
4999 self.worker.instrument_can_use_ccxx(False)
5000 and not is_ccxx_testchart()
5001 and getcfg("measurement_mode") != "auto"
5002 )
5003 self.colorimeter_correction_matrix_ctrl.GetContainingSizer().Show(
5004 self.colorimeter_correction_matrix_ctrl, show_control
5005 )
5006 self.colorimeter_correction_info_btn.GetContainingSizer().Show(
5007 self.colorimeter_correction_info_btn, show_control
5008 )
5009 self.colorimeter_correction_matrix_label.GetContainingSizer().Show(
5010 self.colorimeter_correction_matrix_label, show_control
5011 )
5012 self.colorimeter_correction_matrix_btn.GetContainingSizer().Show(
5013 self.colorimeter_correction_matrix_btn, show_control
5014 )
5015 self.colorimeter_correction_web_btn.GetContainingSizer().Show(
5016 self.colorimeter_correction_web_btn, show_control
5017 )
5018 self.colorimeter_correction_create_btn.ContainingSizer.Show(
5019 self.colorimeter_correction_create_btn, show_control
5020 )
5021 self.calpanel.Layout()
5022 self.panel.Thaw()
5023 if self.IsShown():
5024 wx.CallAfter(self.set_size, True)
5025 wx.CallLater(1, self.update_scrollbars)
5026
5027 def delete_colorimeter_correction_matrix_ctrl_item(self, path: str) -> None:
5028 """Delete a colorimeter correction matrix control item.
5029
5030 Args:
5031 path (str): Path to the CCMX/CCSS file to delete.
5032 """
5033 if path in self.ccmx_cached_paths:
5034 self.ccmx_cached_paths.remove(path)
5035 if path in self.ccmx_cached_descriptors:
5036 del self.ccmx_cached_descriptors[path]
5037 if path in self.ccmx_instruments:
5038 del self.ccmx_instruments[path]
5039 delete = False
5040 key = None
5041 for _key in self.ccmx_mapping:
5042 value = self.ccmx_mapping[_key]
5043 if value == path:
5044 delete = True
5045 key = _key
5046 break
5047 if delete:
5048 del self.ccmx_mapping[key]
5049
5050 def update_colorimeter_correction_matrix_ctrl_items(
5051 self,
5052 force: bool = False,
5053 warn_on_mismatch: bool = False,
5054 update_measurement_mode: bool = True,
5055 ) -> None:
5056 """Show selected correction matrix and list all ccmx/ccss files.
5057
5058 Args:
5059 force (bool, optional): If True, reads the ccmx directory again,
5060 otherwise uses a previously cached result if available
5061 warn_on_mismatch (bool, optional): If True, warns the user if the
5062 selected CCMX does not match the instrument or display type.
5063 update_measurement_mode (bool, optional): If True, updates the
5064 measurement mode control after updating the CCMX items.
5065 """
5066 items = [lang.getstr("colorimeter_correction.file.none"), lang.getstr("auto")]
5067 self.ccmx_item_paths = []
5068 index = 0
5069 ccxx_path = None
5070 ccmx = getcfg("colorimeter_correction_matrix_file").split(":", 1)
5071
5072 if len(ccmx) > 1 and not os.path.isfile(ccmx[1]):
5073 ccmx = ccmx[:1]
5074
5075 if force or not getattr(self, "ccmx_cached_paths", None):
5076 ccmx_paths = self.get_argyll_data_files("lu", "*.ccmx")
5077 ccss_paths = self.get_argyll_data_files("lu", "*.ccss")
5078 # Filter out files with known identical spectra
5079 # Key is the preferred CCSS, value is the one to be ignored
5080 # If key is same as value, remove from paths completely
5081 mapping = {
5082 "Dell_U2413_25Jul12.ccss": "GBrLED_25Jul12.ccss", # HCFR
5083 "necpa242w_full.ccss": "necpa242w_full.ccss", # HCFR
5084 # necpa242w_full.ccss is bad - not done with native primaries
5085 "Panasonic VVX17P051J00.ccss": "PanasonicVVX17P051J00.ccss",
5086 }
5087 imapping = {}
5088 for path in ccss_paths:
5089 basename = os.path.basename(path)
5090 if basename in mapping:
5091 imapping[mapping[basename]] = path
5092 if imapping:
5093 discard_paths = []
5094 for path in ccss_paths:
5095 basename = os.path.basename(path)
5096 if basename in imapping:
5097 if basename in mapping:
5098 print("Ignoring", path)
5099 else:
5100 print("Ignoring", path, "in favor of", imapping[basename])
5101 discard_paths.append(path)
5102 if discard_paths:
5103 ccss_paths = [
5104 path for path in ccss_paths if path not in discard_paths
5105 ]
5106 ccmx_paths.sort(key=os.path.basename)
5107 ccss_paths.sort(key=os.path.basename)
5108 self.ccmx_cached_paths = ccmx_paths + ccss_paths
5109 self.ccmx_cached_descriptors = {}
5110 self.ccmx_instruments = {}
5111 self.ccmx_mapping = {}
5112 types = {
5113 "ccss": lang.getstr("spectral").replace(":", ""),
5114 "ccmx": lang.getstr("matrix").replace(":", ""),
5115 }
5116 add_basename_to_desc_on_mismatch = False
5117 malformed_ccxx = []
5118 for _i, path in enumerate(self.ccmx_cached_paths):
5119 filename, ext = os.path.splitext(path)
5120 lstr = ext[1:] + "." + os.path.basename(filename)
5121 desc = lang.getstr(lstr)
5122 if self.ccmx_cached_descriptors.get(path):
5123 if desc == lstr:
5124 desc = self.ccmx_cached_descriptors[path]
5125 elif os.path.isfile(path):
5126 try:
5127 cgats = CGATS(path, strict=True)
5128 except (OSError, CGATSError) as exception:
5129 print(exception)
5130 if isinstance(exception, CGATSInvalidError):
5131 malformed_ccxx.append(path)
5132 continue
5133 if desc == lstr:
5134 desc = cgats.get_descriptor() # this is bytes
5135 desc = desc.decode("utf-8", "replace")
5136 # If the description is not the same as the 'sane'
5137 # filename, add the filename after the description
5138 # (max 31 chars)
5139 # See also colorimeter_correction_check_overwrite, the
5140 # way the filename is processed must be the same
5141 if (
5142 add_basename_to_desc_on_mismatch
5143 and make_argyll_compatible_path(desc, is_name=True)
5144 != os.path.splitext(os.path.basename(path))[0]
5145 ):
5146 desc = "{} <{}>".format(
5147 ellipsis_(desc, 66, "m"),
5148 ellipsis_(os.path.basename(path), 31, "m"),
5149 )
5150 else:
5151 desc = ellipsis_(desc, 100, "m")
5152 self.ccmx_cached_descriptors[path] = desc
5153 # get_canonical_instrument_name: returns bytes
5154 self.ccmx_instruments[path] = get_canonical_instrument_name(
5155 cgats.queryv1("INSTRUMENT") or b"",
5156 {
5157 "DTP94-LCD mode": "DTP94",
5158 "eye-one display": "i1 Display",
5159 "Spyder 2 LCD": "Spyder2",
5160 "Spyder 3": "Spyder3",
5161 },
5162 ).decode("utf-8")
5163 key = "{}\0{}".format(
5164 self.ccmx_instruments[path],
5165 (cgats.queryv1("DISPLAY") or b"").decode("utf-8"),
5166 )
5167 if not self.ccmx_mapping.get(key) or (
5168 len(ccmx) > 1 and path == ccmx[1]
5169 ):
5170 # Prefer the selected CCMX
5171 self.ccmx_mapping[key] = path
5172 else:
5173 continue
5174
5175 instrument_name = self.worker.get_instrument_name()
5176 if instrument_name.lower().replace(" ", "") in self.ccmx_instruments.get(
5177 path, ""
5178 ).lower().replace(" ", "") or (
5179 path.lower().endswith(".ccss")
5180 and self.worker.instrument_supports_ccss()
5181 ):
5182 # Only add the correction to the list if it matches the
5183 # currently selected instrument or if it is a CCSS
5184 if len(ccmx) > 1 and ccmx[0] != "AUTO" and ccmx[1] == path:
5185 ccxx_path = path
5186
5187 item_text = "{}: {}".format(
5188 types.get(os.path.splitext(path)[1].lower()[1:]),
5189 desc if isinstance(desc, str) else desc.decode("utf-8", "replace"),
5190 )
5191 items.append(item_text)
5192 self.ccmx_item_paths.append(path)
5193 items_paths = []
5194 for i, item in enumerate(items[2:]):
5195 items_paths.append({"item": item, "path": self.ccmx_item_paths[i]})
5196 items_paths.sort(key=lambda item_path: item_path["item"].lower())
5197 for i, item_path in enumerate(items_paths):
5198 items[i + 2] = item_path["item"]
5199 self.ccmx_item_paths[i] = item_path["path"]
5200 if ccxx_path:
5201 index = self.ccmx_item_paths.index(ccxx_path) + 2
5202 add_cfg_ccxx = False
5203 cgats = None
5204 if (
5205 len(ccmx) > 1
5206 and ccmx[1]
5207 and ccmx[1] not in self.ccmx_cached_paths
5208 and (
5209 not ccmx[1].lower().endswith(".ccss")
5210 or self.worker.instrument_supports_ccss()
5211 )
5212 ):
5213 # Add currently configured CCXX to list? Check if same file in list
5214 add_cfg_ccxx = True
5215 for i, path in enumerate(self.ccmx_item_paths):
5216 if os.path.basename(path) == os.path.basename(ccmx[1]):
5217 try:
5218 ccxx = CGATS(path)
5219 ccxx[0].DATA.vmaxlen = 5 # Allow margin of error
5220 except Exception as exception:
5221 print(exception)
5222 break
5223 try:
5224 cgats = CGATS(ccmx[1], strict=True)
5225 vmaxlen = cgats[0].DATA.vmaxlen
5226 cgats[0].DATA.vmaxlen = 5 # Allow margin of error
5227 except Exception as exception:
5228 show_ccxx_error_dialog(exception, ccmx[1], self)
5229 add_cfg_ccxx = False
5230 ccmx = [""]
5231 else:
5232 if str(cgats) == str(ccxx):
5233 # Same, use existing entry
5234 print(ccmx[1], "matches", path, "- using the latter")
5235 add_cfg_ccxx = False
5236 ccmx[1] = path
5237 index = i + 2
5238 else:
5239 print(ccmx[1], "does not match", path, "- using the former")
5240 cgats[0].DATA.vmaxlen = vmaxlen
5241 break
5242 if add_cfg_ccxx:
5243 desc = self.ccmx_cached_descriptors.get(ccmx[1])
5244 if not desc and os.path.isfile(ccmx[1]):
5245 try:
5246 if not cgats:
5247 cgats = CGATS(ccmx[1], strict=True)
5248 except (OSError, CGATSError) as exception:
5249 if isinstance(exception, CGATSInvalidError) and ccmx[
5250 1
5251 ] in self.get_argyll_data_files(
5252 "lu", "*" + os.path.splitext(ccmx[1])[1]
5253 ):
5254 malformed_ccxx.append(ccmx[1])
5255 show_ccxx_error_dialog(exception, ccmx[1], self)
5256 ccmx = [""]
5257 else:
5258 self.ccmx_cached_paths.insert(0, ccmx[1])
5259 desc = cgats.get_descriptor()
5260 # If the description is not the same as the 'sane'
5261 # filename, add the filename after the description
5262 # (max 31 chars)
5263 # See also colorimeter_correction_check_overwite, the
5264 # way the filename is processed must be the same
5265 if (
5266 add_basename_to_desc_on_mismatch
5267 and make_argyll_compatible_path(desc, is_name=True)
5268 != os.path.splitext(os.path.basename(ccmx[1]))[0]
5269 ):
5270 desc = "{} <{}>".format(
5271 ellipsis_(desc, 66, "m"),
5272 ellipsis_(os.path.basename(ccmx[1]), 31, "m"),
5273 )
5274 else:
5275 desc = ellipsis_(desc, 100, "m")
5276 self.ccmx_cached_descriptors[ccmx[1]] = desc
5277 self.ccmx_instruments[ccmx[1]] = get_canonical_instrument_name(
5278 cgats.queryv1("INSTRUMENT") or b"",
5279 {
5280 "DTP94-LCD mode": "DTP94",
5281 "eye-one display": "i1 Display",
5282 "Spyder 2 LCD": "Spyder2",
5283 "Spyder 3": "Spyder3",
5284 },
5285 ).decode("utf-8")
5286 key = "{}\0{}".format(
5287 self.ccmx_instruments[ccmx[1]],
5288 (cgats.queryv1("DISPLAY") or b"").decode("utf-8"),
5289 )
5290 self.ccmx_mapping[key] = ccmx[1]
5291 if desc and (
5292 self.worker.get_instrument_name().lower().replace(" ", "")
5293 in self.ccmx_instruments.get(ccmx[1], "").lower().replace(" ", "")
5294 or ccmx[1].lower().endswith(".ccss")
5295 ):
5296 # Only add the correction to the list if it matches the
5297 # currently selected instrument or if it is a CCSS
5298 items.insert(
5299 2,
5300 "{}: {}".format(
5301 types.get(os.path.splitext(ccmx[1])[1].lower()[1:]),
5302 desc
5303 if isinstance(desc, str)
5304 else desc.decode("utf-8", "replace"),
5305 ),
5306 )
5307 self.ccmx_item_paths.insert(0, ccmx[1])
5308 if ccmx[0] != "AUTO":
5309 index = 2
5310 if ccmx[0] == "AUTO":
5311 if len(ccmx) < 2:
5312 ccmx.append("")
5313 display_name = self.worker.get_display_name(False, True, False)
5314 if self.worker.instrument_supports_ccss():
5315 # Prefer CCSS
5316 ccmx[1] = self.ccmx_mapping.get(f"\0{display_name}", "")
5317 if not self.worker.instrument_supports_ccss() or not ccmx[1]:
5318 instrument_name = self.worker.get_instrument_name()
5319 print(f"instrument_name: {instrument_name}")
5320 print(f"display_name : {display_name}")
5321 ccmx[1] = self.ccmx_mapping.get(
5322 f"{instrument_name}\0{display_name}", ""
5323 )
5324 cgats = None
5325 elif not ccmx[0] and len(ccmx) < 2:
5326 current_index = self.colorimeter_correction_matrix_ctrl.Selection
5327 if -1 < current_index - 2 < len(self.ccmx_item_paths):
5328 index = current_index
5329 ccmx.append(self.ccmx_item_paths[current_index - 2])
5330 if (
5331 self.worker.instrument_can_use_ccxx()
5332 and len(ccmx) > 1
5333 and ccmx[1]
5334 and ccmx[1] not in self.ccmx_item_paths
5335 ):
5336 # CCMX does not match the currently selected instrument,
5337 # don't use
5338 msg = lang.getstr("colorimeter_correction.instrument_mismatch")
5339 if warn_on_mismatch:
5340 show_result_dialog(Warn(msg), self)
5341 else:
5342 print(msg, ccmx[1])
5343 ccmx = [""]
5344 elif ccmx[0] == "AUTO":
5345 index = 1
5346 if ccmx[1]:
5347 ccmx_desc = self.ccmx_cached_descriptors[ccmx[1]]
5348 items[1] += " ({}: {})".format(
5349 types.get(os.path.splitext(ccmx[1])[1].lower()[1:]),
5350 (
5351 ccmx_desc
5352 if isinstance(ccmx_desc, str)
5353 else ccmx_desc.decode("utf-8", "replace")
5354 ),
5355 )
5356 else:
5357 items[1] += " ({})".format(
5358 lang.getstr("colorimeter_correction.file.none")
5359 )
5360 use_ccmx = (
5361 self.worker.instrument_can_use_ccxx(False) and len(ccmx) > 1 and ccmx[1]
5362 )
5363 tech = None
5364 observer = None
5365 if use_ccmx:
5366 mode = None
5367 try:
5368 if not cgats:
5369 cgats = CGATS(ccmx[1], strict=True)
5370 except (OSError, CGATSError) as exception:
5371 show_ccxx_error_dialog(exception, ccmx[1], self)
5372 ccmx = ["", ""]
5373 index = 0
5374 else:
5375 if getcfg("measurement_mode") != "auto":
5376 tech = cgats.queryv1("TECHNOLOGY")
5377 # Set appropriate measurement mode
5378 # IMPORTANT: Make changes aswell in the following locations:
5379 # - DisplayCAL.get_cgats_measurement_mode
5380 mode = get_cgats_measurement_mode(
5381 cgats, self.worker.get_instrument_name()
5382 )
5383 observer = cgats.queryv1("OBSERVER")
5384 if observer in self.observers_ab:
5385 setcfg("observer", observer)
5386 self.update_observer_ctrl()
5387 self.observer_ctrl.Disable()
5388 if mode or (
5389 getcfg("measurement_mode") != "auto"
5390 and not self.worker.instrument_can_use_ccxx()
5391 ):
5392 if update_measurement_mode or mode == getcfg("measurement_mode"):
5393 setcfg("measurement_mode", mode)
5394 self.update_measurement_mode()
5395 else:
5396 ccmx = ["", ""]
5397 index = 0
5398 tech = None
5399 if tech is None:
5400 tech = self.worker.get_instrument_measurement_modes().get(
5401 getcfg("measurement_mode")
5402 )
5403 setcfg("display.technology", tech)
5404 setcfg("colorimeter_correction_matrix_file", ":".join(ccmx))
5405 self.colorimeter_correction_matrix_ctrl.Freeze()
5406 self.colorimeter_correction_matrix_ctrl.SetItems(items)
5407 self.colorimeter_correction_matrix_ctrl.SetSelection(index)
5408 self.colorimeter_correction_matrix_ctrl.Thaw()
5409 tooltip = ccmx[1] if use_ccmx else ""
5410 self.update_main_controls()
5411 self.colorimeter_correction_matrix_ctrl.SetToolTipString(tooltip)
5412 self.colorimeter_correction_info_btn.Enable(len(ccmx) > 1 and bool(ccmx[1]))
5413 self.update_estimated_measurement_times()
5414 if observer not in self.observers_ab:
5415 self.observer_ctrl.Enable()
5416 self.show_observer_ctrl()
5417 if malformed_ccxx:
5418 show_result_dialog(
5419 Warn(
5420 lang.getstr("argyll.malformed_ccxx")
5421 + "\n\n"
5422 + "\n".join(malformed_ccxx)
5423 ),
5424 (self.Shown and self) or None,
5425 )
5426 msg = None
5427 if sys.platform == "darwin":
5428 trashcan = lang.getstr("trashcan.mac")
5429 elif sys.platform == "win32":
5430 trashcan = lang.getstr("trashcan.windows")
5431 else:
5432 trashcan = lang.getstr("trashcan.linux")
5433 try:
5434 send2trash(malformed_ccxx)
5435 except OSError as exc:
5436 msg = lang.getstr("error.deletion", trashcan) + "\n\n" + str(exc)
5437 else:
5438 orphans = [
5439 orphan for orphan in malformed_ccxx if os.path.exists(orphan)
5440 ]
5441 if orphans:
5442 msg = (
5443 lang.getstr("error.deletion", trashcan)
5444 + "\n\n"
5445 + "\n".join(orphans)
5446 )
5447 if msg:
5448 show_result_dialog(msg, (self.Shown and self) or None)
5449 elif not add_cfg_ccxx:
5450 # Need to refresh displays & instruments
5451 self.Bind(wx.EVT_SHOW, self.check_update_controls_once)
5452
5453 def check_update_controls_once(self, event: wx.Event) -> None:
5454 """Check if controls need to be updated once after the panel is shown.
5455
5456 Args:
5457 event (wx.Event): The event that triggered this method.
5458 """
5459 if not hasattr(self, "_check_update_controls_once"):
5460 self._check_update_controls_once = True
5461 wx.CallAfter(self.check_update_controls, event)
5462
5463 def update_main_controls(self) -> None:
5464 """Enable/disable calibrate/profile buttons based on Argyll functionality."""
5465 self.panel.Freeze()
5466
5467 is_profile_ = is_profile()
5468
5469 cal = getcfg("calibration.file", False)
5470 self.install_profile_btn.Enable(
5471 bool(self.worker.displays) and is_profile_ and cal not in self.presets
5472 )
5473
5474 update_cal = self.calibration_update_cb.GetValue()
5475
5476 self.measurement_mode_ctrl.Enable(
5477 bool(self.worker.instruments)
5478 and len(self.measurement_mode_ctrl.GetItems()) > 1
5479 )
5480
5481 update_profile = update_cal and is_profile_
5482
5483 self.visual_whitepoint_editor_btn.Enable(
5484 bool(self.worker.displays)
5485 and bool(self.worker.instruments)
5486 and not update_cal
5487 )
5488 self.whitepoint_measure_btn.Enable(
5489 bool(self.worker.instruments) and not update_cal
5490 )
5491 self.ambient_measure_btn.Enable(
5492 bool(self.worker.instruments) and not update_cal
5493 )
5494 self.luminance_measure_btn.Enable(
5495 bool(self.worker.instruments) and not update_cal
5496 )
5497 self.ambient_luminance_measure_btn.Enable(
5498 bool(self.worker.instruments) and not update_cal
5499 )
5500 self.black_luminance_measure_btn.Enable(
5501 bool(self.worker.instruments) and not update_cal
5502 )
5503
5504 lut3d_create_btn_show = self.lut3d_settings_panel.IsShown() and not getcfg(
5505 "3dlut.create"
5506 )
5507 mr_btn_show = self.mr_settings_panel.IsShown()
5508 enable_cal = not config.is_uncalibratable_display() and (
5509 self.interactive_display_adjustment_cb.GetValue()
5510 or self.trc_ctrl.GetSelection() > 0
5511 )
5512 calibrate_and_profile_btn_show = (
5513 not lut3d_create_btn_show
5514 and not mr_btn_show
5515 and enable_cal
5516 and not update_profile
5517 )
5518 calibrate_btn_show = (
5519 not lut3d_create_btn_show and not mr_btn_show and enable_cal
5520 )
5521 profile_btn_show = (
5522 not lut3d_create_btn_show
5523 and not mr_btn_show
5524 and not calibrate_and_profile_btn_show
5525 and not update_cal
5526 )
5527 if (
5528 config.is_uncalibratable_display()
5529 and self.calibration_settings_panel.IsShown()
5530 ) or (not getcfg("3dlut.tab.enable") and self.lut3d_settings_panel.IsShown()):
5531 self.tab_select_handler(self.display_instrument_btn)
5532 if (
5533 config.is_uncalibratable_display()
5534 and not self.calibration_settings_btn.IsEnabled()
5535 ):
5536 self.calibration_settings_btn._pressed = False
5537 self.calibration_settings_btn._SetState(platebtn.PLATE_NORMAL)
5538 self.calibration_settings_btn.Enable(not config.is_uncalibratable_display())
5539 self.lut3d_settings_btn.Enable(bool(getcfg("3dlut.tab.enable")))
5540 self.calibrate_btn.Show(
5541 not calibrate_and_profile_btn_show and calibrate_btn_show
5542 )
5543 self.calibrate_btn.Enable(
5544 not calibrate_and_profile_btn_show
5545 and calibrate_btn_show
5546 and not is_ccxx_testchart()
5547 and bool(self.worker.displays)
5548 and bool(self.worker.instruments)
5549 )
5550 self.calibrate_and_profile_btn.Show(calibrate_and_profile_btn_show)
5551 self.calibrate_and_profile_btn.Enable(
5552 calibrate_and_profile_btn_show
5553 and not is_ccxx_testchart()
5554 and bool(self.worker.displays)
5555 and bool(self.worker.instruments)
5556 )
5557 self.profile_btn.Show(profile_btn_show)
5558 self.profile_btn.Enable(
5559 profile_btn_show
5560 and bool(self.worker.displays)
5561 and bool(self.worker.instruments)
5562 )
5563 self.lut3d_create_btn.Show(lut3d_create_btn_show)
5564 self.measurement_report_btn.Show(mr_btn_show)
5565 self.buttonpanel.Layout()
5566
5567 self.lut3d_create_btn.Enable(
5568 is_profile() and getcfg("calibration.file", False) not in self.presets
5569 )
5570
5571 self.panel.Layout()
5572 self.panel.Thaw()
5573
5574 def update_calibration_file_ctrl(
5575 self, silent: bool = False
5576 ) -> tuple[str, str, str, bool]:
5577 """Update calibration file control items and tooltip for the selected file.
5578
5579 Returns:
5580 tuple[str, str, str, bool]: A tuple containing:
5581 - The selected calibration file path.
5582 - The filename without extension.
5583 - The profile path (filename with .icc or .icm extension).
5584 - A boolean indicating if the profile exists.
5585 """
5586 cal = getcfg("calibration.file", False)
5587
5588 if cal:
5589 result = check_file_isfile(cal, silent=silent)
5590 if isinstance(result, Exception) and not silent:
5591 show_result_dialog(result, self)
5592 else:
5593 result = False
5594 if not isinstance(result, Exception) and result:
5595 filename, ext = os.path.splitext(cal)
5596 if cal not in self.recent_cals:
5597 self.recent_cals.append(cal)
5598 recent_cals = self.get_unpreseted_recent_calibrations()
5599 setcfg("recent_cals", os.pathsep.join(recent_cals))
5600 self.calibration_file_ctrl.Append(lang.getstr(os.path.basename(cal)))
5601 # The case-sensitive index could fail because of
5602 # case insensitive file systems, e.g. if the
5603 # stored filename string is
5604 # "C:\Users\Name\AppData\DisplayCAL\storage\MyFile"
5605 # but the actual filename is
5606 # "C:\Users\Name\AppData\DisplayCAL\storage\myfile"
5607 # (maybe because the user renamed the file)
5608 idx = index_fallback_ignorecase(self.recent_cals, cal)
5609 self.calibration_file_ctrl.SetSelection(idx)
5610 self.calibration_file_ctrl.SetToolTipString(cal)
5611 if ext.lower() in ICCPROFILE_FILE_EXTENSIONS:
5612 profile_path = cal
5613 else:
5614 profile_path = filename + PROFILE_EXT
5615 profile_exists = os.path.exists(profile_path)
5616 else:
5617 filename = None
5618 if cal in self.recent_cals[1:]:
5619 # The case-sensitive index could fail because of
5620 # case insensitive file systems, e.g. if the
5621 # stored filename string is
5622 # "C:\Users\Name\AppData\DisplayCAL\storage\MyFile"
5623 # but the actual filename is
5624 # "C:\Users\Name\AppData\DisplayCAL\storage\myfile"
5625 # (maybe because the user renamed the file)
5626 idx = index_fallback_ignorecase(self.recent_cals, cal)
5627 self.recent_cals.remove(cal)
5628 self.calibration_file_ctrl.Delete(idx)
5629 cal = None
5630 self.calibration_file_ctrl.SetStringSelection(lang.getstr("settings.new"))
5631 self.calibration_file_ctrl.SetToolTip(None)
5632 setcfg("calibration.file", None)
5633 setcfg("calibration.update", 0)
5634 profile_path = None
5635 profile_exists = False
5636
5637 return cal, filename, profile_path, profile_exists
5638
5639 def get_unpreseted_recent_calibrations(self) -> list:
5640 """Return recent calibrations that are not presets.
5641
5642 Returns:
5643 list: List of recent calibration file paths that are not presets.
5644 """
5645 return [
5646 recent_cal
5647 for recent_cal in self.recent_cals
5648 if recent_cal not in self.presets
5649 ]
5650
5651 def update_controls(
5652 self,
5653 update_profile_name: bool = True,
5654 update_ccmx_items: bool = True,
5655 silent: bool = False,
5656 ) -> None:
5657 """Update controls based on configuration and Argyll functionality.
5658
5659 Args:
5660 update_profile_name (bool, optional): If True, updates the profile
5661 name control.
5662 update_ccmx_items (bool, optional): If True, updates the
5663 colorimeter correction matrix control items.
5664 silent (bool, optional): If True, suppresses error dialogs.
5665 """
5666 self.updatingctrls = True
5667
5668 self.panel.Freeze()
5669
5670 (
5671 cal,
5672 filename,
5673 profile_path,
5674 profile_exists,
5675 ) = self.update_calibration_file_ctrl(silent)
5676 self.create_session_archive_btn.Enable(bool(cal) and cal not in self.presets)
5677 self.delete_calibration_btn.Enable(bool(cal) and cal not in self.presets)
5678 is_profile_ = is_profile(include_display_profile=True)
5679 self.profile_info_btn.Enable(is_profile_)
5680 enable_update = (
5681 bool(cal)
5682 and os.path.exists(filename + ".cal")
5683 and can_update_cal(filename + ".cal")
5684 )
5685 if not enable_update:
5686 setcfg("calibration.update", 0)
5687 update_cal = getcfg("calibration.update")
5688 self.calibration_update_cb.Enable(enable_update)
5689 self.calibration_update_cb.SetValue(bool(update_cal))
5690
5691 if not update_cal or not profile_exists:
5692 setcfg("profile.update", 0)
5693
5694 update_profile = update_cal and profile_exists
5695 enable_profile = not update_profile
5696
5697 if update_ccmx_items:
5698 self.update_colorimeter_correction_matrix_ctrl_items()
5699
5700 self.update_measurement_mode()
5701
5702 self.update_observer_ctrl()
5703
5704 for name in ("min_display_update_delay_ms", "display_settle_time_mult"):
5705 value = bool(getcfg(f"measure.override_{name}"))
5706 getattr(self, f"override_{name}").SetValue(value)
5707 self.update_display_delay_ctrl(name, value)
5708
5709 self.update_ffp_insertion_ctrl()
5710 self.ffp_insertion_interval.SetValue(
5711 getcfg("patterngenerator.ffp_insertion.interval")
5712 )
5713 self.ffp_insertion_duration.SetValue(
5714 getcfg("patterngenerator.ffp_insertion.duration")
5715 )
5716 self.ffp_insertion_level.SetValue(
5717 int(getcfg("patterngenerator.ffp_insertion.level") * 100)
5718 )
5719
5720 self.update_adjustment_controls()
5721 self.whitepoint_colortemp_textctrl.Enable(not update_cal)
5722 self.whitepoint_colortemp_locus_ctrl.Enable(not update_cal)
5723 self.whitepoint_x_textctrl.Enable(not update_cal)
5724 self.whitepoint_y_textctrl.Enable(not update_cal)
5725 self.luminance_textctrl.Enable(not update_cal)
5726 self.black_luminance_textctrl.Enable(not update_cal)
5727 self.trc_ctrl.Enable(not update_cal)
5728 self.trc_textctrl.Enable(not update_cal)
5729 self.trc_type_ctrl.Enable(not update_cal)
5730 self.ambient_viewcond_adjust_cb.Enable(not update_cal)
5731 self.black_output_offset_ctrl.Enable(not update_cal)
5732 self.black_output_offset_intctrl.Enable(not update_cal)
5733 self.black_point_correction_auto_cb.Enable(not update_cal)
5734 self.black_point_correction_ctrl.Enable(not update_cal)
5735 self.black_point_correction_intctrl.Enable(not update_cal)
5736 self.update_black_point_rate_ctrl()
5737 self.update_drift_compensation_ctrls()
5738
5739 self.testchart_btn.Enable(enable_profile)
5740 self.testchart_patches_amount_ctrl.Enable(enable_profile)
5741 self.create_testchart_btn.Enable(enable_profile)
5742 self.profile_type_ctrl.Enable(enable_profile)
5743
5744 self.whitepoint_colortemp_locus_ctrl.SetSelection(
5745 self.whitepoint_colortemp_loci_ba.get(
5746 getcfg("whitepoint.colortemp.locus"),
5747 self.whitepoint_colortemp_loci_ba.get(
5748 DEFAULTS["whitepoint.colortemp.locus"]
5749 ),
5750 )
5751 )
5752
5753 self.whitelevel_drift_compensation.SetValue(
5754 bool(getcfg("drift_compensation.whitelevel"))
5755 )
5756
5757 self.blacklevel_drift_compensation.SetValue(
5758 bool(getcfg("drift_compensation.blacklevel"))
5759 )
5760
5761 trc = getcfg("trc")
5762 bt1886 = (
5763 trc == 2.4
5764 and getcfg("trc.type") == "G"
5765 and getcfg("calibration.black_output_offset") == 0
5766 )
5767 if trc in ("l", "709", "240", "s"):
5768 self.trc_type_ctrl.SetSelection(0)
5769 if trc == "l":
5770 self.trc_ctrl.SetSelection(2)
5771 elif trc == "709":
5772 self.trc_ctrl.SetSelection(3)
5773 elif trc == "240":
5774 self.trc_ctrl.SetSelection(5)
5775 elif trc == "s":
5776 self.trc_ctrl.SetSelection(6)
5777 elif bt1886:
5778 self.trc_ctrl.SetSelection(4)
5779 self.trc_textctrl.SetValue(str(trc))
5780 self.trc_type_ctrl.SetSelection(1)
5781 else:
5782 if trc:
5783 if (
5784 trc == 2.2
5785 and getcfg("trc.type") == "g"
5786 and getcfg("calibration.black_output_offset") == 1
5787 ):
5788 # Gamma 2.2 relative 100% output offset
5789 self.trc_ctrl.SetSelection(1)
5790 else:
5791 # Custom
5792 self.trc_ctrl.SetSelection(7)
5793 self.trc_textctrl.SetValue(str(trc))
5794 else:
5795 self.trc_ctrl.SetSelection(0)
5796 self.trc_type_ctrl.SetSelection(
5797 self.trc_types_ba.get(
5798 getcfg("trc.type"), self.trc_types_ba.get(DEFAULTS["trc.type"])
5799 )
5800 )
5801 self.show_trc_controls()
5802
5803 self.ambient_viewcond_adjust_cb.SetValue(
5804 bool(int(getcfg("calibration.ambient_viewcond_adjust")))
5805 )
5806 self.ambient_viewcond_adjust_textctrl.SetValue(
5807 getcfg("calibration.ambient_viewcond_adjust.lux")
5808 )
5809 self.ambient_viewcond_adjust_textctrl.Enable(
5810 not update_cal and bool(int(getcfg("calibration.ambient_viewcond_adjust")))
5811 )
5812
5813 self.update_profile_type_ctrl()
5814
5815 self.update_black_output_offset_ctrl()
5816
5817 self.black_point_correction_ctrl.SetValue(
5818 int(Decimal(str(getcfg("calibration.black_point_correction"))) * 100)
5819 )
5820 self.black_point_correction_intctrl.SetValue(
5821 int(Decimal(str(getcfg("calibration.black_point_correction"))) * 100)
5822 )
5823
5824 self.black_point_rate_ctrl.SetValue(
5825 int(Decimal(str(getcfg("calibration.black_point_rate"))) * 100)
5826 )
5827 self.black_point_rate_floatctrl.SetValue(getcfg("calibration.black_point_rate"))
5828
5829 q = self.quality_ba.get(
5830 getcfg("calibration.quality"),
5831 self.quality_ba.get(DEFAULTS["calibration.quality"]),
5832 )
5833 self.calibration_quality_ctrl.SetValue(q)
5834 self.set_calibration_quality_label(self.quality_ab[q])
5835
5836 self.update_bpc(enable_profile)
5837
5838 self.testchart_ctrl.Enable(enable_profile)
5839 if self.set_default_testchart() is None:
5840 self.set_testchart(update_profile_name=not update_profile_name)
5841
5842 self.testchart_patch_sequence_ctrl.SetStringSelection(
5843 lang.getstr("testchart." + getcfg("testchart.patch_sequence"))
5844 )
5845
5846 simple_gamma_model = self.get_profile_type() in ("g", "G")
5847 if simple_gamma_model:
5848 q = 3
5849 else:
5850 q = (
5851 self.quality_ba.get(
5852 getcfg("profile.quality"),
5853 self.quality_ba.get(DEFAULTS["profile.quality"]),
5854 )
5855 - 1
5856 )
5857 self.profile_quality_ctrl.SetValue(q)
5858 if q == 1:
5859 self.profile_quality_info.SetLabel(lang.getstr("calibration.quality.low"))
5860 elif q == 2:
5861 self.profile_quality_info.SetLabel(
5862 lang.getstr("calibration.quality.medium")
5863 )
5864 elif q == 3:
5865 self.profile_quality_info.SetLabel(lang.getstr("calibration.quality.high"))
5866 elif q == 4:
5867 self.profile_quality_info.SetLabel(lang.getstr("calibration.quality.ultra"))
5868 self.profile_quality_ctrl.Enable(enable_profile and not simple_gamma_model)
5869
5870 enable_gamap = self.get_profile_type() in ("l", "x", "X")
5871 self.gamap_btn.Enable(enable_profile and enable_gamap)
5872
5873 if getattr(self, "extra_args", None):
5874 self.extra_args.update_controls()
5875
5876 if hasattr(self, "gamapframe"):
5877 self.gamapframe.update_controls()
5878
5879 self.mr_set_filebrowse_paths()
5880
5881 if self.lut3d_settings_panel.IsShown() or self.mr_settings_panel.IsShown():
5882 if self.mr_settings_panel.IsShown():
5883 self.mr_update_controls(False)
5884 else:
5885 self.set_profile("output")
5886
5887 self.lut3d_update_controls()
5888 if getattr(self, "lut3dframe", None):
5889 self.lut3dframe.update_controls()
5890
5891 if getattr(self, "reportframe", None):
5892 self.reportframe.update_controls()
5893
5894 if update_profile_name:
5895 self.profile_name_textctrl.ChangeValue(getcfg("profile.name"))
5896 self.update_profile_name()
5897
5898 self.update_main_controls()
5899 self.panel.Thaw()
5900 self.updatingctrls = False
5901
5902 def update_trc_control(self) -> None:
5903 """Update the TRC control based on the current configuration."""
5904 if self.trc_ctrl.GetSelection() not in (1, 4, 7):
5905 return
5906 if (
5907 getcfg("trc.type") == "G"
5908 and getcfg("calibration.black_output_offset") == 0
5909 and getcfg("trc") == 2.4
5910 ):
5911 self.trc_ctrl.SetSelection(4) # BT.1886
5912 elif (
5913 getcfg("trc.type") == "g"
5914 and getcfg("calibration.black_output_offset") == 1
5915 and getcfg("trc") == 2.2
5916 ):
5917 # Gamma 2.2 relative 100% output offset
5918 self.trc_ctrl.SetSelection(1)
5919 else:
5920 self.trc_ctrl.SetSelection(7) # Custom
5921
5922 def update_use_video_lut(self) -> None:
5923 """Update the use video LUT checkbox based on the current display."""
5924 # Check if the selected display is a pattern generator. If so,
5925 # don't use videoLUT for calibration. Restore previous value
5926 # when switching back to a display with videoLUT access.
5927 is_patterngenerator = config.is_patterngenerator()
5928 setcfg_cond(is_patterngenerator, "calibration.use_video_lut", 0)
5929 if not is_patterngenerator and sys.platform == "darwin":
5930 # macOS video levels encoding seems to only work right on
5931 # some machines if not using videoLUT to do the scaling
5932 setcfg_cond(
5933 getcfg("patterngenerator.use_video_levels"),
5934 "calibration.use_video_lut",
5935 0,
5936 )
5937 self.menuitem_do_not_use_video_lut.Check(
5938 not bool(getcfg("calibration.use_video_lut"))
5939 )
5940
5941 def show_trc_controls(self, freeze: bool = False) -> None:
5942 """Show or hide TRC controls based on the selected TRC type.
5943
5944 Args:
5945 freeze (bool): Whether to freeze the panel while updating controls.
5946 """
5947 show_advanced_options = bool(getcfg("show_advanced_options"))
5948 if freeze:
5949 self.panel.Freeze()
5950 for ctrl in (self.trc_gamma_label, self.trc_textctrl, self.trc_type_ctrl):
5951 ctrl.Show(
5952 self.trc_ctrl.GetSelection() == 7
5953 or (self.trc_ctrl.GetSelection() in (1, 4) and show_advanced_options)
5954 )
5955 for ctrl in (
5956 self.black_output_offset_label,
5957 self.black_output_offset_ctrl,
5958 self.black_output_offset_intctrl,
5959 self.black_output_offset_intctrl_label,
5960 ):
5961 ctrl.Show(
5962 self.trc_ctrl.GetSelection() == 7
5963 or (self.trc_ctrl.GetSelection() > 0 and show_advanced_options)
5964 )
5965 for ctrl in (
5966 self.ambient_viewcond_adjust_cb,
5967 self.ambient_viewcond_adjust_textctrl,
5968 self.ambient_viewcond_adjust_textctrl_label,
5969 self.ambient_measure_btn,
5970 ):
5971 ctrl.GetContainingSizer().Show(
5972 ctrl,
5973 # Rec. 709/SMPTE 240M
5974 self.trc_ctrl.GetSelection() in (3, 5)
5975 or (self.trc_ctrl.GetSelection() > 0 and show_advanced_options),
5976 )
5977 for ctrl in (
5978 self.black_point_correction_label,
5979 self.black_point_correction_auto_cb,
5980 ):
5981 ctrl.GetContainingSizer().Show(
5982 ctrl, self.trc_ctrl.GetSelection() > 0 and show_advanced_options
5983 )
5984 self.update_black_point_rate_ctrl()
5985 for ctrl in (
5986 self.calibration_quality_label,
5987 self.calibration_quality_ctrl,
5988 self.calibration_quality_info,
5989 self.cal_meas_time,
5990 ):
5991 ctrl.GetContainingSizer().Show(ctrl, self.trc_ctrl.GetSelection() > 0)
5992 # Make the height of the last row in the calibration settings sizer
5993 # match the other rows
5994 minheight = self.trc_ctrl.Size[1] + 8 if self.trc_ctrl.GetSelection() > 0 else 0
5995 self.calibration_quality_ctrl.ContainingSizer.SetMinSize((0, minheight))
5996 self.black_point_correction_auto_handler()
5997 if freeze:
5998 self.panel.Thaw()
5999
6000 def check_show_macos_bugs_warning(
6001 self, cal: bool = True, profile: bool = True
6002 ) -> None:
6003 """Warn about specific macOS bugs.
6004
6005 Args:
6006 cal (bool, optional): Whether to check for calibration-related
6007 bugs.
6008 profile (bool, optional): Whether to check for profile-related
6009 bugs.
6010 """
6011 if sys.platform != "darwin" or intlist(platform.mac_ver()[0].split(".")) < [
6012 10,
6013 8,
6014 ]:
6015 # We assume these macOS bugs exist since 10.8 "Mountain Lion"
6016 return None
6017 result = None
6018 if cal and (
6019 getcfg("calibration.black_point_correction.auto")
6020 or getcfg("calibration.black_point_correction")
6021 or getcfg("calibration.black_luminance", False)
6022 ): # Warn about calibration bugs
6023 dlg = ConfirmDialog(
6024 self,
6025 msg=lang.getstr("macos.bugs.cal.warning"),
6026 ok=lang.getstr("yes"),
6027 alt=lang.getstr("no"),
6028 bitmap=get_icon(32, "dialog-warning"),
6029 )
6030 result = dlg.ShowModal()
6031 dlg.Destroy()
6032 if result == wx.ID_OK:
6033 self.black_luminance_ctrl.SetSelection(0)
6034 self.black_luminance_ctrl_handler(
6035 CustomEvent(wx.EVT_CHOICE.evtType[0], self.black_luminance_ctrl)
6036 )
6037 setcfg("calibration.black_point_correction.auto", 0)
6038 setcfg("calibration.black_point_correction", 0)
6039 self.black_point_correction_ctrl.SetValue(0)
6040 self.black_point_correction_intctrl.SetValue(0)
6041 self.black_point_correction_auto_handler()
6042 self.update_black_point_rate_ctrl()
6043 elif result == wx.ID_CANCEL:
6044 return False
6045 if not profile or not (
6046 getcfg("profile.type") != "S"
6047 or not getcfg("profile.black_point_compensation")
6048 ):
6049 return None
6050 # Warn about profile bugs
6051 dlg = ConfirmDialog(
6052 self,
6053 msg=lang.getstr("macos.bugs.profile.warning"),
6054 ok=lang.getstr("yes"),
6055 alt=lang.getstr("no"),
6056 bitmap=get_icon(32, "dialog-warning"),
6057 )
6058 result = dlg.ShowModal()
6059 dlg.Destroy()
6060 if result == wx.ID_OK:
6061 setcfg("profile.type", "S")
6062 setcfg("profile.black_point_compensation", 1)
6063 self.update_profile_type_ctrl()
6064 self.update_bpc()
6065 elif result == wx.ID_CANCEL:
6066 return False
6067 return None
6068
6069 def update_black_output_offset_ctrl(self) -> None:
6070 """Update the black output offset controls based on configuration."""
6071 self.black_output_offset_ctrl.SetValue(
6072 int(Decimal(str(getcfg("calibration.black_output_offset"))) * 100)
6073 )
6074 self.black_output_offset_intctrl.SetValue(
6075 int(Decimal(str(getcfg("calibration.black_output_offset"))) * 100)
6076 )
6077
6078 def update_black_point_rate_ctrl(self) -> None:
6079 """Update the visibility and state of the black point rate controls."""
6080 self.panel.Freeze()
6081 enable = not (self.calibration_update_cb.GetValue())
6082 show = (
6083 self.trc_ctrl.GetSelection() > 0
6084 and bool(getcfg("show_advanced_options"))
6085 and DEFAULTS["calibration.black_point_rate.enabled"]
6086 )
6087 self.black_point_rate_label.GetContainingSizer().Show(
6088 self.black_point_rate_label, show
6089 )
6090 self.black_point_rate_ctrl.GetContainingSizer().Show(
6091 self.black_point_rate_ctrl, show
6092 )
6093 self.black_point_rate_ctrl.Enable(
6094 enable
6095 and getcfg("calibration.black_point_correction") < 1
6096 and DEFAULTS["calibration.black_point_rate.enabled"]
6097 )
6098 self.black_point_rate_floatctrl.GetContainingSizer().Show(
6099 self.black_point_rate_floatctrl, show
6100 )
6101 self.black_point_rate_floatctrl.Enable(
6102 enable
6103 and getcfg("calibration.black_point_correction") < 1
6104 and DEFAULTS["calibration.black_point_rate.enabled"]
6105 )
6106 self.calpanel.Layout()
6107 self.panel.Thaw()
6108
6109 def update_bpc(self, enable_profile: bool = True) -> None:
6110 """Update the black point compensation controls based on configuration.
6111
6112 Args:
6113 enable_profile (bool): Whether to enable black point compensation
6114 controls based on the profile type and other settings.
6115 """
6116 enable_bpc = (
6117 self.get_profile_type() in ("s", "S")
6118 or (
6119 self.get_profile_type() in ("l", "x", "X")
6120 and (
6121 getcfg("profile.b2a.hires")
6122 or getcfg("profile.quality.b2a") in ("l", "n")
6123 )
6124 )
6125 ) and enable_profile
6126 if not enable_bpc:
6127 setcfg("profile.black_point_compensation", 0)
6128 self.black_point_compensation_cb.Enable(enable_bpc)
6129 self.black_point_compensation_cb.SetValue(
6130 enable_bpc and bool(int(getcfg("profile.black_point_compensation")))
6131 )
6132
6133 def update_drift_compensation_ctrls(self) -> None:
6134 """Update the visibility and state of the drift compensation controls."""
6135 self.panel.Freeze()
6136 not_untethered = config.get_display_name(None, True) != "Untethered"
6137 self.blacklevel_drift_compensation.GetContainingSizer().Show(
6138 self.blacklevel_drift_compensation,
6139 self.worker.argyll_version >= [1, 3, 0] and not_untethered,
6140 )
6141 self.whitelevel_drift_compensation.GetContainingSizer().Show(
6142 self.whitelevel_drift_compensation,
6143 self.worker.argyll_version >= [1, 3, 0] and not_untethered,
6144 )
6145 self.calpanel.Layout()
6146 self.panel.Thaw()
6147
6148 def update_estimated_measurement_time(self, which: str) -> None:
6149 """Update the estimated measurement time shown.
6150
6151 Args:
6152 which (str): The type of measurement to estimate time for.
6153 Valid values are "testchart", "cal", and "chart".
6154 """
6155 if which == "testchart":
6156 patches = int(self.testchart_patches_amount.Label)
6157 elif which == "cal":
6158 # See dispcal.c
6159 isteps, rsteps, maxits, mxrpts = {
6160 "v": (10, 16, 1, 10),
6161 "l": (12, 32, 2, 10),
6162 "m": (16, 64, 3, 12),
6163 "h": (20, 96, 4, 16),
6164 "u": (24, 128, 5, 24),
6165 }[getcfg("calibration.quality")]
6166
6167 # 1st iteration
6168 rsteps /= 1 << (maxits - 1)
6169 patches = rsteps
6170 # 2nd..nth iteration
6171 for _i in range(maxits - 1):
6172 rsteps *= 2
6173 patches += rsteps
6174 # Multiply by estimated repeats
6175 patches *= mxrpts / 1.5
6176 # Amount of precal patches is always 9
6177 patches += 9
6178 # Initial amount of cal patches is always isteps * 4
6179 patches += isteps * 4
6180
6181 # Adjust by dark integration time (scale factor)
6182 integration_time = self.worker.get_instrument_features().get(
6183 "integration_time"
6184 )
6185 if integration_time and (
6186 sum(integration_time) / float(len(integration_time))
6187 == integration_time[0]
6188 ): # Check for fixed integration time
6189 # This helps estimation for instruments with fixed
6190 # integration time (e.g. SpyderX)
6191 patches *= float(integration_time[0]) / 2.45
6192 patches = round(patches)
6193 elif which == "chart":
6194 patches = int(self.chart_patches_amount.Label)
6195 ReportFrame.update_estimated_measurement_time(self, which, patches)
6196
6197 def update_estimated_measurement_times(self) -> None:
6198 """Update the estimated measurement times for calibration and profiling."""
6199 self.update_estimated_measurement_time("cal")
6200 self.update_estimated_measurement_time("testchart")
6201 self.update_estimated_measurement_time("chart")
6202
6203 def update_ffp_insertion_ctrl(self) -> None:
6204 """Update the FFP insertion controls based on configuration."""
6205 ffp_insertion = bool(getcfg("patterngenerator.ffp_insertion"))
6206 self.ffp_insertion.SetValue(ffp_insertion)
6207 for ctrl in (
6208 self.ffp_insertion_interval_label,
6209 self.ffp_insertion_interval,
6210 self.ffp_insertion_interval_s_label,
6211 self.ffp_insertion_duration_label,
6212 self.ffp_insertion_duration,
6213 self.ffp_insertion_duration_s_label,
6214 self.ffp_insertion_level_label,
6215 self.ffp_insertion_level,
6216 self.ffp_insertion_level_percentage_label,
6217 ):
6218 ctrl.Enable(ffp_insertion)
6219
6220 def blacklevel_drift_compensation_handler(self, event: wx.Event) -> None:
6221 """Handle the blacklevel drift compensation checkbox event.
6222
6223 Args:
6224 event (wx.Event): The event that triggered this handler.
6225 """
6226 setcfg(
6227 "drift_compensation.blacklevel",
6228 int(self.blacklevel_drift_compensation.GetValue()),
6229 )
6230 self.update_estimated_measurement_times()
6231
6232 def whitelevel_drift_compensation_handler(self, event: wx.Event) -> None:
6233 """Handle the whitelevel drift compensation checkbox event.
6234
6235 Args:
6236 event (wx.Event): The event that triggered this handler.
6237 """
6238 setcfg(
6239 "drift_compensation.whitelevel",
6240 int(self.whitelevel_drift_compensation.GetValue()),
6241 )
6242 self.update_estimated_measurement_times()
6243
6244 def calibration_update_ctrl_handler(self, event: wx.Event) -> None:
6245 """Handle the calibration update checkbox event.
6246
6247 Args:
6248 event (wx.Event): The event that triggered this handler.
6249 """
6250 debug_print(
6251 "[D] calibration_update_ctrl_handler called for ID "
6252 f"{event.GetId()} {getevtobjname(event, self)} event type "
6253 f"{event.GetEventType()} {getevttype(event)}"
6254 )
6255 setcfg("calibration.update", int(self.calibration_update_cb.GetValue()))
6256 setcfg(
6257 "profile.update",
6258 int(self.calibration_update_cb.GetValue() and is_profile()),
6259 )
6260 self.update_controls()
6261
6262 def enable_spyder2_handler(
6263 self,
6264 event: wx.Event,
6265 check_instrument_setup: bool = False,
6266 callafter: None | Callable = None,
6267 callafter_args: None | tuple = None,
6268 ) -> None | bool:
6269 """Handle the enable Spyder2 button click event.
6270
6271 Args:
6272 event (wx.Event): The event that triggered this handler.
6273 check_instrument_setup (bool, optional): Whether to check
6274 instrument setup.
6275 callafter (None | Callable, optional): A function to call after
6276 enabling Spyder2.
6277 callafter_args (tuple, optional): Arguments to pass to the
6278 callafter function.
6279
6280 Returns:
6281 None | bool: None if cancelled, True if successful, or
6282 a boolean indicating the success of the operation.
6283 """
6284 self.update_menus()
6285 if not check_set_argyll_bin():
6286 return None
6287 msg = lang.getstr("oem.import.auto")
6288 if sys.platform == "win32":
6289 msg = " ".join([lang.getstr("oem.import.auto_windows"), msg])
6290 dlg = ConfirmDialog(
6291 self,
6292 title=lang.getstr("enable_spyder2"),
6293 msg=msg,
6294 ok=lang.getstr("auto"),
6295 cancel=lang.getstr("cancel"),
6296 bitmap=get_icon(32, "dialog-information"),
6297 alt=lang.getstr("file.select"),
6298 )
6299 needroot = self.worker.argyll_version < [1, 2, 0]
6300 dlg.install_user = wx.RadioButton(
6301 dlg, -1, lang.getstr("install_user"), style=wx.RB_GROUP
6302 )
6303 dlg.install_user.Enable(not needroot)
6304 dlg.install_user.SetValue(not needroot)
6305 dlg.sizer3.Add(dlg.install_user, flag=wx.TOP | wx.ALIGN_LEFT, border=16)
6306 dlg.install_systemwide = wx.RadioButton(
6307 dlg, -1, lang.getstr("install_local_system")
6308 )
6309 dlg.install_user.Enable(not needroot)
6310 dlg.install_systemwide.SetValue(needroot)
6311 dlg.install_user.Bind(wx.EVT_RADIOBUTTON, install_scope_handler)
6312 dlg.install_systemwide.Bind(wx.EVT_RADIOBUTTON, install_scope_handler)
6313 install_scope_handler(dlg=dlg)
6314 dlg.sizer3.Add(dlg.install_systemwide, flag=wx.TOP | wx.ALIGN_LEFT, border=4)
6315 dlg.sizer0.SetSizeHints(dlg)
6316 dlg.sizer0.Layout()
6317 choice = dlg.ShowModal() if event else wx.ID_OK
6318 asroot = dlg.install_systemwide.GetValue()
6319 dlg.Destroy()
6320 if choice == wx.ID_CANCEL:
6321 return None
6322 if choice == wx.ID_OK:
6323 # Auto
6324 path = None
6325 else:
6326 # Prompt for installer executable
6327 default_dir, default_file = expanduseru("~"), ""
6328 dlg = wx.FileDialog(
6329 self,
6330 lang.getstr("file.select"),
6331 defaultDir=default_dir,
6332 defaultFile=default_file,
6333 wildcard=lang.getstr("filetype.any") + "|*",
6334 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
6335 )
6336 dlg.Center(wx.BOTH)
6337 result = dlg.ShowModal()
6338 path = dlg.GetPath()
6339 dlg.Destroy()
6340 if result != wx.ID_OK:
6341 return None
6342 if asroot:
6343 result = self.worker.authenticate(
6344 get_argyll_util("spyd2en"), lang.getstr("enable_spyder2"), self
6345 )
6346 if result not in (True, None):
6347 if isinstance(result, Exception):
6348 show_result_dialog(result, self)
6349 return None
6350 self.worker.start(
6351 self.enable_spyder2_consumer,
6352 self.enable_spyder2_producer,
6353 cargs=(check_instrument_setup, callafter, callafter_args),
6354 wargs=(path, asroot),
6355 progress_msg=lang.getstr("enable_spyder2"),
6356 fancy=False,
6357 )
6358 return (event and None) or True
6359
6360 def enable_spyder2(self, path: str, asroot: bool) -> bool | str:
6361 """Enable Spyder2 by running the spyd2en utility.
6362
6363 Args:
6364 path (str): Path to the Spyder2 installer executable.
6365 asroot (bool): Whether to install system-wide (as root) or
6366 user-wide.
6367
6368 Raises:
6369 Exception: If an error occurs during the enabling process.
6370
6371 Returns:
6372 bool | str: True if Spyder2 firmware exists, False if not, or
6373 a string with the path to the Spyder2 firmware if successful.
6374 """
6375 cmd, args = get_argyll_util("spyd2en"), ["-v"]
6376 if asroot and self.worker.argyll_version >= [1, 2, 0]:
6377 args.append("-Sl")
6378 if path:
6379 args.append(path)
6380 result = self.worker.exec_cmd(
6381 cmd,
6382 args,
6383 capture_output=True,
6384 skip_scripts=True,
6385 silent=False,
6386 asroot=asroot,
6387 title=lang.getstr("enable_spyder2"),
6388 )
6389 if asroot and sys.platform == "win32":
6390 # Wait for async process
6391 sleep(1)
6392 if result and not isinstance(result, Exception):
6393 result = self.worker.spyder2_firmware_exists(scope="l" if asroot else "u")
6394 return result
6395
6396 def enable_spyder2_producer(self, path: str, asroot: bool) -> None | str:
6397 """Producer for enabling Spyder2.
6398
6399 Args:
6400 path (str): Path to the Spyder2 installer executable.
6401 asroot (bool): Whether to install system-wide (as root) or
6402 user-wide.
6403
6404 Raises:
6405 Exception: If an error occurs during the enabling process.
6406
6407 Returns:
6408 None | str: Path to the Spyder2 firmware if successful, None if
6409 cancelled.
6410 """
6411 if path:
6412 return self.enable_spyder2(path, asroot)
6413
6414 if sys.platform in ("darwin", "win32"):
6415 # Look for Spyder.lib/CVSpyder.dll ourself because spyd2en
6416 # will only try some fixed paths
6417 if sys.platform == "darwin":
6418 wildcard = os.path.join(
6419 os.path.sep,
6420 "Applications",
6421 "Spyder2*",
6422 "Spyder2*.app",
6423 "Contents",
6424 "MacOSClassic",
6425 "Spyder.lib",
6426 )
6427 else:
6428 wildcard = os.path.join(
6429 getenvu("PROGRAMFILES", ""),
6430 "ColorVision",
6431 "Spyder2*",
6432 "CVSpyder.dll",
6433 )
6434 safe_glob_wildcard = safe_glob(wildcard)
6435 path = safe_glob_wildcard[0] if safe_glob_wildcard else None
6436 if getcfg("dry_run"):
6437 return None
6438 if path:
6439 result = self.enable_spyder2(path, asroot)
6440 if result and not isinstance(result, Exception):
6441 return result
6442 # Download from web
6443 path = self.worker.download(f"https://{DOMAIN}/spyd2")
6444 if isinstance(path, Exception):
6445 return path
6446 if not path:
6447 # Cancelled
6448 return None
6449 return self.enable_spyder2(path, asroot)
6450
6451 def enable_spyder2_consumer(
6452 self,
6453 result: bool | str | Exception,
6454 check_instrument_setup: bool,
6455 callafter: None | Callable = None,
6456 callafter_args: tuple = (),
6457 ) -> None:
6458 """Consumer for enabling Spyder2.
6459
6460 Args:
6461 result (bool | str | Exception): Result of the enabling process.
6462 check_instrument_setup (bool): Whether to check instrument setup.
6463 callafter (None | Callable, optional): A function to call after
6464 enabling Spyder2.
6465 callafter_args (tuple, optional): Arguments to pass to the
6466 callafter function.
6467 """
6468 if not isinstance(result, Exception) and result:
6469 result = UnloggedInfo(lang.getstr("enable_spyder2_success"))
6470 self.update_menus()
6471 elif result is False:
6472 result = UnloggedError("".join(self.worker.errors))
6473 if result:
6474 show_result_dialog(result, self)
6475 if check_instrument_setup:
6476 self.check_instrument_setup(callafter, callafter_args)
6477 elif callafter:
6478 wx.CallAfter(callafter, *callafter_args)
6479
6480 def extra_args_handler(self, event: wx.Event) -> None:
6481 """Handle the extra arguments menu item.
6482
6483 Args:
6484 event (wx.Event): The event triggered by the menu item.
6485 """
6486 if not hasattr(self, "extra_args"):
6487 self.extra_args = ExtraArgsFrame(self)
6488 self.extra_args.Center()
6489 if self.extra_args.IsShownOnScreen():
6490 self.extra_args.Raise()
6491 else:
6492 self.extra_args.Show()
6493
6494 def startup_sound_enable_handler(self, event: wx.Event) -> None:
6495 """Handle the startup sound enable menu item.
6496
6497 Args:
6498 event (wx.Event): The event triggered by the menu item.
6499 """
6500 setcfg("startup_sound.enable", int(self.menuitem_startup_sound.IsChecked()))
6501
6502 def use_simple_splash_handler(self, event: wx.Event) -> None:
6503 """Handle the simple splash screen menu item.
6504
6505 Args:
6506 event (wx.Event): The event triggered by the menu item.
6507 """
6508 setcfg("splash.simple", int(self.menuitem_use_simple_splash.IsChecked()))
6509
6510 def use_fancy_progress_handler(self, event: wx.Event) -> None:
6511 """Handle the use fancy progress menu item.
6512
6513 Args:
6514 event (wx.Event): The event triggered by the menu item.
6515 """
6516 setcfg("use_fancy_progress", int(self.menuitem_use_fancy_progress.IsChecked()))
6517
6518 def use_separate_lut_access_handler(self, event: wx.Event) -> None:
6519 """Handle the use separate LUT access menu item.
6520
6521 Args:
6522 event (wx.Event): The event triggered by the menu item.
6523 """
6524 setcfg(
6525 "use_separate_lut_access",
6526 int(self.menuitem_use_separate_lut_access.IsChecked()),
6527 )
6528 self.update_displays(set_height=True)
6529
6530 def do_not_use_video_lut_handler(self, event: wx.Event) -> None:
6531 """Handle the do not use video LUT menu item.
6532
6533 Args:
6534 event (wx.Event): The event triggered by the menu item.
6535 """
6536 do_not_use_video_lut = self.menuitem_do_not_use_video_lut.IsChecked()
6537 is_patterngenerator = config.is_patterngenerator()
6538 if do_not_use_video_lut != is_patterngenerator:
6539 dlg = ConfirmDialog(
6540 self,
6541 msg=lang.getstr("calibration.do_not_use_video_lut.warning"),
6542 ok=lang.getstr("yes"),
6543 cancel=lang.getstr("no"),
6544 bitmap=get_icon(32, "dialog-warning"),
6545 log=False,
6546 )
6547 result = dlg.ShowModal()
6548 dlg.Destroy()
6549 if result != wx.ID_OK:
6550 self.menuitem_do_not_use_video_lut.Check(is_patterngenerator)
6551 return
6552 setcfg("calibration.use_video_lut", int(not do_not_use_video_lut))
6553 if not is_patterngenerator:
6554 setcfg("calibration.use_video_lut.backup", None)
6555
6556 def skip_legacy_serial_ports_handler(self, event: wx.Event) -> None:
6557 """Handle the skip legacy serial ports menu item.
6558
6559 Args:
6560 event (wx.Event): The event triggered by the menu item.
6561 """
6562 setcfg(
6563 "skip_legacy_serial_ports",
6564 int(self.menuitem_skip_legacy_serial_ports.IsChecked()),
6565 )
6566
6567 def calibrate_instrument_handler(self, event: wx.Event) -> None:
6568 """Handle the calibrate instrument menu item.
6569
6570 Args:
6571 event (wx.Event): The event triggered by the menu item.
6572 """
6573 self.worker.start(
6574 lambda result: (
6575 show_result_dialog(result, self)
6576 if isinstance(result, Exception)
6577 else None
6578 ),
6579 self.worker.calibrate_instrument_producer,
6580 fancy=False,
6581 )
6582
6583 def allow_skip_sensor_cal_handler(self, event: wx.Event) -> None:
6584 """Handle the allow skip sensor calibration menu item.
6585
6586 Args:
6587 event (wx.Event): The event triggered by the menu item.
6588 """
6589 setcfg(
6590 "allow_skip_sensor_cal",
6591 int(self.menuitem_allow_skip_sensor_cal.IsChecked()),
6592 )
6593
6594 def update_adjustment_controls(self) -> None:
6595 """Update the adjustment controls based on the current configuration."""
6596 update_cal = getcfg("calibration.update")
6597 auto = self.get_measurement_mode() == "auto"
6598 do_cal = bool(
6599 getcfg("calibration.interactive_display_adjustment") or getcfg("trc")
6600 )
6601 enable = not update_cal and not auto and do_cal
6602 for option in (
6603 "whitepoint.colortemp",
6604 "whitepoint.x",
6605 "whitepoint.y",
6606 "calibration.luminance",
6607 "calibration.black_luminance",
6608 "calibration.interactive_display_adjustment",
6609 ):
6610 backup = getcfg(f"{option}.backup", False)
6611 if auto and backup is None:
6612 # Backup current settings
6613 setcfg(f"{option}.backup", getcfg(option, False))
6614 elif not auto and backup is not None:
6615 setcfg(option, getcfg(f"{option}.backup"))
6616 setcfg(f"{option}.backup", None)
6617 if auto or not do_cal:
6618 setcfg("whitepoint.colortemp", None)
6619 setcfg("whitepoint.x", None)
6620 setcfg("whitepoint.y", None)
6621 setcfg("3dlut.whitepoint.x", None)
6622 setcfg("3dlut.whitepoint.y", None)
6623 self.whitepoint_colortemp_textctrl.Hide()
6624 self.whitepoint_colortemp_label.Hide()
6625 self.whitepoint_x_textctrl.Hide()
6626 self.whitepoint_x_label.Hide()
6627 self.whitepoint_y_textctrl.Hide()
6628 self.whitepoint_y_label.Hide()
6629 self.visual_whitepoint_editor_btn.Hide()
6630 self.whitepoint_measure_btn.Hide()
6631 self.luminance_ctrl.SetSelection(0)
6632 self.luminance_textctrl.Hide()
6633 self.luminance_textctrl_label.Hide()
6634 setcfg("calibration.luminance", None)
6635 self.black_luminance_textctrl.Hide()
6636 self.black_luminance_textctrl_label.Hide()
6637 setcfg("calibration.black_luminance", None)
6638 setcfg("calibration.interactive_display_adjustment", 0)
6639 self.whitepoint_ctrl.Enable(enable)
6640 self.luminance_ctrl.Enable(enable)
6641 self.black_luminance_ctrl.Enable(enable)
6642 self.interactive_display_adjustment_cb.Enable(not update_cal and not auto)
6643
6644 self.interactive_display_adjustment_cb.SetValue(
6645 not update_cal
6646 and bool(int(getcfg("calibration.interactive_display_adjustment")))
6647 )
6648 self.whitepoint_colortemp_textctrl.SetValue(
6649 str(stripzeros(getcfg("whitepoint.colortemp")))
6650 )
6651 self.whitepoint_x_textctrl.SetValue(round(getcfg("whitepoint.x"), 4))
6652 self.whitepoint_y_textctrl.SetValue(round(getcfg("whitepoint.y"), 4))
6653 sel = self.whitepoint_ctrl.GetSelection()
6654 if getcfg("whitepoint.colortemp", False):
6655 self.whitepoint_ctrl.SetSelection(1)
6656 elif getcfg("whitepoint.x", False) and getcfg("whitepoint.y", False):
6657 self.whitepoint_ctrl.SetSelection(2)
6658 else:
6659 self.whitepoint_ctrl.SetSelection(0)
6660 self.whitepoint_ctrl_handler(
6661 CustomEvent(wx.EVT_CHOICE.evtType[0], self.whitepoint_ctrl),
6662 -1 < sel != self.whitepoint_ctrl.GetSelection(),
6663 )
6664 show_advanced_options = bool(getcfg("show_advanced_options"))
6665 for ctrl in (
6666 self.whitepoint_colortemp_locus_label,
6667 self.whitepoint_colortemp_locus_ctrl,
6668 ):
6669 ctrl.Show(
6670 self.whitepoint_ctrl.GetSelection() in (0, 1)
6671 and not auto
6672 and do_cal
6673 and show_advanced_options
6674 )
6675
6676 for name in ("luminance", "black_luminance"):
6677 userconf = bool(getcfg(f"calibration.{name}", False))
6678 getattr(self, f"{name}_ctrl").SetSelection(int(userconf))
6679 getattr(self, f"{name}_textctrl").SetValue(getcfg(f"calibration.{name}"))
6680 if name == "black_luminance":
6681 userconf = show_advanced_options and userconf
6682 else:
6683 self.ambient_luminance_measure_btn.Show(userconf)
6684 getattr(self, f"{name}_textctrl").Show(userconf)
6685 getattr(self, f"{name}_textctrl_label").Show(userconf)
6686 getattr(self, f"{name}_measure_btn").Show(userconf)
6687
6688 def enable_3dlut_tab_handler(self, event: wx.Event) -> None:
6689 """Handle enabling or disabling the 3D LUT tab.
6690
6691 Args:
6692 event (wx.Event): The event triggered by the menu item.
6693 """
6694 setcfg("3dlut.tab.enable", int(self.menuitem_enable_3dlut_tab.IsChecked()))
6695 setcfg("3dlut.tab.enable.backup", getcfg("3dlut.tab.enable"))
6696 if not getcfg("3dlut.tab.enable"):
6697 setcfg("3dlut.create", 0)
6698 self.lut3d_update_controls()
6699 self.update_main_controls()
6700
6701 def enable_argyll_debug_handler(self, event: wx.Event) -> None:
6702 """Handle enabling or disabling Argyll debug mode.
6703
6704 Args:
6705 event (wx.Event): The event triggered by the debug menu item.
6706 """
6707 if not getcfg("argyll.debug"):
6708 dlg = ConfirmDialog(
6709 self,
6710 msg=lang.getstr("argyll.debug.warning1"),
6711 ok=lang.getstr("ok"),
6712 cancel=lang.getstr("cancel"),
6713 bitmap=get_icon(32, "dialog-warning"),
6714 log=False,
6715 )
6716 result = dlg.ShowModal()
6717 dlg.Destroy()
6718 if result != wx.ID_OK:
6719 self.menuitem_enable_argyll_debug.Check(False)
6720 return
6721 InfoDialog(
6722 self,
6723 msg=lang.getstr("argyll.debug.warning2"),
6724 bitmap=get_icon(32, "dialog-warning"),
6725 log=False,
6726 )
6727 setcfg("argyll.debug", int(self.menuitem_enable_argyll_debug.IsChecked()))
6728
6729 def enable_dry_run_handler(self, event: wx.Event) -> None:
6730 """Handle enabling or disabling dry run mode.
6731
6732 Args:
6733 event (wx.Event): The event triggered by the dry run menu item.
6734 """
6735 setcfg("dry_run", int(self.menuitem_enable_dry_run.IsChecked()))
6736 self.menuitem_enable_argyll_debug.Enable(
6737 not self.menuitem_enable_dry_run.IsChecked()
6738 )
6739
6740 def enable_menus(self, enable: bool = True) -> None:
6741 """Enable or disable all menus in the menubar.
6742
6743 Args:
6744 enable (bool): If True, enable all menus; if False, disable them.
6745 """
6746 for menu, _label in self.menubar.GetMenus():
6747 for item in menu.GetMenuItems():
6748 item.Enable(enable)
6749 if enable:
6750 self.update_menus()
6751
6752 def lut3d_check_bpc(self) -> None:
6753 """Check if black point compensation is enabled for 3D LUTs."""
6754 if getcfg("3dlut.create") and getcfg("profile.black_point_compensation"):
6755 # Warn about BPC if creating 3D LUT
6756 dlg = ConfirmDialog(
6757 self,
6758 msg=lang.getstr("black_point_compensation.3dlut.warning"),
6759 ok=lang.getstr("turn_off"),
6760 cancel=lang.getstr("setting.keep_current"),
6761 bitmap=get_icon(32, "dialog-warning"),
6762 )
6763 if dlg.ShowModal() == wx.ID_OK:
6764 setcfg("profile.black_point_compensation", 0)
6765 self.update_bpc()
6766
6767 def check_3dlut_relcol_rendering_intent(self) -> None:
6768 """Check if relative colorimetric rendering intent is set for 3D LUTs."""
6769 if getcfg("3dlut.tab.enable") and getcfg("3dlut.rendering_intent") in (
6770 "a",
6771 "aa",
6772 "aw",
6773 "pa",
6774 ):
6775 wx.CallAfter(self.lut3d_confirm_relcol_rendering_intent)
6776
6777 def lut3d_confirm_relcol_rendering_intent(self) -> None:
6778 """Confirm the use of relative colorimetric rendering intent for 3D LUTs."""
6779 dlg = ConfirmDialog(
6780 self,
6781 msg=lang.getstr("3dlut.confirm_relcol_rendering_intent"),
6782 ok=lang.getstr("yes"),
6783 cancel=lang.getstr("no"),
6784 bitmap=get_icon(32, "dialog-warning"),
6785 )
6786 result = dlg.ShowModal()
6787 dlg.Destroy()
6788 if result == wx.ID_OK:
6789 self.lut3d_set_option("3dlut.rendering_intent", "r")
6790 self.lut3d_rendering_intent_ctrl.SetSelection(
6791 self.rendering_intents_ba[getcfg("3dlut.rendering_intent")]
6792 )
6793
6794 def lut3d_create_cb_handler(self, event: wx.Event) -> None:
6795 """Handle changes to the 3D LUT creation checkbox.
6796
6797 Args:
6798 event (wx.Event): The event triggered by the checkbox.
6799 """
6800 v = int(self.lut3d_create_cb.GetValue())
6801 if v != getcfg("3dlut.create"):
6802 self.profile_settings_changed()
6803 setcfg("3dlut.create", v)
6804 self.calpanel.Freeze()
6805 self.lut3d_show_trc_controls()
6806 self.lut3d_update_apply_cal_control()
6807 self.lut3d_update_b2a_controls()
6808 self.calpanel.Thaw()
6809 self.lut3d_check_bpc()
6810 self.update_main_controls()
6811
6812 def lut3d_init_input_profiles(self) -> None:
6813 """Initialize the input profiles for 3D LUTs."""
6814 self.input_profiles = {}
6815 for profile_filename in [
6816 "ACES.icm",
6817 "ACEScg.icm",
6818 "DCDM X'Y'Z'.icm",
6819 "Rec709.icm",
6820 "Rec2020.icm",
6821 "EBU3213_PAL.icm",
6822 "SMPTE_RP145_NTSC.icm",
6823 "SMPTE431_P3.icm",
6824 "SMPTE431_P3_D65.icm",
6825 getcfg("3dlut.input.profile"),
6826 ]:
6827 if not os.path.isabs(profile_filename):
6828 profile_filename = get_data_path("ref/" + profile_filename)
6829 if not profile_filename:
6830 continue
6831 try:
6832 profile = ICCProfile(profile_filename)
6833 except (OSError, ICCProfileInvalidError) as exception:
6834 print(f"{profile_filename}:", exception)
6835 continue
6836 if profile_filename not in list(self.input_profiles.values()):
6837 desc = profile.getDescription()
6838 desc = re.sub(
6839 r"\s*(?:color profile|primaries with "
6840 r"\S+ transfer function)$",
6841 "",
6842 desc,
6843 )
6844 self.input_profiles[desc] = profile_filename
6845 self.input_profiles = dict_sort(self.input_profiles)
6846 self.lut3d_input_profile_ctrl.SetItems(list(self.input_profiles.keys()))
6847
6848 def lut3d_input_colorspace_handler(self, event: wx.Event) -> None:
6849 """Handle changes to the input colorspace selection for 3D LUTs.
6850
6851 Args:
6852 event (wx.Event): The event triggered by the input colorspace control.
6853 """
6854 if not event:
6855 self.lut3d_input_profile_ctrl.SetToolTipString(
6856 getcfg("3dlut.input.profile")
6857 )
6858 return
6859 self.lut3d_set_option(
6860 "3dlut.input.profile",
6861 self.input_profiles[self.lut3d_input_profile_ctrl.GetStringSelection()],
6862 event,
6863 )
6864 lut3d_input_profile = ICCProfile(getcfg("3dlut.input.profile"))
6865 if (
6866 lut3d_input_profile
6867 and "rTRC" in lut3d_input_profile.tags
6868 and "gTRC" in lut3d_input_profile.tags
6869 and "bTRC" in lut3d_input_profile.tags
6870 and lut3d_input_profile.tags.rTRC
6871 == lut3d_input_profile.tags.gTRC
6872 == lut3d_input_profile.tags.bTRC
6873 and isinstance(lut3d_input_profile.tags.rTRC, CurveType)
6874 ):
6875 tf = lut3d_input_profile.tags.rTRC.get_transfer_function(outoffset=1.0)
6876 # Set gamma to profile gamma if single gamma profile
6877 # Backup current gamma
6878 # Restore previous gamma if not single gamma
6879 # profile
6880 setcfg_cond(
6881 tf[0][0].startswith("Gamma"),
6882 "3dlut.trc_gamma",
6883 round(tf[0][1], 2),
6884 True,
6885 )
6886 self.lut3d_update_trc_controls()
6887 self.lut3d_show_trc_controls()
6888 if getattr(self, "lut3dframe", None):
6889 self.lut3dframe.update_controls()
6890 self.lut3d_input_profile_ctrl.SetToolTipString(getcfg("3dlut.input.profile"))
6891
6892 def lut3d_set_path(
6893 self, path: None | str = None, set_mr_sim_profile: bool = True
6894 ) -> None:
6895 """Set the path for the 3D LUT and update related settings.
6896
6897 Args:
6898 path (None | str, optional): The path to the 3D LUT file. If None,
6899 the current path is used.
6900 set_mr_sim_profile (bool, optional): Whether to set the simulation
6901 profile for measurement reports.
6902 """
6903 self.lut3d_path = self.worker.lut3d_get_filename(path)
6904 devlink = os.path.splitext(self.lut3d_path)[0] + PROFILE_EXT
6905 mr_option_changed = False
6906 if devlink != getcfg("measurement_report.devlink_profile"):
6907 setcfg("measurement_report.devlink_profile", devlink)
6908 mr_option_changed = True
6909 # Simulation profile for 3D LUT
6910 if (
6911 set_mr_sim_profile
6912 and getcfg("3dlut.tab.enable")
6913 and (
6914 getcfg("3dlut.trc").startswith("smpte2084")
6915 or getcfg("3dlut.trc") == "hlg"
6916 or getcfg("3dlut.whitepoint.x", False)
6917 )
6918 ):
6919 # Use 3D LUT input profile
6920 cfgvalue = getcfg("3dlut.input.profile")
6921 # Add 3D LUT parameters and use only filename
6922 # (file will be in profile dir)
6923 cfgfn, cfgext = os.path.splitext(os.path.basename(cfgvalue))
6924 lut3d_fn = self.worker.lut3d_get_filename(cfgfn, False, False)
6925 cfgvalue = os.path.join(os.path.dirname(self.lut3d_path), lut3d_fn + cfgext)
6926 if cfgvalue != getcfg(
6927 "measurement_report.simulation_profile"
6928 ) and os.path.isfile(cfgvalue):
6929 setcfg("measurement_report.simulation_profile", cfgvalue)
6930 mr_option_changed = True
6931 if mr_option_changed:
6932 self.mr_update_controls()
6933
6934 def lut3d_show_controls(self) -> None:
6935 """Show or hide the 3D LUT controls based on the current configuration."""
6936 show = True # bool(getcfg("3dlut.create"))
6937 self.lut3d_input_profile_label.Show(show)
6938 self.lut3d_input_profile_ctrl.Show(show)
6939 self.lut3d_show_trc_controls()
6940 self.lut3d_show_encoding_controls(show)
6941 self.lut3d_format_label.Show(show)
6942 self.lut3d_format_ctrl.Show(show)
6943 show_advanced_options = getcfg("show_advanced_options")
6944 for ctrl in (
6945 self.lut3d_apply_cal_cb,
6946 self.gamut_mapping_mode,
6947 self.gamut_mapping_inverse_a2b,
6948 self.gamut_mapping_b2a,
6949 ):
6950 ctrl.GetContainingSizer().Show(ctrl, show_advanced_options and show)
6951 for ctrl in (self.lut3d_size_label, self.lut3d_size_ctrl):
6952 ctrl.GetContainingSizer().Show(ctrl, show)
6953
6954 def lut3d_update_apply_cal_control(self) -> None:
6955 """Update the apply calibration control based on the current configuration."""
6956 profile = not getcfg("3dlut.create") and get_current_profile(True)
6957 enable_apply_cal = bool(
6958 getcfg("3dlut.create")
6959 or (profile and isinstance(profile.tags.get("vcgt"), VideoCardGammaType))
6960 )
6961 self.lut3d_apply_cal_cb.SetValue(
6962 enable_apply_cal and bool(getcfg("3dlut.output.profile.apply_cal"))
6963 )
6964 self.lut3d_apply_cal_cb.Enable(enable_apply_cal)
6965
6966 def lut3d_update_b2a_controls(self) -> None:
6967 """Update the B2A controls based on the current configuration."""
6968 # Allow using B2A instead of inverse A2B?
6969 if getcfg("3dlut.create"):
6970 allow_b2a_gamap = getcfg("profile.type") in ("l", "x", "X") and getcfg(
6971 "profile.b2a.hires"
6972 )
6973 else:
6974 profile = get_current_profile(True)
6975 allow_b2a_gamap = (
6976 profile
6977 and "B2A0" in profile.tags
6978 and isinstance(profile.tags.B2A0, LUT16Type)
6979 and profile.tags.B2A0.clut_grid_steps >= 17
6980 )
6981 self.gamut_mapping_b2a.Enable(bool(allow_b2a_gamap))
6982 if not allow_b2a_gamap:
6983 setcfg("3dlut.gamap.use_b2a", 0)
6984 self.gamut_mapping_inverse_a2b.SetValue(not getcfg("3dlut.gamap.use_b2a"))
6985 self.gamut_mapping_b2a.SetValue(bool(getcfg("3dlut.gamap.use_b2a")))
6986
6987 def lut3d_update_controls(self) -> None:
6988 """Update the 3D LUT controls based on the current configuration."""
6989 self.lut3d_create_cb.SetValue(bool(getcfg("3dlut.create")))
6990 lut3d_input_profile = getcfg("3dlut.input.profile")
6991 if lut3d_input_profile not in list(self.input_profiles.values()):
6992 if not lut3d_input_profile or not os.path.isfile(lut3d_input_profile):
6993 lut3d_input_profile = DEFAULTS["3dlut.input.profile"]
6994 setcfg("3dlut.input.profile", lut3d_input_profile)
6995 else:
6996 try:
6997 profile = ICCProfile(lut3d_input_profile)
6998 except (OSError, ICCProfileInvalidError) as exception:
6999 print(f"{lut3d_input_profile}:", exception)
7000 else:
7001 desc = profile.getDescription()
7002 desc = re.sub(
7003 r"\s*(?:color profile|primaries with "
7004 r"\S+ transfer function)$",
7005 "",
7006 desc,
7007 )
7008 self.input_profiles[desc] = lut3d_input_profile
7009 if lut3d_input_profile in list(self.input_profiles.values()):
7010 self.lut3d_input_profile_ctrl.SetSelection(
7011 list(self.input_profiles.values()).index(lut3d_input_profile)
7012 )
7013 self.lut3d_input_colorspace_handler(None)
7014 self.lut3d_update_apply_cal_control()
7015 self.lut3d_update_b2a_controls()
7016 self.lut3d_update_shared_controls()
7017 self.lut3d_update_encoding_controls()
7018 self.lut3d_show_controls()
7019
7020 def profile_quality_warning_handler(self, event: wx.Event) -> None:
7021 """Show a warning dialog if the profile quality is set to ultra.
7022
7023 Args:
7024 event (wx.Event): The event that triggered the handler.
7025 """
7026 q = self.get_profile_quality()
7027 if q == "u":
7028 InfoDialog(
7029 self,
7030 msg=lang.getstr("quality.ultra.warning"),
7031 ok=lang.getstr("ok"),
7032 bitmap=get_icon(32, "dialog-warning"),
7033 log=False,
7034 )
7035
7036 def profile_quality_ctrl_handler(self, event: wx.Event) -> None:
7037 """Handle changes to the profile quality controls.
7038
7039 Args:
7040 event (wx.Event): The event that triggered the handler.
7041 """
7042 debug_print(
7043 "[D] profile_quality_ctrl_handler called for ID "
7044 f"{event.GetId()} {getevtobjname(event, self)} event type "
7045 f"{event.GetEventType()} {getevttype(event)}"
7046 )
7047 oldq = getcfg("profile.quality")
7048 q = self.get_profile_quality()
7049 if q == oldq:
7050 return
7051 if q == "l":
7052 self.profile_quality_info.SetLabel(lang.getstr("calibration.quality.low"))
7053 elif q == "m":
7054 self.profile_quality_info.SetLabel(
7055 lang.getstr("calibration.quality.medium")
7056 )
7057 elif q == "h":
7058 self.profile_quality_info.SetLabel(lang.getstr("calibration.quality.high"))
7059 elif q == "u":
7060 self.profile_quality_info.SetLabel(lang.getstr("calibration.quality.ultra"))
7061 self.profile_settings_changed()
7062 setcfg("profile.quality", q)
7063 self.update_profile_name()
7064 self.set_default_testchart(False)
7065 wx.CallAfter(self.check_testchart_patches_amount)
7066
7067 def calibration_file_ctrl_handler(self, event: wx.Event) -> None:
7068 """Handle changes to the calibration file control.
7069
7070 Args:
7071 event (wx.Event): The event that triggered the handler.
7072 """
7073 debug_print(
7074 "[D] calibration_file_ctrl_handler called for ID "
7075 f"{event.GetId()} {getevtobjname(event, self)} event type "
7076 f"{event.GetEventType()} {getevttype(event)}"
7077 )
7078 sel = self.calibration_file_ctrl.GetSelection()
7079 if sel > 0:
7080 self.load_cal_handler(None, path=self.recent_cals[sel])
7081 return
7082
7083 self.cal_changed(setchanged=False)
7084 if getattr(self, "lut3dframe", None):
7085 self.lut3dframe.set_profile("output")
7086 if getattr(self, "reportframe", None):
7087 self.reportframe.set_profile("output")
7088 # # Set measurement report dest profile to current
7089 # setcfg("measurement_report.output_profile",
7090 # get_current_profile_path())
7091 if self.lut3d_settings_panel.IsShown() or self.mr_settings_panel.IsShown():
7092 if self.mr_settings_panel.IsShown():
7093 self.mr_update_controls()
7094 else:
7095 self.set_profile("output")
7096 if self.lut3d_settings_panel.IsShown():
7097 self.lut3d_show_trc_controls()
7098 self.update_main_controls()
7099
7100 def settings_discard_changes(
7101 self, sel: None | int = None, keep_changed_state: bool = False
7102 ) -> None:
7103 """Update the calibration file control.
7104
7105 Also remove the leading asterisk (*) from items.
7106
7107 Args:
7108 sel (None | int, optional): The index of the selected item in the
7109 calibration file control. If None, the current selection will
7110 be used.
7111 keep_changed_state (bool, optional): If True, the changed state
7112 will not be reset. Defaults to False.
7113 """
7114 if sel is None:
7115 sel = self.calibration_file_ctrl.GetSelection()
7116 if not keep_changed_state:
7117 setcfg("settings.changed", 0)
7118 items = self.calibration_file_ctrl.GetItems()
7119 changed = False
7120 for j, item in enumerate(items):
7121 # if j != sel and item[0] == "*":
7122 if item[0] == "*":
7123 items[j] = item[2:]
7124 changed = True
7125 if changed:
7126 self.calibration_file_ctrl.Freeze()
7127 self.calibration_file_ctrl.SetItems(items)
7128 self.calibration_file_ctrl.SetSelection(sel)
7129 self.calibration_file_ctrl.Thaw()
7130
7131 def settings_confirm_discard(self) -> bool:
7132 """Show a dialog for user to confirm or cancel discarding changed settings.
7133
7134 Returns:
7135 bool: True if the user confirmed discarding changes, False otherwise.
7136 """
7137 sel = self.calibration_file_ctrl.GetSelection()
7138 cal = getcfg("calibration.file", False) or ""
7139 if cal not in self.recent_cals:
7140 self.recent_cals.append(cal)
7141 # The case-sensitive index could fail because of
7142 # case insensitive file systems, e.g. if the
7143 # stored filename string is
7144 # "C:\Users\Name\AppData\DisplayCAL\storage\MyFile"
7145 # but the actual filename is
7146 # "C:\Users\Name\AppData\DisplayCAL\storage\myfile"
7147 # (maybe because the user renamed the file)
7148 idx = index_fallback_ignorecase(self.recent_cals, cal)
7149 self.calibration_file_ctrl.SetSelection(idx)
7150 dlg = ConfirmDialog(
7151 self,
7152 msg=lang.getstr("warning.discard_changes"),
7153 ok=lang.getstr("ok"),
7154 cancel=lang.getstr("cancel"),
7155 bitmap=get_icon(32, "dialog-warning"),
7156 )
7157 result = dlg.ShowModal()
7158 dlg.Destroy()
7159 if result != wx.ID_OK:
7160 return False
7161 self.settings_discard_changes(sel)
7162 return True
7163
7164 def calibration_quality_ctrl_handler(self, event: wx.Event) -> None:
7165 """Handle changes to the calibration quality controls.
7166
7167 Args:
7168 event (wx.Event): The event that triggered the handler.
7169 """
7170 debug_print(
7171 "[D] calibration_quality_ctrl_handler called for ID "
7172 f"{event.GetId()} {getevtobjname(event, self)} event type "
7173 f"{event.GetEventType()} {getevttype(event)}"
7174 )
7175 q = self.get_calibration_quality()
7176 self.set_calibration_quality_label(q)
7177 if q != getcfg("calibration.quality"):
7178 self.profile_settings_changed()
7179 setcfg("calibration.quality", q)
7180 self.update_estimated_measurement_time("cal")
7181 self.update_profile_name()
7182
7183 def set_calibration_quality_label(self, q: str) -> None:
7184 """Set the label for the calibration quality info based on the quality level.
7185
7186 Args:
7187 q (str): The quality level, which can be one of "v", "l", "m", "h",
7188 or "u".
7189 """
7190 if q == "v":
7191 self.calibration_quality_info.SetLabel(
7192 lang.getstr("calibration.speed.veryhigh")
7193 )
7194 elif q == "l":
7195 self.calibration_quality_info.SetLabel(
7196 lang.getstr("calibration.speed.high")
7197 )
7198 elif q == "m":
7199 self.calibration_quality_info.SetLabel(
7200 lang.getstr("calibration.speed.medium")
7201 )
7202 elif q == "h":
7203 self.calibration_quality_info.SetLabel(lang.getstr("calibration.speed.low"))
7204 elif q == "u":
7205 self.calibration_quality_info.SetLabel(
7206 lang.getstr("calibration.speed.verylow")
7207 )
7208
7209 def interactive_display_adjustment_ctrl_handler(self, event: wx.Event) -> None:
7210 """Handle changes to the interactive display adjustment controls.
7211
7212 Args:
7213 event (wx.Event): The event that triggered the handler.
7214 """
7215 debug_print(
7216 "[D] interactive_display_adjustment_ctrl_handler called "
7217 f"for ID {event.GetId()} {getevtobjname(event, self)} event type "
7218 f"{event.GetEventType()} {getevttype(event)}"
7219 )
7220 v = int(self.interactive_display_adjustment_cb.GetValue())
7221 if v != getcfg("calibration.interactive_display_adjustment"):
7222 setcfg("calibration.interactive_display_adjustment", v)
7223 self.profile_settings_changed()
7224 self.panel.Freeze()
7225 self.update_adjustment_controls()
7226 self.calpanel.Layout()
7227 self.calpanel.Refresh()
7228 self.panel.Thaw()
7229 self.update_main_controls()
7230 self.update_profile_name()
7231
7232 def black_point_compensation_ctrl_handler(self, event: wx.Event) -> None:
7233 """Handle changes to the black point compensation controls.
7234
7235 Args:
7236 event (wx.Event): The event that triggered the handler.
7237 """
7238 v = int(self.black_point_compensation_cb.GetValue())
7239 if v != getcfg("profile.black_point_compensation"):
7240 self.profile_settings_changed()
7241 setcfg("profile.black_point_compensation", v)
7242 self.lut3d_check_bpc()
7243
7244 def black_point_correction_auto_handler(
7245 self, event: None | wx.Event = None
7246 ) -> None:
7247 """Handle changes to the black point correction auto checkbox.
7248
7249 Args:
7250 event (wx.Event, optional): The event that triggered the handler.
7251 """
7252 if event:
7253 auto = self.black_point_correction_auto_cb.GetValue()
7254 setcfg("calibration.black_point_correction.auto", int(auto))
7255 self.cal_changed()
7256 self.update_profile_name()
7257 else:
7258 auto = getcfg("calibration.black_point_correction.auto")
7259 self.black_point_correction_auto_cb.SetValue(bool(auto))
7260 show = (
7261 self.trc_ctrl.GetSelection() > 0
7262 and bool(getcfg("show_advanced_options"))
7263 and not auto
7264 )
7265 self.calpanel.Freeze()
7266 self.black_point_correction_ctrl.Show(show)
7267 self.black_point_correction_intctrl.Show(show)
7268 self.black_point_correction_intctrl_label.Show(show)
7269 self.calpanel.Layout()
7270 self.calpanel.Refresh()
7271 self.calpanel.Thaw()
7272
7273 def black_point_correction_ctrl_handler(self, event: wx.Event) -> None:
7274 """Handle changes to the black point correction controls.
7275
7276 Args:
7277 event (wx.Event): The event that triggered the handler.
7278 """
7279 debug_print(
7280 "[D] black_point_correction_ctrl_handler called for ID "
7281 f"{event.GetId()} {getevtobjname(event, self)} event type "
7282 f"{event.GetEventType()} {getevttype(event)}"
7283 )
7284 if event.GetId() == self.black_point_correction_intctrl.GetId():
7285 self.black_point_correction_ctrl.SetValue(
7286 self.black_point_correction_intctrl.GetValue()
7287 )
7288 else:
7289 self.black_point_correction_intctrl.SetValue(
7290 self.black_point_correction_ctrl.GetValue()
7291 )
7292 v = self.get_black_point_correction()
7293 if float(v) != getcfg("calibration.black_point_correction"):
7294 self.cal_changed()
7295 setcfg("calibration.black_point_correction", v)
7296 self.black_point_rate_ctrl.Enable(
7297 getcfg("calibration.black_point_correction") < 1
7298 and DEFAULTS["calibration.black_point_rate.enabled"]
7299 )
7300 self.black_point_rate_floatctrl.Enable(
7301 getcfg("calibration.black_point_correction") < 1
7302 and DEFAULTS["calibration.black_point_rate.enabled"]
7303 )
7304 self.update_profile_name()
7305
7306 def black_point_rate_ctrl_handler(self, event: wx.Event) -> None:
7307 """Handle changes to the black point rate controls.
7308
7309 Args:
7310 event (wx.Event): The event that triggered the handler.
7311 """
7312 debug_print(
7313 "[D] black_point_rate_ctrl_handler called for ID "
7314 f"{event.GetId()} {getevtobjname(event, self)} event type "
7315 f"{event.GetEventType()} {getevttype(event)}"
7316 )
7317 if event.GetId() == self.black_point_rate_floatctrl.GetId():
7318 self.black_point_rate_ctrl.SetValue(
7319 round(self.black_point_rate_floatctrl.GetValue() * 100)
7320 )
7321 else:
7322 self.black_point_rate_floatctrl.SetValue(
7323 self.black_point_rate_ctrl.GetValue() / 100.0
7324 )
7325 v = self.get_black_point_rate()
7326 if v != str(getcfg("calibration.black_point_rate")):
7327 self.cal_changed()
7328 setcfg("calibration.black_point_rate", v)
7329 self.update_profile_name()
7330
7331 def black_output_offset_ctrl_handler(self, event: wx.Event) -> None:
7332 """Handle changes to the black output offset controls.
7333
7334 Args:
7335 event (wx.Event): The event that triggered the handler.
7336 """
7337 debug_print(
7338 "[D] black_output_offset_ctrl_handler called for ID "
7339 f"{event.GetId()} {getevtobjname(event, self)} event type "
7340 f"{event.GetEventType()} {getevttype(event)}"
7341 )
7342 if event.GetId() == self.black_output_offset_intctrl.GetId():
7343 self.black_output_offset_ctrl.SetValue(
7344 self.black_output_offset_intctrl.GetValue()
7345 )
7346 else:
7347 self.black_output_offset_intctrl.SetValue(
7348 self.black_output_offset_ctrl.GetValue()
7349 )
7350 v = self.get_black_output_offset()
7351 if float(v) != getcfg("calibration.black_output_offset"):
7352 self.cal_changed()
7353 setcfg("calibration.black_output_offset", v)
7354 self.update_profile_name()
7355 self.update_trc_control()
7356 # self.show_trc_controls(True)
7357
7358 def visual_whitepoint_editor_handler(self, event: wx.Event) -> None:
7359 """Open the visual whitepoint editor.
7360
7361 Args:
7362 event (wx.Event): The event that triggered the editor opening.
7363 """
7364 if not self.setup_patterngenerator(self):
7365 return
7366 display_name = config.get_display_name(None, True)
7367 if display_name == "madVR":
7368 # Disable gamma ramp
7369 self.worker.madtpg.set_device_gamma_ramp(None)
7370 # Disable 3D LUT
7371 self.worker.madtpg.disable_3dlut()
7372 if self.worker.madtpg.is_fullscreen():
7373 # Leave fullscreen
7374 self.worker.madtpg.leave_fullscreen()
7375 elif display_name == "Prisma":
7376 # Disable 3D LUT
7377 try:
7378 self.worker.patterngenerator.disable_processing()
7379 except OSError as exception:
7380 show_result_dialog(exception)
7381 return
7382 pos = self.GetDisplay().ClientArea[:2]
7383 geometry = None
7384 profile = None
7385 print(" *************** display_name: ", display_name)
7386 if display_name in (
7387 "madVR",
7388 "Prisma",
7389 "Resolve",
7390 "Web @ localhost",
7391 ) or display_name.startswith("Chromecast "):
7392 patterngenerator = self.worker.patterngenerator
7393 else:
7394 patterngenerator = None
7395 display_no = config.get_display_number(getcfg("display.number") - 1)
7396 try:
7397 display = wx.Display(display_no)
7398 except Exception as exception:
7399 print(f"wx.Display({display_no}):", exception)
7400 else:
7401 pos = display.ClientArea[:2]
7402 profile = config.get_current_profile(True)
7403 if profile and profile.filename in self.presets:
7404 profile = None
7405 else:
7406 geometry = display.Geometry.Get() # Has to be tuple!
7407 display_name = display_name.replace("[PRIMARY]", lang.getstr("display.primary"))
7408 title = f"{display_name} - {lang.getstr('whitepoint.visual_editor')}"
7409 self.wpeditor = VisualWhitepointEditor(
7410 self,
7411 pos=pos,
7412 title=title,
7413 patterngenerator=patterngenerator,
7414 geometry=geometry,
7415 profile=profile,
7416 )
7417 if (
7418 patterngenerator
7419 and ChromeCastPatternGenerator
7420 and isinstance(patterngenerator, ChromeCastPatternGenerator)
7421 ):
7422 self.wpeditor.Bind(wx.EVT_CLOSE, self.patterngenerator_disconnect)
7423 self.wpeditor.RealCenterOnScreen()
7424 self.wpeditor.Show()
7425 self.wpeditor.Raise()
7426
7427 def patterngenerator_disconnect(self, event: wx.Event) -> None:
7428 """Disconnect the pattern generator client.
7429
7430 Args:
7431 event (wx.Event): The event that triggered the disconnection.
7432 """
7433 try:
7434 self.worker.patterngenerator.disconnect_client()
7435 except Exception as exception:
7436 print(exception)
7437 event.Skip()
7438
7439 def luminance_measure_handler(self, event: wx.Event) -> None:
7440 """Start measuring luminance.
7441
7442 Args:
7443 event (wx.Event): The event that triggered the luminance measurement.
7444 """
7445 if not self.setup_patterngenerator(self):
7446 return
7447 evtobjname = event.GetEventObject().Name
7448 color = wx.WHITE if evtobjname == "luminance_measure_btn" else wx.BLACK
7449 if self.worker.patterngenerator:
7450 self.worker.patterngenerator.send(
7451 tuple(v / 255.0 for v in color[:3]),
7452 (0, 0, 0),
7453 x=0.25,
7454 y=0.25,
7455 w=0.5,
7456 h=0.5,
7457 )
7458 frame = wx.Frame(
7459 self,
7460 title=lang.getstr("measureframe.title"),
7461 style=wx.DEFAULT_FRAME_STYLE
7462 | wx.FRAME_TOOL_WINDOW
7463 | wx.FRAME_FLOAT_ON_PARENT,
7464 )
7465 frame.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
7466 panel = wx.Panel(frame, size=(int(get_default_size()),) * 2)
7467 panel.SetBackgroundColour(color)
7468 btncls = ThemedGenButton if wx.Platform == "__WXMSW__" else wx.Button
7469 measure_btn = btncls(panel, label=lang.getstr("measure"), name=evtobjname)
7470 measure_btn.Bind(wx.EVT_BUTTON, self.ambient_measure_handler)
7471 panel.Sizer = wx.FlexGridSizer(2, 3)
7472 panel.Sizer.Add((1, 1))
7473 panel.Sizer.Add((1, 1))
7474 panel.Sizer.Add((1, 1))
7475 panel.Sizer.AddGrowableRow(0)
7476 panel.Sizer.Add((1, 1))
7477 panel.Sizer.Add(measure_btn, flag=wx.ALL | wx.ALIGN_CENTER, border=12)
7478 panel.Sizer.Add((1, 1))
7479 panel.Sizer.AddGrowableCol(0)
7480 panel.Sizer.AddGrowableCol(2)
7481 frame.Sizer = wx.BoxSizer(wx.VERTICAL)
7482 frame.Sizer.Add(panel, 1, flag=wx.EXPAND)
7483 frame.Sizer.SetSizeHints(frame)
7484 frame.Sizer.Layout()
7485 if (
7486 self.worker.patterngenerator
7487 and ChromeCastPatternGenerator
7488 and isinstance(self.worker.patterngenerator, ChromeCastPatternGenerator)
7489 ):
7490 frame.Bind(wx.EVT_CLOSE, self.patterngenerator_disconnect)
7491 frame.Show()
7492 self.measureframes.append(frame)
7493
7494 def ambient_measure_handler(self, event: wx.Event) -> None:
7495 """Start measuring ambient illumination.
7496
7497 Args:
7498 event (wx.Event): The event that triggered the measurement.
7499 """
7500 if not check_set_argyll_bin():
7501 return
7502 # Minimum Windows version: XP or Server 2003
7503 if sys.platform == "win32" and sys.getwindowsversion() < (5, 1):
7504 show_result_dialog(Error(lang.getstr("windows.version.unsupported")))
7505 return
7506 print("-" * 80)
7507 self.stop_timers()
7508 evtobjname = event.GetEventObject().Name
7509 lstr = "measure"
7510 if evtobjname == "visual_whitepoint_editor_measure_btn":
7511 interactive_frame = event.GetEventObject().TopLevelParent
7512 while not isinstance(interactive_frame, VisualWhitepointEditor):
7513 # Floated panel
7514 interactive_frame = interactive_frame.Parent
7515 elif evtobjname in ("luminance_measure_btn", "black_luminance_measure_btn"):
7516 interactive_frame = "luminance"
7517 else:
7518 interactive_frame = "ambient"
7519 lstr = "ambient.measure"
7520 print(lang.getstr(lstr))
7521 self.worker.interactive = interactive_frame not in ("ambient", "luminance")
7522 self.worker.start(
7523 self.ambient_measure_consumer,
7524 self.ambient_measure_producer,
7525 ckwargs={"evtobjname": evtobjname},
7526 wkwargs={"interactive_frame": interactive_frame},
7527 progress_title=lang.getstr("ambient.measure"),
7528 interactive_frame=interactive_frame,
7529 )
7530
7531 def ambient_measure_producer(
7532 self, interactive_frame: str | VisualWhitepointEditor
7533 ) -> str | Exception:
7534 """Process spotread output for ambient readings.
7535
7536 Args:
7537 interactive_frame (str | VisualWhitepointEditor): The frame or mode
7538 in which the ambient measurement is being taken. If it is a
7539 `VisualWhitepointEditor`, it indicates that the measurement is
7540 being taken in an interactive whitepoint adjustment context.
7541
7542 Returns:
7543 str | Exception: The result of the measurement command or an
7544 exception if an error occurs.
7545 """
7546 cmd = get_argyll_util("spotread")
7547 # Emissive if interactive_frame is not ambient or Ambient
7548 mode = "-e" if interactive_frame != "ambient" else "-a"
7549 args = ["-v", mode, "-x"]
7550 if getcfg("extra_args.spotread").strip():
7551 args += parse_argument_string(getcfg("extra_args.spotread"))
7552 result = self.worker.add_measurement_features(
7553 args, False, allow_nondefault_observer=True, ambient=mode == "-a"
7554 )
7555 if isinstance(result, Exception):
7556 return result
7557 return self.worker.exec_cmd(cmd, args, capture_output=True, skip_scripts=True)
7558
7559 def ambient_measure_consumer(
7560 self, result: None | str | Exception = None, evtobjname: None | str = None
7561 ) -> None:
7562 """Process ambient measurement results.
7563
7564 Args:
7565 result (None | str | Exception, optional): The result of the
7566 measurement command.
7567 evtobjname (None | str, optional): The name of the event object
7568 that triggered the measurement.
7569 """
7570 self.start_timers()
7571 if not result or isinstance(result, Exception):
7572 if getattr(self.worker, "subprocess", None):
7573 self.worker.quit_terminate_cmd()
7574 if isinstance(result, Exception):
7575 show_result_dialog(result, self)
7576 return
7577 result = re.sub(r"[^\t\n\r\x20-\x7f]", "", "".join(self.worker.output)).strip()
7578 if getcfg("whitepoint.colortemp.locus") == "T":
7579 K = re.search(r"Planckian temperature += (\d+(?:\.\d+)?)K", result, re.I) # noqa: N806
7580 else:
7581 K = re.search(r"Daylight temperature += (\d+(?:\.\d+)?)K", result, re.I) # noqa: N806
7582 XYZ = re.search(r"XYZ: (\d+(?:\.\d+)) (\d+(?:\.\d+)) (\d+(?:\.\d+))", result) # noqa: N806
7583 Yxy = re.search(r"Yxy: (\d+(?:\.\d+)) (\d+(?:\.\d+)) (\d+(?:\.\d+))", result) # noqa: N806
7584 Y = re.search( # noqa: N806
7585 r"Y: (\d+(?:\.\d+))", result
7586 ) # Monochrome, e.g. Spyder4/5
7587 lux = re.search(r"Ambient = (\d+(?:\.\d+)) Lux", result, re.I)
7588 if not result or (not K and not XYZ and not Yxy and not lux):
7589 show_result_dialog(Error(result + lang.getstr("failure")), self)
7590 return
7591 if K:
7592 K = float(K.groups()[0]) # noqa: N806
7593 print(lang.getstr("success"))
7594 set_whitepoint = evtobjname in (
7595 "visual_whitepoint_editor_measure_btn",
7596 "whitepoint_measure_btn",
7597 )
7598 set_ambient = evtobjname == "ambient_measure_btn"
7599 if (
7600 set_whitepoint
7601 and not set_ambient
7602 and lux
7603 and getcfg("show_advanced_options")
7604 and getcfg("trc", False) in ("709", "240")
7605 ):
7606 dlg = ConfirmDialog(
7607 self,
7608 msg=lang.getstr("ambient.set"),
7609 ok=lang.getstr("yes"),
7610 cancel=lang.getstr("no"),
7611 bitmap=get_icon(32, "dialog-question"),
7612 )
7613 set_ambient = dlg.ShowModal() == wx.ID_OK
7614 dlg.Destroy()
7615 if set_ambient:
7616 if lux:
7617 self.ambient_viewcond_adjust_textctrl.SetValue(float(lux.groups()[0]))
7618 self.ambient_viewcond_adjust_cb.SetValue(True)
7619 self.ambient_viewcond_adjust_ctrl_handler(
7620 CustomEvent(
7621 wx.EVT_CHECKBOX.evtType[0], self.ambient_viewcond_adjust_cb
7622 )
7623 )
7624 else:
7625 show_result_dialog(
7626 Error(lang.getstr("ambient.measure.light_level.missing")), self
7627 )
7628 if not set_whitepoint and K is not None and 4000 <= K <= 25000:
7629 dlg = ConfirmDialog(
7630 self,
7631 msg=lang.getstr("whitepoint.set"),
7632 ok=lang.getstr("yes"),
7633 cancel=lang.getstr("no"),
7634 bitmap=get_icon(32, "dialog-question"),
7635 )
7636 set_whitepoint = dlg.ShowModal() == wx.ID_OK
7637 dlg.Destroy()
7638 elif XYZ or Y:
7639 # White or black luminance or Monochrome, e.g. Spyder4/5
7640 Y = XYZ.group(2) if XYZ else Y.group(1) # noqa: N806
7641 Y = float(Y) # noqa: N806
7642 if evtobjname in ("luminance_measure_btn", "ambient_luminance_measure_btn"):
7643 # Force minimum luminance of 40 cd/m2 which should be suitable for
7644 # dark viewing. See (e.g.) research done by Mantiuk et al,
7645 # "Display Considerations for Night and Low-Illumination Viewing"
7646 # https://www.cl.cam.ac.uk/~rkm38/pdfs/mantiuk09dcnliv.pdf
7647 Y = max(Y, 40) # noqa: N806
7648 self.luminance_textctrl.SetValue(Y)
7649 self.luminance_ctrl_handler(
7650 CustomEvent(wx.EVT_CHOICE.evtType[0], self.luminance_ctrl)
7651 )
7652 elif evtobjname == "black_luminance_measure_btn":
7653 self.black_luminance_textctrl.SetValue(Y)
7654 self.black_luminance_ctrl_handler(
7655 CustomEvent(wx.EVT_CHOICE.evtType[0], self.black_luminance_ctrl)
7656 )
7657 if not set_whitepoint:
7658 return
7659 # Set whitepoint controls
7660 if evtobjname == "visual_whitepoint_editor_measure_btn" and XYZ:
7661 RGB = [ # noqa: N806
7662 getcfg("whitepoint.visual_editor.r"),
7663 getcfg("whitepoint.visual_editor.g"),
7664 getcfg("whitepoint.visual_editor.b"),
7665 ]
7666 if max(RGB) < 255:
7667 # Set luminance
7668 self.luminance_ctrl.SetSelection(1)
7669 self.luminance_textctrl.SetValue(float(XYZ.group(2)))
7670 else:
7671 self.luminance_ctrl.SetSelection(0)
7672 self.luminance_ctrl_handler(
7673 CustomEvent(wx.EVT_CHOICE.evtType[0], self.luminance_ctrl)
7674 )
7675 if not K and not Yxy:
7676 # Monochrome reading?
7677 show_result_dialog(
7678 Error(
7679 lang.getstr(
7680 "ambient.measure.color.unsupported",
7681 self.comport_ctrl.GetStringSelection(),
7682 )
7683 ),
7684 self,
7685 )
7686 return
7687 if K and self.whitepoint_ctrl.GetSelection() in (0, 1):
7688 self.whitepoint_ctrl.SetSelection(1)
7689 self.whitepoint_colortemp_textctrl.SetValue(str(K))
7690 elif Yxy:
7691 self.whitepoint_ctrl.SetSelection(2)
7692 Y, x, y = Yxy.groups() # noqa: N806
7693 self.whitepoint_x_textctrl.SetValue(round(float(x), 4))
7694 self.whitepoint_y_textctrl.SetValue(round(float(y), 4))
7695 self.whitepoint_ctrl_handler(
7696 CustomEvent(wx.EVT_CHOICE.evtType[0], self.whitepoint_ctrl)
7697 )
7698
7699 def ambient_viewcond_adjust_ctrl_handler(self, event: wx.Event) -> None:
7700 """Handle changes to the ambient view condition adjustment control.
7701
7702 Args:
7703 event (wx.Event): The event that triggered this handler.
7704 """
7705 if event.GetId() == self.ambient_viewcond_adjust_textctrl.GetId() and (
7706 not self.ambient_viewcond_adjust_cb.GetValue()
7707 or getcfg("calibration.ambient_viewcond_adjust.lux")
7708 == self.ambient_viewcond_adjust_textctrl.GetValue()
7709 ):
7710 event.Skip()
7711 return
7712 debug_print(
7713 "[D] ambient_viewcond_adjust_ctrl_handler called for ID "
7714 f"{event.GetId()} {getevtobjname(event, self)} event type "
7715 f"{event.GetEventType()} {getevttype(event)}"
7716 )
7717 if event.GetId() == self.ambient_viewcond_adjust_textctrl.GetId():
7718 if self.ambient_viewcond_adjust_textctrl.GetValue():
7719 self.ambient_viewcond_adjust_cb.SetValue(True)
7720 else:
7721 self.ambient_viewcond_adjust_cb.SetValue(False)
7722 if self.ambient_viewcond_adjust_cb.GetValue():
7723 self.ambient_viewcond_adjust_textctrl.Enable()
7724 v = self.ambient_viewcond_adjust_textctrl.GetValue()
7725 if v and (v < 0.000001 or v > sys.maxsize):
7726 wx.Bell()
7727 self.ambient_viewcond_adjust_textctrl.SetValue(
7728 getcfg("calibration.ambient_viewcond_adjust.lux")
7729 )
7730 if event.GetId() == self.ambient_viewcond_adjust_cb.GetId():
7731 self.ambient_viewcond_adjust_textctrl.SetFocus()
7732 else:
7733 self.ambient_viewcond_adjust_textctrl.Disable()
7734 v1 = int(self.ambient_viewcond_adjust_cb.GetValue())
7735 v2 = self.ambient_viewcond_adjust_textctrl.GetValue()
7736 if v1 != getcfg("calibration.ambient_viewcond_adjust") or v2 != getcfg(
7737 "calibration.ambient_viewcond_adjust.lux", False
7738 ):
7739 self.cal_changed()
7740 setcfg("calibration.ambient_viewcond_adjust", v1)
7741 setcfg("calibration.ambient_viewcond_adjust.lux", v2)
7742 self.update_profile_name()
7743 if event.GetEventType() == wx.EVT_KILL_FOCUS.evtType[0]:
7744 event.Skip()
7745
7746 def ambient_viewcond_adjust_info_handler(self, event: wx.Event) -> None:
7747 """Show information dialog about ambient view condition adjustment.
7748
7749 Args:
7750 event (wx.Event): The event that triggered this handler.
7751 """
7752 InfoDialog(
7753 self,
7754 msg=lang.getstr("calibration.ambient_viewcond_adjust.info"),
7755 ok=lang.getstr("ok"),
7756 bitmap=get_icon(32, "dialog-information"),
7757 log=False,
7758 )
7759
7760 def black_luminance_ctrl_handler(self, event: wx.Event) -> None:
7761 """Handle changes to the black luminance control.
7762
7763 Args:
7764 event (wx.Event): The event that triggered this handler.
7765
7766 Raises:
7767 ValueError: If the input value for black luminance is out of range.
7768 """
7769 if event.GetId() == self.black_luminance_textctrl.GetId() and (
7770 self.black_luminance_ctrl.GetSelection() != 1
7771 or getcfg("calibration.black_luminance")
7772 == self.black_luminance_textctrl.GetValue()
7773 or not self.black_luminance_ctrl.IsShown()
7774 ):
7775 event.Skip()
7776 return
7777 debug_print(
7778 "[D] black_luminance_ctrl_handler called for ID "
7779 f"{event.GetId()} {getevtobjname(event, self)} event type "
7780 f"{event.GetEventType()} {getevttype(event)}"
7781 )
7782 self.calpanel.Freeze()
7783 if self.black_luminance_ctrl.GetSelection() == 1: # cd/m2
7784 self.black_luminance_textctrl.Show()
7785 self.black_luminance_textctrl_label.Show()
7786 self.black_luminance_measure_btn.Show()
7787 try:
7788 v = self.black_luminance_textctrl.GetValue()
7789 if v < 0.000001 or v > 100000:
7790 raise ValueError
7791 except ValueError:
7792 wx.Bell()
7793 self.black_luminance_textctrl.SetValue(
7794 getcfg("calibration.black_luminance")
7795 )
7796 if (
7797 event.GetId() == self.black_luminance_ctrl.GetId()
7798 and self.black_luminance_ctrl.GetSelection() == 1
7799 ):
7800 self.black_luminance_textctrl.SetFocus()
7801 else:
7802 self.black_luminance_textctrl.Hide()
7803 self.black_luminance_textctrl_label.Hide()
7804 self.black_luminance_measure_btn.Hide()
7805 self.calpanel.Layout()
7806 self.calpanel.Refresh()
7807 self.calpanel.Thaw()
7808 v = self.get_black_luminance()
7809 if v != str(getcfg("calibration.black_luminance", False)):
7810 self.cal_changed()
7811 setcfg("calibration.black_luminance", v)
7812 self.update_profile_name()
7813 if event.GetEventType() == wx.EVT_KILL_FOCUS.evtType[0]:
7814 event.Skip()
7815
7816 def luminance_ctrl_handler(self, event: wx.Event) -> None:
7817 """Handle changes to the luminance control.
7818
7819 Args:
7820 event (wx.Event): The event that triggered this handler.
7821
7822 Raises:
7823 ValueError: If the input value for luminance is out of range.
7824 """
7825 if event.GetId() == self.luminance_textctrl.GetId() and (
7826 self.luminance_ctrl.GetSelection() != 1
7827 or getcfg("calibration.luminance") == self.luminance_textctrl.GetValue()
7828 ):
7829 event.Skip()
7830 return
7831 debug_print(
7832 "[D] luminance_ctrl_handler called for ID "
7833 f"{event.GetId()} {getevtobjname(event, self)} event type "
7834 f"{event.GetEventType()} {getevttype(event)}"
7835 )
7836 self.calpanel.Freeze()
7837 if self.luminance_ctrl.GetSelection() == 1: # cd/m2
7838 self.luminance_textctrl.Show()
7839 self.luminance_textctrl_label.Show()
7840 self.luminance_measure_btn.Show()
7841 self.ambient_luminance_measure_btn.Show()
7842 try:
7843 v = self.luminance_textctrl.GetValue()
7844 if v < 0.000001 or v > 100000:
7845 raise ValueError
7846 except ValueError:
7847 wx.Bell()
7848 self.luminance_textctrl.SetValue(getcfg("calibration.luminance"))
7849 if (
7850 event.GetId() == self.luminance_ctrl.GetId()
7851 and self.luminance_ctrl.GetSelection() == 1
7852 ):
7853 self.luminance_textctrl.SetFocus()
7854 else:
7855 self.luminance_textctrl.Hide()
7856 self.luminance_textctrl_label.Hide()
7857 self.luminance_measure_btn.Hide()
7858 self.ambient_luminance_measure_btn.Hide()
7859 self.calpanel.Layout()
7860 self.calpanel.Refresh()
7861 self.calpanel.Thaw()
7862 v = self.get_luminance()
7863 if v != str(getcfg("calibration.luminance", False)):
7864 self.cal_changed()
7865 setcfg("calibration.luminance", v)
7866 self.update_profile_name()
7867 if event.GetEventType() == wx.EVT_KILL_FOCUS.evtType[0]:
7868 event.Skip()
7869
7870 def whitepoint_colortemp_locus_ctrl_handler(self, event: wx.Event) -> None:
7871 """Handle changes to the whitepoint color temperature locus control.
7872
7873 Args:
7874 event (wx.Event): The event that triggered this handler.
7875 """
7876 debug_print(
7877 "[D] whitepoint_colortemp_locus_ctrl_handler called for ID "
7878 f"{event.GetId()} {getevtobjname(event, self)} event type "
7879 f"{event.GetEventType()} {getevttype(event)}"
7880 )
7881 v = self.get_whitepoint_locus()
7882 if v != getcfg("whitepoint.colortemp.locus"):
7883 setcfg("whitepoint.colortemp.locus", v)
7884 self.whitepoint_ctrl_handler(
7885 CustomEvent(wx.EVT_CHOICE.evtType[0], self.whitepoint_ctrl), False
7886 )
7887 self.profile_settings_changed()
7888 self.update_profile_name()
7889
7890 def whitepoint_ctrl_handler(
7891 self, event: wx.Event, cal_changed: None | bool = None
7892 ) -> None:
7893 """Handle changes to the whitepoint control.
7894
7895 Args:
7896 event (wx.Event): The event that triggered this handler.
7897 cal_changed (None | bool, optional): If set, indicates whether the
7898 calibration has changed.
7899
7900 Raises:
7901 ValueError: If the input values for color temperature or chromaticity
7902 coordinates are out of range.
7903 """
7904 if event.GetId() == self.whitepoint_colortemp_textctrl.GetId() and (
7905 self.whitepoint_ctrl.GetSelection() != 1
7906 or str(int(getcfg("whitepoint.colortemp")))
7907 == self.whitepoint_colortemp_textctrl.GetValue()
7908 ):
7909 event.Skip()
7910 return
7911 if event.GetId() == self.whitepoint_x_textctrl.GetId() and (
7912 self.whitepoint_ctrl.GetSelection() != 2
7913 or round(getcfg("whitepoint.x"), 4)
7914 == round(self.whitepoint_x_textctrl.GetValue(), 4)
7915 ):
7916 event.Skip()
7917 return
7918 if event.GetId() == self.whitepoint_y_textctrl.GetId() and (
7919 self.whitepoint_ctrl.GetSelection() != 2
7920 or round(getcfg("whitepoint.y"), 4)
7921 == round(self.whitepoint_y_textctrl.GetValue(), 4)
7922 ):
7923 event.Skip()
7924 return
7925 if (
7926 event.GetEventObject()
7927 and hasattr(event.GetEventObject(), "IsShown")
7928 and not event.GetEventObject().IsShown()
7929 ):
7930 event.Skip()
7931 return
7932 debug_print(
7933 "[D] whitepoint_ctrl_handler called for ID "
7934 f"{event.GetId()} {getevtobjname(event, self)} event type "
7935 f"{event.GetEventType()} {getevttype(event)}"
7936 )
7937 self.calpanel.Freeze()
7938 show_advanced_options = bool(getcfg("show_advanced_options"))
7939 if self.whitepoint_ctrl.GetSelection() == 2:
7940 # x,y chromaticity coordinates
7941 self.whitepoint_colortemp_locus_label.Hide()
7942 self.whitepoint_colortemp_locus_ctrl.Hide()
7943 self.whitepoint_colortemp_textctrl.Hide()
7944 self.whitepoint_colortemp_label.Hide()
7945 self.whitepoint_x_textctrl.Show()
7946 self.whitepoint_x_label.Show()
7947 self.whitepoint_y_textctrl.Show()
7948 self.whitepoint_y_label.Show()
7949 try:
7950 v = self.whitepoint_x_textctrl.GetValue()
7951 if v < 0 or v > 1:
7952 raise ValueError
7953 except ValueError:
7954 wx.Bell()
7955 self.whitepoint_x_textctrl.SetValue(round(getcfg("whitepoint.x"), 4))
7956 try:
7957 v = self.whitepoint_y_textctrl.GetValue()
7958 if v < 0 or v > 1:
7959 raise ValueError
7960 except ValueError:
7961 wx.Bell()
7962 self.whitepoint_y_textctrl.SetValue(round(getcfg("whitepoint.y"), 4))
7963 x = self.whitepoint_x_textctrl.GetValue()
7964 y = self.whitepoint_y_textctrl.GetValue()
7965 k = xyY2CCT(x, y, 1.0)
7966 if k:
7967 self.whitepoint_colortemp_textctrl.SetValue(
7968 str(stripzeros(math.ceil(k)))
7969 )
7970 else:
7971 self.whitepoint_colortemp_textctrl.SetValue("")
7972 if cal_changed is None and (
7973 not getcfg("whitepoint.colortemp", False)
7974 and x == getcfg("whitepoint.x")
7975 and y == getcfg("whitepoint.y")
7976 ):
7977 cal_changed = False
7978 setcfg("whitepoint.colortemp", None)
7979 setcfg("whitepoint.x", x)
7980 setcfg("whitepoint.y", y)
7981 setcfg("3dlut.whitepoint.x", x)
7982 setcfg("3dlut.whitepoint.y", y)
7983 if (
7984 event.GetId() == self.whitepoint_ctrl.GetId()
7985 and self.whitepoint_ctrl.GetSelection() == 2
7986 and not self.updatingctrls
7987 ):
7988 self.whitepoint_x_textctrl.SetFocus()
7989 elif self.whitepoint_ctrl.GetSelection() == 1:
7990 # Color temperature
7991 self.whitepoint_colortemp_locus_label.Show(show_advanced_options)
7992 self.whitepoint_colortemp_locus_ctrl.Show(show_advanced_options)
7993 self.whitepoint_colortemp_textctrl.Show()
7994 self.whitepoint_colortemp_label.Show()
7995 self.whitepoint_x_textctrl.Hide()
7996 self.whitepoint_x_label.Hide()
7997 self.whitepoint_y_textctrl.Hide()
7998 self.whitepoint_y_label.Hide()
7999 try:
8000 v = float(
8001 self.whitepoint_colortemp_textctrl.GetValue().replace(",", ".")
8002 )
8003 if v < 1000 or v > 15000:
8004 raise ValueError
8005 self.whitepoint_colortemp_textctrl.SetValue(str(stripzeros(v)))
8006 except ValueError:
8007 wx.Bell()
8008 self.whitepoint_colortemp_textctrl.SetValue(
8009 str(stripzeros(getcfg("whitepoint.colortemp")))
8010 )
8011 v = float(self.whitepoint_colortemp_textctrl.GetValue())
8012 if cal_changed is None and (
8013 getcfg("whitepoint.colortemp") == v
8014 and not getcfg("whitepoint.x", False)
8015 and not getcfg("whitepoint.y", False)
8016 ):
8017 cal_changed = False
8018 setcfg("whitepoint.colortemp", int(v))
8019 setcfg("whitepoint.x", None)
8020 setcfg("whitepoint.y", None)
8021 if (
8022 event.GetId() == self.whitepoint_ctrl.GetId()
8023 and self.whitepoint_ctrl.GetSelection() == 1
8024 and not self.updatingctrls
8025 ):
8026 self.whitepoint_colortemp_textctrl.SetFocus()
8027 self.whitepoint_colortemp_textctrl.SelectAll()
8028 else:
8029 # "As measured"
8030 self.whitepoint_colortemp_locus_label.Show(show_advanced_options)
8031 self.whitepoint_colortemp_locus_ctrl.Show(show_advanced_options)
8032 self.whitepoint_colortemp_textctrl.Hide()
8033 self.whitepoint_colortemp_label.Hide()
8034 self.whitepoint_x_textctrl.Hide()
8035 self.whitepoint_x_label.Hide()
8036 self.whitepoint_y_textctrl.Hide()
8037 self.whitepoint_y_label.Hide()
8038 if (
8039 cal_changed is None
8040 and not getcfg("whitepoint.colortemp", False)
8041 and not getcfg("whitepoint.x", False)
8042 and not getcfg("whitepoint.y", False)
8043 ):
8044 cal_changed = False
8045 setcfg("whitepoint.colortemp", None)
8046 self.whitepoint_colortemp_textctrl.SetValue(
8047 str(stripzeros(getcfg("whitepoint.colortemp")))
8048 )
8049 setcfg("whitepoint.x", None)
8050 setcfg("whitepoint.y", None)
8051 setcfg("3dlut.whitepoint.x", None)
8052 setcfg("3dlut.whitepoint.y", None)
8053 # Only show visual whitepoint editor if whitepoint set to chromaticity
8054 self.visual_whitepoint_editor_btn.Show(self.whitepoint_ctrl.GetSelection() == 2)
8055 self.whitepoint_measure_btn.Show(self.whitepoint_ctrl.GetSelection() > 0)
8056 self.calpanel.Layout()
8057 self.calpanel.Refresh()
8058 self.calpanel.Thaw()
8059 self.show_observer_ctrl()
8060 if self.whitepoint_ctrl.GetSelection() == 1:
8061 # Color temperature
8062 if getcfg("whitepoint.colortemp.locus") == "T":
8063 # Planckian locus
8064 xyY = planckianCT2xyY(getcfg("whitepoint.colortemp")) # noqa: N806
8065 else:
8066 # Daylight locus
8067 xyY = CIEDCCT2xyY(getcfg("whitepoint.colortemp")) # noqa: N806
8068 if xyY:
8069 self.whitepoint_x_textctrl.SetValue(round(xyY[0], 4))
8070 self.whitepoint_y_textctrl.SetValue(round(xyY[1], 4))
8071 setcfg("3dlut.whitepoint.x", xyY[0])
8072 setcfg("3dlut.whitepoint.y", xyY[1])
8073 else:
8074 self.whitepoint_x_textctrl.SetValue(0)
8075 self.whitepoint_y_textctrl.SetValue(0)
8076 setcfg("3dlut.whitepoint.x", None)
8077 setcfg("3dlut.whitepoint.y", None)
8078 if cal_changed is None and not self.updatingctrls:
8079 self.profile_settings_changed()
8080 self.update_profile_name()
8081 if event.GetEventType() == wx.EVT_KILL_FOCUS.evtType[0]:
8082 event.Skip()
8083 if (
8084 cal_changed is not False
8085 and not self.updatingctrls
8086 and not getcfg("3dlut.whitepoint.x", False)
8087 and not getcfg("3dlut.whitepoint.y", False)
8088 ):
8089 # Should change 3D LUT rendering intent to rel col?
8090 wx.CallAfter(self.check_3dlut_relcol_rendering_intent)
8091
8092 def trc_type_ctrl_handler(self, event: wx.Event) -> None:
8093 """Handle TRC type control events.
8094
8095 Args:
8096 event (wx.Event): The event triggered by the control.
8097 """
8098 debug_print(
8099 "[D] trc_type_ctrl_handler called for ID "
8100 f"{event.GetId()} {getevtobjname(event, self)} event type "
8101 f"{event.GetEventType()} {getevttype(event)}"
8102 )
8103 v = self.get_trc_type()
8104 if v != getcfg("trc.type"):
8105 setcfg("trc.type", v)
8106 self.cal_changed()
8107 self.update_profile_name()
8108 self.update_trc_control()
8109 self.show_trc_controls(True)
8110
8111 def trc_ctrl_handler(self, event: wx.Event, cal_changed: bool = True) -> None:
8112 """Handle TRC control events.
8113
8114 Args:
8115 event (wx.Event): The event triggered by the control.
8116 cal_changed (bool): Whether the calibration has changed.
8117 """
8118 if event.GetId() == self.trc_textctrl.GetId() and (
8119 self.trc_ctrl.GetSelection() not in (1, 4, 7)
8120 or stripzeros(getcfg("trc")) == stripzeros(self.trc_textctrl.GetValue())
8121 ):
8122 event.Skip()
8123 self.show_trc_controls(True)
8124 return
8125 debug_print(
8126 "[D] trc_ctrl_handler called for ID "
8127 f"{event.GetId()} {getevtobjname(event, self)} event type "
8128 f"{event.GetEventType()} {getevttype(event)}"
8129 )
8130 self.panel.Freeze()
8131 unload_cal = True
8132 if event.GetId() == self.trc_ctrl.GetId():
8133 bt1886 = (
8134 getcfg("trc.type") == "G"
8135 and getcfg("calibration.black_output_offset") == 0
8136 and getcfg("trc") == 2.4
8137 )
8138 if self.trc_ctrl.GetSelection() == 1:
8139 # Gamma 2.2
8140 self.trc_textctrl.SetValue("2.2")
8141 setcfg("trc.type", "g")
8142 self.trc_type_ctrl.SetSelection(0)
8143 setcfg("calibration.black_output_offset", 1)
8144 self.black_output_offset_ctrl.SetValue(100)
8145 self.black_output_offset_intctrl.SetValue(100)
8146 elif self.trc_ctrl.GetSelection() == 4:
8147 # BT.1886
8148 if not bt1886 and not getcfg("trc.backup", False):
8149 setcfg("trc.backup", self.trc_textctrl.GetValue().replace(",", "."))
8150 setcfg("trc.type.backup", getcfg("trc.type"))
8151 setcfg(
8152 "calibration.black_output_offset.backup",
8153 getcfg("calibration.black_output_offset"),
8154 )
8155 self.trc_textctrl.SetValue("2.4")
8156 setcfg("trc.type", "G")
8157 self.trc_type_ctrl.SetSelection(1)
8158 setcfg("calibration.black_output_offset", 0)
8159 self.black_output_offset_ctrl.SetValue(0)
8160 self.black_output_offset_intctrl.SetValue(0)
8161 elif self.trc_ctrl.GetSelection() not in (0, 1, 7):
8162 self.restore_trc_backup()
8163 if getcfg("calibration.black_output_offset.backup") is not None:
8164 setcfg(
8165 "calibration.black_output_offset",
8166 getcfg("calibration.black_output_offset.backup"),
8167 )
8168 setcfg("calibration.black_output_offset.backup", None)
8169 self.update_black_output_offset_ctrl()
8170 elif self.trc_ctrl.GetSelection() == 0:
8171 # As measured
8172 unload_cal = False
8173 if self.trc_ctrl.GetSelection() in (1, 4, 7):
8174 try:
8175 v = float(self.trc_textctrl.GetValue().replace(",", "."))
8176 if v == 0 or v > 10:
8177 raise ValueError
8178 except ValueError:
8179 wx.Bell()
8180 self.trc_textctrl.SetValue(str(getcfg("trc")))
8181 else:
8182 if str(v) != self.trc_textctrl.GetValue():
8183 self.trc_textctrl.SetValue(str(v))
8184 if (
8185 event.GetId() == self.trc_ctrl.GetId()
8186 and self.trc_ctrl.GetSelection() == 7
8187 ):
8188 # Have to use CallAfter, otherwise only part of the text will
8189 # be selected (wxPython bug?)
8190 wx.CallAfter(self.trc_textctrl.SetFocus)
8191 wx.CallLater(1, self.trc_textctrl.SelectAll)
8192 trc = self.get_trc()
8193 if cal_changed and trc != str(getcfg("trc")):
8194 if unload_cal:
8195 self.cal_changed()
8196 else:
8197 self.worker.options_dispcal = []
8198 self.profile_settings_changed()
8199 setcfg("trc", trc)
8200 if cal_changed:
8201 self.update_profile_name()
8202 if event.GetId() != self.trc_ctrl.GetId():
8203 self.update_trc_control()
8204 else:
8205 self.lut3d_update_apply_cal_control()
8206 self.update_adjustment_controls()
8207 self.show_trc_controls()
8208 self.calpanel.Layout()
8209 self.calpanel.Refresh()
8210 self.panel.Thaw()
8211 self.set_size(True)
8212 self.update_scrollbars()
8213 self.update_main_controls()
8214 if event.GetEventType() == wx.EVT_KILL_FOCUS.evtType[0]:
8215 event.Skip()
8216 if (
8217 trc in ("240", "709")
8218 and not (
8219 bool(int(getcfg("calibration.ambient_viewcond_adjust")))
8220 and getcfg("calibration.ambient_viewcond_adjust.lux")
8221 )
8222 and getcfg("trc.should_use_viewcond_adjust.show_msg")
8223 ):
8224 dlg = ConfirmDialog(
8225 self,
8226 msg=lang.getstr("trc.should_use_viewcond_adjust"),
8227 ok=lang.getstr("turn_on"),
8228 cancel=lang.getstr("cancel"),
8229 bitmap=get_icon(32, "dialog-information"),
8230 log=False,
8231 )
8232 chk = wx.CheckBox(dlg, -1, lang.getstr("dialog.do_not_show_again"))
8233 dlg.Bind(
8234 wx.EVT_CHECKBOX, self.should_use_viewcond_adjust_handler, id=chk.GetId()
8235 )
8236 dlg.sizer3.Add(chk, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
8237 dlg.sizer0.SetSizeHints(dlg)
8238 dlg.sizer0.Layout()
8239 if dlg.ShowModal() == wx.ID_OK:
8240 setcfg("calibration.ambient_viewcond_adjust", 1)
8241 self.ambient_viewcond_adjust_cb.SetValue(True)
8242 self.ambient_viewcond_adjust_textctrl.Enable()
8243 dlg.Destroy()
8244
8245 def restore_trc_backup(self) -> None:
8246 """Restore the TRC backup settings if available."""
8247 if getcfg("trc.backup"):
8248 setcfg("trc", getcfg("trc.backup"))
8249 setcfg("trc.backup", None)
8250 self.trc_textctrl.SetValue(str(getcfg("trc")))
8251 if getcfg("trc.type.backup"):
8252 setcfg("trc.type", getcfg("trc.type.backup"))
8253 setcfg("trc.type.backup", None)
8254 self.trc_type_ctrl.SetSelection(
8255 self.trc_types_ba.get(
8256 getcfg("trc.type"), self.trc_types_ba.get(DEFAULTS["trc.type"])
8257 )
8258 )
8259
8260 def should_use_viewcond_adjust_handler(self, event: wx.Event) -> None:
8261 """Handle the checkbox for showing the view condition adjustment message.
8262
8263 Args:
8264 event (wx.Event): The event that triggered this handler.
8265 """
8266 setcfg(
8267 "trc.should_use_viewcond_adjust.show_msg",
8268 int(not event.GetEventObject().GetValue()),
8269 )
8270
8271 def check_overwrite(self, ext: str = "", filename: None | str = None) -> bool:
8272 """Check if the profile file already exists and prompt the user.
8273
8274 Args:
8275 ext (str, optional): The file extension to use if no filename is
8276 provided.
8277 filename (None | str, optional): The name of the file to check. If
8278 None, the default profile name with the specified extension
8279 will be used.
8280
8281 Returns:
8282 bool: True if the file does not exist or the user confirms to
8283 overwrite, False if the user cancels the operation.
8284 """
8285 if not filename:
8286 filename = getcfg("profile.name.expanded") + ext
8287 dst_file = os.path.join(
8288 getcfg("profile.save_path"), getcfg("profile.name.expanded"), filename
8289 )
8290 else:
8291 dst_file = os.path.join(getcfg("profile.save_path"), filename)
8292 if os.path.exists(dst_file):
8293 dlg = ConfirmDialog(
8294 self,
8295 msg=lang.getstr("warning.already_exists", filename),
8296 ok=lang.getstr("ok"),
8297 cancel=lang.getstr("cancel"),
8298 bitmap=get_icon(32, "dialog-warning"),
8299 )
8300 result = dlg.ShowModal()
8301 dlg.Destroy()
8302 if result != wx.ID_OK:
8303 return False
8304 return True
8305
8306 def measure_uniformity_handler(self, event: wx.Event) -> None:
8307 """Start measuring display device uniformity.
8308
8309 Args:
8310 event (wx.Event): The event that triggered this handler.
8311 """
8312 dlg = ConfirmDialog(
8313 self,
8314 msg=lang.getstr("patch.layout.select"),
8315 ok=lang.getstr("ok"),
8316 cancel=lang.getstr("cancel"),
8317 bitmap=get_icon(32, "dialog-information"),
8318 )
8319 sizer = wx.BoxSizer(wx.HORIZONTAL)
8320 dlg.sizer3.Add(sizer, flag=wx.TOP, border=12)
8321 cols = wx.Choice(
8322 dlg, -1, choices=list(map(str, config.VALID_VALUES["uniformity.cols"]))
8323 )
8324 rows = wx.Choice(
8325 dlg, -1, choices=list(map(str, config.VALID_VALUES["uniformity.rows"]))
8326 )
8327 cols.SetStringSelection(str(getcfg("uniformity.cols")))
8328 rows.SetStringSelection(str(getcfg("uniformity.rows")))
8329 sizer.Add(cols, flag=wx.ALIGN_CENTER_VERTICAL)
8330 sizer.Add(
8331 wx.StaticText(dlg, -1, "x"),
8332 flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
8333 border=4,
8334 )
8335 sizer.Add(rows, flag=wx.ALIGN_CENTER_VERTICAL)
8336 dlg.sizer0.SetSizeHints(dlg)
8337 dlg.sizer0.Layout()
8338 dlg.ok.SetDefault()
8339 result = dlg.ShowModal()
8340 if result == wx.ID_OK:
8341 setcfg("uniformity.cols", int(cols.GetStringSelection()))
8342 setcfg("uniformity.rows", int(rows.GetStringSelection()))
8343 dlg.Destroy()
8344 if result != wx.ID_OK:
8345 return
8346 if isinstance(getattr(self.worker, "terminal", None), DisplayUniformityFrame):
8347 self.worker.terminal.Destroy()
8348 self.worker.terminal = None
8349 self.HideAll()
8350 self.worker.interactive = True
8351 self.worker.start(
8352 self.measure_uniformity_consumer,
8353 self.measure_uniformity_producer,
8354 resume=False,
8355 continue_next=False,
8356 interactive_frame="uniformity",
8357 )
8358
8359 def measure_uniformity_producer(self) -> None | str | Exception:
8360 """Produce the command to measure display device uniformity.
8361
8362 Returns:
8363 None | str | Exception: The result of the command execution, or
8364 None if the command could not be found.
8365 """
8366 cmd, args = get_argyll_util("spotread"), ["-v", "-e", "-T"]
8367 if cmd:
8368 result = self.worker.add_measurement_features(args, display=False, cmd=cmd)
8369 if isinstance(result, Exception):
8370 return result
8371 return self.worker.exec_cmd(cmd, args, skip_scripts=True)
8372 wx.CallAfter(
8373 show_result_dialog,
8374 Error(lang.getstr("argyll.util.not_found", "spotread")),
8375 self,
8376 )
8377 return None
8378
8379 def measure_uniformity_consumer(self, result: str | Exception) -> None:
8380 """Consume the results of the uniformity measurement.
8381
8382 Args:
8383 result (str | Exception): The result of the measurement command.
8384 """
8385 self.Show()
8386 if isinstance(result, Exception):
8387 show_result_dialog(result, self)
8388 if getcfg("dry_run"):
8389 return
8390 for _i, line in enumerate(self.worker.output):
8391 if line.startswith("spotread: Warning"):
8392 show_result_dialog(Warn(line.strip()), self)
8393
8394 def profile_share_get_meta_error(self, profile: ICCProfile) -> None | str:
8395 """Check for required metadata in profile to allow sharing.
8396
8397 The treshold for average deltaE 1976 is 1.0.
8398
8399 Arguments:
8400 profile (ICCProfile): The ICC profile to check.
8401
8402 Returns:
8403 None | str: An error message if the profile is not suitable for
8404 sharing, or None if the profile is suitable for sharing.
8405 """
8406 if "meta" not in profile.tags or not isinstance(profile.tags.meta, DictType):
8407 return lang.getstr("profile.share.meta_missing")
8408
8409 try:
8410 avg_dE76 = float(profile.tags.meta.getvalue("ACCURACY_dE76_avg")) # noqa: N806
8411 except (TypeError, ValueError):
8412 return lang.getstr("profile.share.meta_missing")
8413 threshold = 1.0
8414 if avg_dE76 and avg_dE76 > threshold:
8415 return lang.getstr(
8416 "profile.share.avg_dE_too_high",
8417 (f"{avg_dE76:.2f}", f"{threshold:.2f}"),
8418 )
8419 # Check for EDID metadata
8420 metadata = profile.tags.meta
8421 if "EDID_mnft" in metadata:
8422 # Check and correct manufacturer if necessary
8423 manufacturer = get_manufacturer_name(metadata["EDID_mnft"])
8424 if manufacturer:
8425 manufacturer = colord.quirk_manufacturer(manufacturer)
8426 if (
8427 "EDID_manufacturer" not in metadata
8428 or metadata["EDID_manufacturer"] != manufacturer
8429 ):
8430 metadata["EDID_manufacturer"] = manufacturer
8431 if (
8432 "EDID_model_id" not in metadata
8433 or ("EDID_model" not in metadata and metadata["EDID_model_id"] == "0")
8434 or "EDID_mnft_id" not in metadata
8435 or "EDID_mnft" not in metadata
8436 or "EDID_manufacturer" not in metadata
8437 or "OPENICC_automatic_generated" not in metadata
8438 ):
8439 return lang.getstr("profile.share.meta_missing")
8440 if (
8441 "B2A0" in profile.tags
8442 and isinstance(profile.tags.B2A0, LUT16Type)
8443 and profile.tags.B2A0.input_entries_count < 1024
8444 ):
8445 # 1024 is the Argyll value for a medium quality profile
8446 return lang.getstr("profile.share.b2a_resolution_too_low")
8447 return None
8448
8449 def profile_share_handler(self, event: wx.Event) -> None:
8450 """Share ICC profile via http://icc.opensuse.org.
8451
8452 Args:
8453 event (wx.Event): The event that triggered this handler.
8454 """
8455 # as mentioned in #194 the icc.opensuse.org is not working,
8456 # disabling this functionality temporarily
8457 InfoDialog(
8458 getattr(self, "modaldlg", self),
8459 msg="icc.opensuse.org is not working anymore\n"
8460 "This functionality is temporarily disabled.",
8461 ok=lang.getstr("ok"),
8462 bitmap=get_icon(32, "dialog-error"),
8463 )
8464 return
8465
8466 # Select profile
8467 profile = get_current_profile(include_display_profile=True)
8468 ignore = not profile or self.profile_share_get_meta_error(profile)
8469 kwargs = {
8470 "ignore_current_profile": ignore,
8471 "prefer_current_profile": isinstance(event.EventObject, wx.Button),
8472 "title": lang.getstr("profile.share"),
8473 }
8474 profile = self.select_profile(**kwargs)
8475 if not profile:
8476 return
8477
8478 # Check meta and profcheck data
8479 error = self.profile_share_get_meta_error(profile)
8480 if error:
8481 InfoDialog(
8482 getattr(self, "modaldlg", self),
8483 msg=error,
8484 ok=lang.getstr("ok"),
8485 bitmap=get_icon(32, "dialog-error"),
8486 )
8487 return
8488
8489 # Get options from profile
8490 options_dispcal, options_colprof = get_options_from_profile(profile)
8491 gamma = None
8492 for option in options_dispcal:
8493 if option.startswith(("g", "G")):
8494 option = option[1:]
8495 gamma = {
8496 "240": "SMPTE 240M",
8497 "709": "Rec. 709",
8498 "l": "L*",
8499 "s": "sRGB",
8500 }.get(option, f"Gamma {option}")
8501
8502 metadata = profile.tags.meta
8503 # Model will be shown in overview on http://icc.opensuse.org
8504 model = metadata.getvalue(
8505 "EDID_model",
8506 profile.getDeviceModelDescription() or metadata["EDID_model_id"],
8507 None,
8508 )
8509 description = model
8510 date = metadata.getvalue("EDID_date", "", None).split("-T")
8511 if len(date) == 2:
8512 year = int(date[0])
8513 week = int(date[1])
8514 date = datetime.date(int(year), 1, 1) + datetime.timedelta(weeks=week)
8515 description += " '" + strftime("%y", date.timetuple())
8516 if isinstance(profile.tags.get("vcgt"), VideoCardGammaType):
8517 vcgt = "linear VCGT" if profile.tags.vcgt.is_linear() else "VCGT"
8518 else:
8519 vcgt = "no VCGT"
8520 if vcgt:
8521 description += ", " + vcgt
8522 whitepoint = f"{round(XYZ2CCT(*list(profile.tags.wtpt.values()))):.0f}K"
8523 description += ", " + whitepoint
8524 description += f", {profile.tags.lumi.Y:0.f} cd/m²"
8525 if gamma:
8526 description += f", {gamma}"
8527 instrument = metadata.getvalue("MEASUREMENT_device")
8528 if instrument:
8529 for instrument_name in instruments:
8530 if instrument_name.lower() == instrument:
8531 instrument = instrument_name
8532 break
8533 description += ", " + instrument
8534 description += ", " + strftime("%Y-%m-%d", profile.dateTime.timetuple())
8535 dlg = ConfirmDialog(
8536 getattr(self, "modaldlg", self),
8537 title=lang.getstr("profile.share"),
8538 msg=lang.getstr("profile.share.enter_info"),
8539 ok=lang.getstr("upload"),
8540 cancel=lang.getstr("cancel"),
8541 bitmap=get_icon(32, APPNAME + "-profile-info"),
8542 alt=lang.getstr("save"),
8543 wrap=100,
8544 )
8545 # Description field
8546 boxsizer = wx.StaticBoxSizer(
8547 wx.StaticBox(dlg, -1, lang.getstr("description")), wx.VERTICAL
8548 )
8549 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
8550 if sys.platform not in ("darwin", "win32"):
8551 boxsizer.Add((1, 8))
8552 dlg.description_txt_ctrl = wx.TextCtrl(dlg, -1, description)
8553 boxsizer.Add(dlg.description_txt_ctrl, 1, flag=wx.ALL | wx.EXPAND, border=4)
8554 # Display properties
8555 boxsizer = wx.StaticBoxSizer(
8556 wx.StaticBox(dlg, -1, lang.getstr("display.properties")), wx.VERTICAL
8557 )
8558 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
8559 if sys.platform not in ("darwin", "win32"):
8560 boxsizer.Add((1, 8))
8561 box_gridsizer = wx.FlexGridSizer(0, 1, 0, 0)
8562 boxsizer.Add(box_gridsizer, 1, flag=wx.ALL, border=4)
8563 # Display panel surface type, connection
8564 gridsizer = wx.FlexGridSizer(0, 4, 4, 8)
8565 box_gridsizer.Add(gridsizer, 1, wx.ALIGN_LEFT)
8566 # Panel surface type
8567 gridsizer.Add(
8568 wx.StaticText(dlg, -1, lang.getstr("panel.surface")),
8569 1,
8570 flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
8571 )
8572 paneltypes = ["glossy", "matte"]
8573 dlg.panel_ctrl = wx.Choice(
8574 dlg, -1, choices=[""] + [lang.getstr(panel) for panel in paneltypes]
8575 )
8576 panel_surface = metadata.getvalue("SCREEN_surface", "")
8577 try:
8578 index = dlg.panel_ctrl.GetItems().index(lang.getstr(panel_surface))
8579 except ValueError:
8580 index = 0
8581 dlg.panel_ctrl.SetSelection(index)
8582 gridsizer.Add(
8583 dlg.panel_ctrl,
8584 1,
8585 flag=wx.RIGHT | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
8586 border=8,
8587 )
8588 # Connection type
8589 gridsizer.Add(
8590 wx.StaticText(dlg, -1, lang.getstr("display.connection.type")),
8591 1,
8592 flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
8593 )
8594 connections = ["dvi", "displayport", "hdmi", "internal", "vga"]
8595 dlg.connection_ctrl = wx.Choice(
8596 dlg, -1, choices=[lang.getstr(contype) for contype in connections]
8597 )
8598 connection_type = metadata.getvalue("CONNECTION_type", "dvi")
8599 try:
8600 index = dlg.connection_ctrl.GetItems().index(lang.getstr(connection_type))
8601 except ValueError:
8602 index = 0
8603 dlg.connection_ctrl.SetSelection(index)
8604 gridsizer.Add(
8605 dlg.connection_ctrl,
8606 1,
8607 flag=wx.RIGHT | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
8608 border=8,
8609 )
8610 if sys.platform == "darwin":
8611 display_settings_tabs = wx.Notebook(dlg, -1)
8612 else:
8613 display_settings_tabs = aui.AuiNotebook(dlg, -1, style=aui.AUI_NB_TOP)
8614 display_settings_tabs._agwFlags = aui.AUI_NB_TOP
8615 try:
8616 art = AuiBetterTabArt()
8617 if sys.platform == "win32":
8618 art.SetDefaultColours(aui.StepColour(dlg.BackgroundColour, 96))
8619 display_settings_tabs.SetArtProvider(art)
8620 except Exception as exception:
8621 print(exception)
8622 dlg.display_settings = display_settings_tabs
8623 # Column layout
8624 scale = getcfg("app.dpi") / config.get_default_dpi()
8625 scale = max(scale, 1)
8626 display_settings = (
8627 ( # 1st tab
8628 lang.getstr("osd") + ": " + lang.getstr("settings.basic"), # Tab title
8629 2, # Number of columns
8630 ( # 1st (left) column
8631 (
8632 ("preset", 150),
8633 ("brightness", 50),
8634 ("contrast", 50),
8635 ("trc.gamma", 50),
8636 ("blacklevel", 50),
8637 ("hue", 50),
8638 ),
8639 # 2nd (right) column
8640 (
8641 ("", 0),
8642 ("whitepoint.colortemp", 125),
8643 ("whitepoint", 50),
8644 ("saturation", 50),
8645 ),
8646 ),
8647 ),
8648 ( # 2nd tab
8649 lang.getstr("osd")
8650 + ": "
8651 + lang.getstr("settings.additional"), # Tab title
8652 3, # Number of columns
8653 ( # 1st (left) column
8654 (("hue", 50),),
8655 # 2nd (middle) column
8656 (("offset", 50),),
8657 # 3rd (right) column
8658 (("saturation", 50),),
8659 ),
8660 ),
8661 )
8662 display_settings_ctrls = []
8663 for tab_num, settings in enumerate(display_settings):
8664 panel = wx.Panel(display_settings_tabs, -1)
8665 panel.SetSizer(wx.BoxSizer(wx.VERTICAL))
8666 gridsizer = wx.FlexGridSizer(0, settings[1] * 2, 4, 12)
8667 panel.GetSizer().Add(gridsizer, 1, wx.ALL | wx.EXPAND, border=8)
8668 display_settings_tabs.AddPage(panel, settings[0])
8669 ctrls = []
8670 texts = []
8671 for column in settings[2]:
8672 for name, width in column:
8673 if name in ("whitepoint",):
8674 components = ("red", "green", "blue")
8675 elif tab_num == 1 and name in ("hue", "offset", "saturation"):
8676 components = (
8677 "red",
8678 "green",
8679 "blue",
8680 "cyan",
8681 "magenta",
8682 "yellow",
8683 )
8684 else:
8685 components = ("",)
8686 nameprefix = name
8687 for component in components:
8688 if component:
8689 name = nameprefix + "_" + component
8690 if name:
8691 label = name
8692 if "_" in label:
8693 label = label.split("_")
8694 for i, part in enumerate(label):
8695 label[i] = lang.getstr(part)
8696 label = " ".join(label)
8697 else:
8698 label = lang.getstr(label)
8699 text = wx.StaticText(panel, -1, label)
8700 ctrl = wx.TextCtrl(
8701 panel,
8702 -1,
8703 metadata.getvalue(
8704 "OSD_settings_{}".format(
8705 re.sub(r"[ .]", "_", name)
8706 ),
8707 "",
8708 ),
8709 size=(width * scale, -1),
8710 name=name,
8711 )
8712 else:
8713 text = (0, 0)
8714 ctrl = (0, 0)
8715 texts.append(text)
8716 ctrls.append(ctrl)
8717 display_settings_ctrls.append(ctrl)
8718 # Add the controls to the sizer
8719 rows = math.ceil(len(ctrls) / float(settings[1]))
8720 for row_num in range(rows):
8721 for column_num in range(settings[1]):
8722 ctrl_index = row_num + column_num * rows
8723 if ctrl_index < len(ctrls):
8724 gridsizer.Add(
8725 texts[ctrl_index],
8726 1,
8727 flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT,
8728 )
8729 gridsizer.Add(
8730 ctrls[ctrl_index],
8731 1,
8732 flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.RIGHT,
8733 border=4,
8734 )
8735 if isinstance(display_settings_tabs, aui.AuiNotebook):
8736 if sys.platform != "win32":
8737 display_settings_tabs.SetTabCtrlHeight(
8738 display_settings_tabs.GetTabCtrlHeight() + 2
8739 )
8740 height = display_settings_tabs.GetHeightForPageHeight(
8741 panel.Sizer.MinSize[1]
8742 )
8743 else:
8744 height = -1
8745 display_settings_tabs.SetMinSize((dlg.sizer3.MinSize[0] - 16, height))
8746 box_gridsizer.Add(
8747 display_settings_tabs, 1, flag=wx.TOP | wx.ALIGN_LEFT, border=8
8748 )
8749 # License field
8750 # dlg.sizer3.Add(wx.StaticText(dlg, -1, lang.getstr("license")), 1,
8751 # flag=wx.TOP | wx.ALIGN_LEFT, border=12)
8752 # dlg.license_ctrl = wx.Choice(dlg, -1,
8753 # choices=["http://www.color.org/registry/icc_license_2011.txt",
8754 # "http://www.gzip.org/zlib/zlib_license.html"])
8755 # dlg.license_ctrl.SetSelection(0)
8756 # sizer4 = wx.BoxSizer(wx.HORIZONTAL)
8757 # dlg.sizer3.Add(sizer4, 1,
8758 # flag=wx.TOP | wx.ALIGN_LEFT, border=4)
8759 # sizer4.Add(dlg.license_ctrl, 1,
8760 # flag=wx.RIGHT | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
8761 # border=8)
8762 # License link button
8763 # dlg.license_link_ctrl = wx.BitmapButton(dlg, -1,
8764 # get_icon(16, "dialog-information"),
8765 # style=wx.NO_BORDER)
8766 # dlg.license_link_ctrl.SetToolTipString(lang.getstr("license"))
8767 # dlg.Bind(wx.EVT_BUTTON,
8768 # lambda event: launch_file(dlg.license_ctrl.GetValue()),
8769 # dlg.license_link_ctrl)
8770 # sizer4.Add(dlg.license_link_ctrl, flag=wx.ALIGN_LEFT |
8771 # wx.ALIGN_CENTER_VERTICAL)
8772 # Link to ICC Profile Taxi service
8773 hyperlink = HyperLinkCtrl(
8774 dlg.buttonpanel,
8775 -1,
8776 label="icc.opensuse.org",
8777 URL="https://icc.opensuse.org/",
8778 )
8779 dlg.sizer2.Insert(
8780 0,
8781 hyperlink,
8782 flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
8783 border=round(32 + 12),
8784 )
8785 dlg.description_txt_ctrl.SetFocus()
8786 dlg.sizer0.SetSizeHints(dlg)
8787 dlg.sizer0.Layout()
8788 dlg.Center()
8789 result = dlg.ShowModal()
8790 if result == wx.ID_CANCEL:
8791 return
8792 # Get meta prefix
8793 prefixes = (metadata.getvalue("prefix", "", None) or "CONNECTION_").split(",")
8794 if "CONNECTION_" not in prefixes:
8795 prefixes.append("CONNECTION_")
8796 # Update meta
8797 panel = dlg.panel_ctrl.GetSelection()
8798 if panel > 0:
8799 metadata["SCREEN_surface"] = paneltypes[panel - 1]
8800 if "SCREEN_" not in prefixes:
8801 prefixes.append("SCREEN_")
8802 # Update meta
8803 metadata["CONNECTION_type"] = connections[dlg.connection_ctrl.GetSelection()]
8804 for ctrl in display_settings_ctrls:
8805 if isinstance(ctrl, wx.TextCtrl) and ctrl.GetValue().strip():
8806 metadata["OSD_settings_{}".format(re.sub(r"[ .]", "_", ctrl.Name))] = (
8807 ctrl.GetValue().strip()
8808 )
8809 if "OSD_" not in prefixes:
8810 prefixes.append("OSD_")
8811 # Set meta prefix
8812 metadata["prefix"] = ",".join(prefixes)
8813 # Calculate profile ID
8814 profile.calculate_id()
8815 # Save profile
8816 try:
8817 profile.write()
8818 except OSError as exception:
8819 show_result_dialog(exception, self)
8820 if result != wx.ID_OK:
8821 return
8822 # Get profile data
8823 data = profile.data
8824 # Add metadata which should not be reflected in profile
8825 metadata["model"] = model
8826 metadata["vcgt"] = int("vcgt" in profile.tags)
8827 # Upload
8828 params = {
8829 "description": dlg.description_txt_ctrl.GetValue(),
8830 # "licence": dlg.license_ctrl.GetValue()}
8831 "licence": "http://www.color.org/registry/icc_license_2011.txt",
8832 }
8833 files = [
8834 (
8835 "metadata",
8836 "metadata.json",
8837 '{"org":{"freedesktop":{"openicc":{"device":{"monitor":['
8838 f"{metadata.to_json()}]}}}}}}}}}}",
8839 ),
8840 ("profile", "profile.icc", data),
8841 ]
8842 self.worker.interactive = False
8843 self.worker.start(
8844 self.profile_share_consumer,
8845 http_request,
8846 ckwargs={},
8847 wkwargs={
8848 "domain": DOMAIN if TEST else "icc.opensuse.org",
8849 "request_type": "POST",
8850 "path": "/print_r_post.php" if TEST else "/upload",
8851 "params": params,
8852 "files": files,
8853 },
8854 progress_msg=lang.getstr("profile.share"),
8855 stop_timers=False,
8856 cancelable=False,
8857 show_remaining_time=False,
8858 fancy=False,
8859 )
8860
8861 def profile_share_consumer(
8862 self, result: bool | str | Exception, parent: None | wx.Window = None
8863 ) -> None:
8864 """This function receives the response from the profile upload.
8865
8866 Args:
8867 result (bool | str | Exception): The result of the upload
8868 operation. If the upload was successful, it will be a string
8869 containing the URL of the uploaded profile. If it failed, it
8870 will be False or an Exception.
8871 parent (None | wx.Window, optional): The parent window for the
8872 dialog. If not provided, it defaults to the current modal
8873 dialog or the main window of the application.
8874 """
8875 if result is False:
8876 return
8877
8878 parent = parent or getattr(self, "modaldlg", self)
8879 dlg = InfoDialog(
8880 parent,
8881 msg=lang.getstr("profile.share.success"),
8882 ok=lang.getstr("ok"),
8883 bitmap=get_icon(32, "dialog-information"),
8884 show=False,
8885 )
8886 # Link to ICC Profile Taxi service
8887 hyperlink = HyperLinkCtrl(
8888 dlg.buttonpanel,
8889 -1,
8890 label="icc.opensuse.org",
8891 URL="https://icc.opensuse.org/",
8892 )
8893 border = dlg.sizer3.MinSize[0] - dlg.sizer2.MinSize[0] - hyperlink.Size[0]
8894 border = max(border, 24)
8895 dlg.sizer2.Insert(
8896 0,
8897 hyperlink,
8898 flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
8899 border=border,
8900 )
8901 dlg.sizer2.Insert(0, (44, 1))
8902 dlg.sizer0.SetSizeHints(dlg)
8903 dlg.sizer0.Layout()
8904 dlg.ok.SetDefault()
8905 dlg.ShowModalThenDestroy()
8906
8907 def install_argyll_instrument_conf(
8908 self, event: None | wx.Event = None, uninstall: bool = False
8909 ) -> None:
8910 """Install or uninstall Argyll instrument configuration files.
8911
8912 Args:
8913 event (None | wx.Event, optional): The event that triggered this
8914 handler.
8915 uninstall (bool, optional): If True, uninstall the configuration
8916 files instead of installing them.
8917 """
8918 filenames = None
8919 cmd = "cp"
8920
8921 if uninstall:
8922 if filenames := get_argyll_instrument_config("installed"):
8923 dlgs = []
8924 dlg = ConfirmDialog(
8925 self,
8926 title=lang.getstr(
8927 "argyll.instrument.configuration_files.uninstall"
8928 ),
8929 msg=lang.getstr("dialog.confirm_uninstall"),
8930 ok=lang.getstr("uninstall"),
8931 cancel=lang.getstr("cancel"),
8932 bitmap=get_icon(32, "dialog-warning"),
8933 )
8934 dlgs.append(dlg)
8935 dlg.sizer3.Add((0, 8))
8936 chks = []
8937 for filename in filenames:
8938 dlg.sizer3.Add((0, 4))
8939 chk = wx.CheckBox(dlg, -1, filename)
8940 chks.append(chk)
8941 chk.SetValue(True)
8942 dlg.sizer3.Add(chk, flag=wx.ALIGN_LEFT)
8943 dlg.sizer0.SetSizeHints(dlg)
8944 dlg.sizer0.Layout()
8945 dlg.Center()
8946 result = dlg.ShowModal()
8947 filenames = []
8948 if result == wx.ID_OK:
8949 for chk in chks:
8950 if chk.GetValue():
8951 filenames.append(chk.Label)
8952 for filename in filenames:
8953 if os.path.dirname(filename) == "/lib/udev/rules.d":
8954 dlg = ConfirmDialog(
8955 self,
8956 title=lang.getstr(
8957 "argyll.instrument.configuration_files.uninstall"
8958 ),
8959 msg=lang.getstr("warning.system_file", filename),
8960 ok=lang.getstr("continue"),
8961 cancel=lang.getstr("cancel"),
8962 bitmap=get_icon(32, "dialog-warning"),
8963 )
8964 dlgs.append(dlg)
8965 result = dlg.ShowModal()
8966 if result != wx.ID_OK:
8967 break
8968 for dlg in dlgs:
8969 dlg.Destroy()
8970 if not filenames or result != wx.ID_OK:
8971 return
8972 cmd = "rm"
8973
8974 result = self.worker.authenticate(which(cmd))
8975 if result not in (True, None):
8976 if isinstance(result, Exception):
8977 show_result_dialog(result, self)
8978 return
8979 self.worker.start(
8980 self.install_argyll_instrument_conf_consumer,
8981 self.worker.install_argyll_instrument_conf,
8982 ckwargs={"uninstall": uninstall},
8983 wkwargs={"uninstall": uninstall, "filenames": filenames},
8984 fancy=False,
8985 )
8986
8987 def install_argyll_instrument_conf_consumer(
8988 self, result: bool | Exception, uninstall: bool = False
8989 ) -> None:
8990 """Consumer for installing/uninstalling Argyll instrument configuration files.
8991
8992 Args:
8993 result (bool or Exception): The result of the installation or
8994 uninstallation process.
8995 uninstall (bool): If True, the process is an uninstallation.
8996 """
8997 if isinstance(result, Exception):
8998 show_result_dialog(result, self)
8999 elif result is False:
9000 show_result_dialog(Error("".join(self.worker.errors)), self)
9001 else:
9002 self.update_menus()
9003 if uninstall:
9004 msgid = "argyll.instrument.configuration_files.uninstall.success"
9005 else:
9006 msgid = "argyll.instrument.configuration_files.install.success"
9007 show_result_dialog(Info(lang.getstr(msgid)), self)
9008
9009 def install_argyll_instrument_drivers(
9010 self, event: None | wx.Event = None, uninstall: bool = False
9011 ) -> None:
9012 """Install or uninstall Argyll instrument drivers.
9013
9014 Args:
9015 event (wx.Event, optional): The event that triggered this handler.
9016 uninstall (bool, optional): If True, uninstall the drivers instead
9017 of installing them.
9018 """
9019 if uninstall:
9020 title = "argyll.instrument.drivers.uninstall"
9021 msg = "argyll.instrument.drivers.uninstall.confirm"
9022 ok = "continue"
9023 else:
9024 title = "argyll.instrument.drivers.install"
9025 msg = "argyll.instrument.drivers.install.confirm"
9026 ok = "download_install"
9027 dlg = ConfirmDialog(
9028 self,
9029 title=lang.getstr(title),
9030 msg=lang.getstr(msg),
9031 ok=lang.getstr(ok).replace("&", "&&"),
9032 cancel=lang.getstr("cancel"),
9033 bitmap=get_icon(32, "dialog-information"),
9034 )
9035 dlg.launch_devman = wx.CheckBox(dlg, -1, lang.getstr("device_manager.launch"))
9036 dlg.launch_devman.SetValue(uninstall)
9037 dlg.sizer3.Add(dlg.launch_devman, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
9038 if hasattr(dlg.ok, "SetAuthNeeded"):
9039 dlg.ok.SetAuthNeeded(True)
9040 dlg.sizer0.SetSizeHints(dlg)
9041 dlg.sizer0.Layout()
9042 result = dlg.ShowModal()
9043 launch_devman = dlg.launch_devman.IsChecked()
9044 dlg.Destroy()
9045 if result != wx.ID_OK:
9046 return
9047 print("-" * 80)
9048 print(lang.getstr(title))
9049 self.worker.start(
9050 lambda result: (
9051 show_result_dialog(result, self)
9052 if isinstance(result, Exception)
9053 else self.check_update_controls(True)
9054 ),
9055 self.worker.install_argyll_instrument_drivers,
9056 wargs=(uninstall, launch_devman),
9057 fancy=False,
9058 )
9059
9060 def uninstall_argyll_instrument_conf(self, event: wx.Event = None) -> None:
9061 """Uninstall Argyll instrument configuration files.
9062
9063 Args:
9064 event (wx.Event, optional): The event that triggered this handler.
9065 """
9066 self.install_argyll_instrument_conf(uninstall=True)
9067
9068 def uninstall_argyll_instrument_drivers(
9069 self, event: None | wx.Event = None
9070 ) -> None:
9071 """Uninstall Argyll instrument drivers.
9072
9073 Args:
9074 event (wx.Event, optional): The event that triggered this handler.
9075 """
9076 self.install_argyll_instrument_drivers(uninstall=True)
9077
9078 def install_profile_handler(
9079 self,
9080 event: None | wx.Event = None,
9081 profile_path: None | str = None,
9082 install_3dlut: None | bool = None,
9083 ) -> None:
9084 """Install a profile.
9085
9086 Show an error dialog if the profile is invalid or unsupported (only
9087 'mntr' RGB profiles are allowed).
9088
9089 Args:
9090 event (wx.Event): The event that triggered this handler.
9091 profile_path (str, optional): Path to the profile to install. If
9092 not provided, it will use the path from the configuration.
9093 install_3dlut (bool, optional): Whether to install a 3D LUT. If
9094 not provided, it will use the current state of the LUT3D
9095 settings panel.
9096 """
9097 if not check_set_argyll_bin():
9098 return
9099 if profile_path is None:
9100 profile_path = getcfg("calibration.file", False)
9101 if profile_path:
9102 result = check_file_isfile(profile_path)
9103 if isinstance(result, Exception):
9104 show_result_dialog(result, self)
9105 else:
9106 result = False
9107 if install_3dlut is None:
9108 install_3dlut = self.lut3d_settings_panel.IsShown()
9109 if isinstance(result, Exception) or not result:
9110 return
9111 try:
9112 profile = ICCProfile(profile_path)
9113 except (OSError, ICCProfileInvalidError):
9114 InfoDialog(
9115 self,
9116 msg=lang.getstr("profile.invalid") + "\n" + profile_path,
9117 ok=lang.getstr("ok"),
9118 bitmap=get_icon(32, "dialog-error"),
9119 )
9120 return
9121
9122 if profile.profileClass != b"mntr" or profile.colorSpace != b"RGB":
9123 InfoDialog(
9124 self,
9125 msg=lang.getstr(
9126 "profile.unsupported",
9127 (
9128 profile.profileClass.decode("utf-8"),
9129 profile.colorSpace.decode("utf-8"),
9130 ),
9131 )
9132 + "\n"
9133 + profile_path,
9134 ok=lang.getstr("ok"),
9135 bitmap=get_icon(32, "dialog-error"),
9136 )
9137 return
9138 setcfg("calibration.file.previous", getcfg("calibration.file", False))
9139 self.profile_finish(
9140 True,
9141 profile_path=profile_path,
9142 skip_scripts=True,
9143 allow_show_log=False,
9144 install_3dlut=install_3dlut,
9145 )
9146
9147 def select_install_profile_handler(self, event: wx.Event) -> None:
9148 """Show a dialog for user to select a profile for installation.
9149
9150 Args:
9151 event (wx.Event): The event that triggered this handler.
9152 """
9153 default_dir, default_file = get_verified_path("last_icc_path")
9154 dlg = wx.FileDialog(
9155 self,
9156 lang.getstr("install_display_profile"),
9157 defaultDir=default_dir,
9158 defaultFile=default_file,
9159 wildcard=lang.getstr("filetype.icc") + "|*.icc;*.icm",
9160 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
9161 )
9162 dlg.Center(wx.BOTH)
9163 result = dlg.ShowModal()
9164 path = dlg.GetPath()
9165 dlg.Destroy()
9166 if result == wx.ID_OK:
9167 setcfg("last_icc_path", path)
9168 setcfg("last_cal_or_icc_path", path)
9169 self.install_profile_handler(profile_path=path, install_3dlut=False)
9170
9171 def load_profile_cal_handler(self, event: wx.Event) -> None:
9172 """Prompt user to select a profile for loading calibration (vcgt).
9173
9174 Args:
9175 event (wx.Event): The event that triggered this handler.
9176 """
9177 if not check_set_argyll_bin():
9178 return
9179 default_dir, default_file = get_verified_path("last_cal_or_icc_path")
9180 dlg = wx.FileDialog(
9181 self,
9182 lang.getstr("calibration.load_from_cal_or_profile"),
9183 defaultDir=default_dir,
9184 defaultFile=default_file,
9185 wildcard=lang.getstr("filetype.cal_icc") + "|*.cal;*.icc;*.icm",
9186 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
9187 )
9188 dlg.Center(wx.BOTH)
9189 result = dlg.ShowModal()
9190 path = dlg.GetPath()
9191 dlg.Destroy()
9192 if result == wx.ID_OK:
9193 if not os.path.exists(path):
9194 InfoDialog(
9195 self,
9196 msg=lang.getstr("file.missing", path),
9197 ok=lang.getstr("ok"),
9198 bitmap=get_icon(32, "dialog-error"),
9199 )
9200 return
9201 setcfg("last_cal_or_icc_path", path)
9202 verbose_print(lang.getstr("calibration.loading"))
9203 verbose_print(path)
9204 if os.path.splitext(path)[1].lower() in (".icc", ".icm"):
9205 try:
9206 profile = ICCProfile(path)
9207 except (OSError, ICCProfileInvalidError):
9208 verbose_print(lang.getstr("failure"))
9209 InfoDialog(
9210 self,
9211 msg=lang.getstr("profile.invalid") + "\n" + path,
9212 ok=lang.getstr("ok"),
9213 bitmap=get_icon(32, "dialog-error"),
9214 )
9215 return
9216 setcfg("last_icc_path", path)
9217 if (
9218 self.install_cal(
9219 capture_output=True,
9220 profile_path=path,
9221 skip_scripts=True,
9222 silent=not getcfg("dry_run"),
9223 title=lang.getstr("calibration.load_from_profile"),
9224 )
9225 is True
9226 ):
9227 self.lut_viewer_load_lut(profile=profile)
9228 verbose_print(lang.getstr("success"))
9229 elif not getcfg("dry_run"):
9230 verbose_print(lang.getstr("failure"))
9231 InfoDialog(
9232 self,
9233 msg=lang.getstr("calibration.load_error") + "\n" + path,
9234 ok=lang.getstr("ok"),
9235 bitmap=get_icon(32, "dialog-error"),
9236 )
9237 else:
9238 setcfg("last_cal_path", path)
9239 if (
9240 self.install_cal(
9241 capture_output=True,
9242 cal=path,
9243 skip_scripts=True,
9244 silent=not getcfg("dry_run"),
9245 title=lang.getstr("calibration.load_from_cal"),
9246 )
9247 is True
9248 ):
9249 self.lut_viewer_load_lut(profile=cal_to_fake_profile(path))
9250 verbose_print(lang.getstr("success"))
9251 elif not getcfg("dry_run"):
9252 verbose_print(lang.getstr("failure"))
9253
9254 def preview_handler(
9255 self, event: None | wx.Event = None, preview: bool = False
9256 ) -> None:
9257 """Preview profile calibration (vcgt).
9258
9259 Toggle between profile curves and previous calibration curves.
9260
9261 Args:
9262 event (wx.Event, optional): The event that triggered this handler.
9263 preview (bool, optional): Whether to use the preview checkbox value.
9264 """
9265 if preview or self.preview.GetValue():
9266 cal = self.cal
9267 else:
9268 cal = getcfg("calibration.file.previous")
9269 if self.cal == cal:
9270 cal = False
9271 elif not cal:
9272 cal = True
9273 if cal is False: # linear
9274 profile = None
9275 elif cal is True: # display profile
9276 profile = get_display_profile()
9277 if not profile:
9278 cal = False
9279 elif cal.lower().endswith(".icc") or cal.lower().endswith(".icm"):
9280 try:
9281 profile = ICCProfile(cal)
9282 except (OSError, ICCProfileInvalidError) as exception:
9283 show_result_dialog(exception, self)
9284 profile = None
9285 else:
9286 profile = cal_to_fake_profile(cal)
9287 if profile:
9288 verbose_print(lang.getstr("calibration.loading"))
9289 if profile.filename:
9290 verbose_print(profile.filename)
9291 else:
9292 verbose_print(lang.getstr("calibration.resetting"))
9293 if (
9294 self.install_cal(
9295 capture_output=True,
9296 cal=cal,
9297 skip_scripts=True,
9298 silent=True,
9299 title=lang.getstr("calibration.load_from_cal_or_profile"),
9300 )
9301 is True
9302 ):
9303 self.lut_viewer_load_lut(profile=profile)
9304 verbose_print(lang.getstr("success"))
9305 else:
9306 verbose_print(lang.getstr("failure"))
9307
9308 def profile_load_on_login_handler(self, event: None | wx.Event = None) -> None:
9309 """Handle the profile load on login checkbox event.
9310
9311 Args:
9312 event (None | wx.Event, optional): The event that triggered this
9313 handler.
9314 """
9315 setcfg("profile.load_on_login", int(self.profile_load_on_login.GetValue()))
9316 if sys.platform == "win32" and sys.getwindowsversion() >= (6, 1):
9317 self.profile_load_on_login.Enable(
9318 is_superuser() or not util_win.calibration_management_isenabled()
9319 )
9320 self.profile_load_by_os.Enable(
9321 is_superuser() and self.profile_load_on_login.GetValue()
9322 )
9323 if (
9324 not self.profile_load_on_login.GetValue()
9325 and self.profile_load_by_os.GetValue()
9326 and is_superuser()
9327 ):
9328 self.profile_load_by_os.SetValue(False)
9329 self.profile_load_by_os_handler()
9330 # Update profile loader config
9331 if sys.platform == "win32" and event:
9332 prev = self.send_command("apply-profiles", "getcfg profile.load_on_login")
9333 if prev:
9334 with contextlib.suppress(Exception):
9335 prev = int(prev.split()[-1])
9336 result = self.send_command(
9337 "apply-profiles",
9338 "setcfg profile.load_on_login {:.0f}".format(
9339 getcfg("profile.load_on_login")
9340 ),
9341 )
9342 if result == "ok" and getcfg("profile.load_on_login") != prev:
9343 if getcfg("profile.load_on_login"):
9344 lstr = "calibration.preserve"
9345 else:
9346 lstr = "profile_loader.disable"
9347 self.send_command("apply-profiles", f"notify '{lang.getstr(lstr)}'")
9348 else:
9349 # Profile loader not running? Fall back to config files
9350
9351 # 1. Remember current config
9352 items = config.CFG.items(config.configparser.DEFAULTSECT)
9353
9354 # 2. Read in profile loader config. Result is unison of current
9355 # config and profile loader config.
9356 initcfg("apply-profiles", force_load=True)
9357
9358 # 3. Restore current config (but do not override profile loader
9359 # options)
9360 for name, value in items:
9361 if not name.startswith("profile_loader"):
9362 config.CFG.set(config.configparser.DEFAULTSECT, name, value)
9363
9364 # 4. Write profile loader config with values updated from
9365 # current config
9366 writecfg(
9367 module="apply-profiles",
9368 options=("profile.load_on_login", "profile_loader"),
9369 )
9370
9371 # 5. Remove profile loader options from current config
9372 for name in DEFAULTS:
9373 if name.startswith("profile_loader"):
9374 setcfg(name, None)
9375
9376 def profile_load_by_os_handler(self, event: None | wx.Event = None) -> None:
9377 """Handle the profile load by OS checkbox event.
9378
9379 Args:
9380 event (None | wx.Event, optional): The event that triggered this
9381 handler.
9382 """
9383 if not is_superuser():
9384 return
9385 # Enable calibration management under Windows 7
9386 try:
9387 util_win.enable_calibration_management(self.profile_load_by_os.GetValue())
9388 except Exception as exception:
9389 print(f"util_win.enable_calibration_management(True): {exception}")
9390 else:
9391 label = get_profile_load_on_login_label(self.profile_load_by_os.GetValue())
9392 self.profile_load_on_login.Label = label
9393 self.profile_load_on_login.ContainingSizer.Layout()
9394
9395 def install_cal(
9396 self,
9397 capture_output: bool = False,
9398 cal: None | bool | str = None,
9399 profile_path: None | str = None,
9400 skip_scripts: bool = False,
9401 silent: bool = False,
9402 title: str = APPNAME,
9403 ) -> bool | Exception:
9404 """Install (load) a calibration from a calibration file or profile.
9405
9406 Args:
9407 capture_output (bool): Whether to capture output from the command.
9408 cal (None | bool | str, optional): Path to the calibration file or
9409 True for display profile, False to reset calibration. None
9410 if the current calibration file from the configuration should
9411 be used.
9412 profile_path (None | str, optional): Path to the profile file to
9413 load.
9414 skip_scripts (bool): Whether to skip running scripts after loading
9415 the calibration.
9416 silent (bool): Whether to suppress dialog messages.
9417 title (str): Title for the dialog.
9418
9419 Returns:
9420 bool | Exception: True if the calibration was successfully loaded,
9421 False if it was reset, or an Exception if an error occurred.
9422 """
9423 if config.is_virtual_display():
9424 return True
9425 # Install using dispwin
9426 cmd, args = self.worker.prepare_dispwin(cal, profile_path, False)
9427 if not isinstance(cmd, Exception):
9428 result = self.worker.exec_cmd(
9429 cmd,
9430 args,
9431 capture_output,
9432 low_contrast=False,
9433 skip_scripts=skip_scripts,
9434 silent=silent,
9435 title=title,
9436 )
9437 else:
9438 result = cmd
9439 if not isinstance(result, Exception) and result:
9440 if not silent:
9441 if cal is False:
9442 InfoDialog(
9443 self,
9444 msg=lang.getstr("calibration.reset_success"),
9445 ok=lang.getstr("ok"),
9446 bitmap=get_icon(32, "dialog-information"),
9447 log=False,
9448 )
9449 else:
9450 InfoDialog(
9451 self,
9452 msg=lang.getstr("calibration.load_success"),
9453 ok=lang.getstr("ok"),
9454 bitmap=get_icon(32, "dialog-information"),
9455 log=False,
9456 )
9457 elif not silent:
9458 if isinstance(result, Exception) and getcfg("dry_run"):
9459 show_result_dialog(result, self)
9460 return None
9461 if cal is False:
9462 InfoDialog(
9463 self,
9464 msg=lang.getstr("calibration.reset_error"),
9465 ok=lang.getstr("ok"),
9466 bitmap=get_icon(32, "dialog-error"),
9467 log=False,
9468 )
9469 else:
9470 InfoDialog(
9471 self,
9472 msg=lang.getstr("calibration.load_error"),
9473 ok=lang.getstr("ok"),
9474 bitmap=get_icon(32, "dialog-error"),
9475 log=False,
9476 )
9477 return result
9478
9479 def update_measurement_report(self, event: None | wx.Event = None) -> None:
9480 """Show file dialog to select a HTML measurement report for updating.
9481
9482 Update the selected report and show it afterwards.
9483
9484 Args:
9485 event (wx.Event, optional): The event that triggered the update.
9486 """
9487 default_dir, default_file = get_verified_path("last_filedialog_path")
9488 dlg = wx.FileDialog(
9489 self,
9490 lang.getstr("measurement_report.update"),
9491 defaultDir=default_dir,
9492 defaultFile=default_file,
9493 wildcard=f"{lang.getstr('filetype.html')}|*.html;*.htm",
9494 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
9495 )
9496 dlg.Center(wx.BOTH)
9497 result = dlg.ShowModal()
9498 if result == wx.ID_OK:
9499 path = dlg.GetPath()
9500 setcfg("last_filedialog_path", path)
9501 dlg.Destroy()
9502 if result != wx.ID_OK:
9503 return
9504 try:
9505 report.update(path, pack=getcfg("report.pack_js"))
9506 except OSError as exception:
9507 show_result_dialog(exception)
9508 else:
9509 # show report
9510 wx.CallAfter(launch_file, path)
9511
9512 def verify_calibration_handler(self, event: wx.Event) -> None:
9513 """Handler for verifying the current calibration.
9514
9515 Args:
9516 event (wx.Event): The event that triggered the verification.
9517 """
9518 if check_set_argyll_bin():
9519 self.setup_measurement(self.verify_calibration)
9520
9521 def verify_calibration(self) -> None:
9522 """Verify the current calibration by measuring the display."""
9523 if self.measure_auto(self.verify_calibration):
9524 return
9525 print("-" * 80)
9526 self.report_title = lang.getstr("calibration.verify")
9527 print(self.report_title)
9528 self.worker.interactive = False
9529 self.worker.start(
9530 self.result_consumer,
9531 self.worker.verify_calibration,
9532 progress_msg=self.report_title,
9533 pauseable=True,
9534 resume=bool(getattr(self, "measure_auto_after", None)),
9535 )
9536
9537 def select_profile(
9538 self,
9539 parent: None | wx.Window = None,
9540 title: str = APPNAME,
9541 msg: None | str = None,
9542 check_profile_class: bool = True,
9543 ignore_current_profile: bool = False,
9544 prefer_current_profile: bool = False,
9545 ) -> None | ICCProfile:
9546 """Select the currently configured profile or display profile.
9547
9548 Falls back to user choice via FileDialog if both not set.
9549
9550 Args:
9551 parent (wx.Window, optional): Parent window for dialogs. Defaults
9552 to self.
9553 title (str, optional): Title for the dialog. Defaults to APPNAME.
9554 msg (str, optional): Message to display in the dialog. Defaults to
9555 None.
9556 check_profile_class (bool, optional): Whether to check the profile
9557 class and color space of the selected profile. Defaults to
9558 True.
9559 ignore_current_profile (bool, optional): If True, do not use the
9560 current profile as a fallback. Defaults to False.
9561 prefer_current_profile (bool, optional): If True, prefer the
9562 current profile over user selection. Defaults to False.
9563
9564 Returns:
9565 None | ICCProfile: The selected profile, or None if no valid
9566 profile was selected or the user canceled the dialog.
9567 """
9568 if not parent:
9569 parent = self
9570 if not msg:
9571 msg = lang.getstr("profile.choose")
9572 if ignore_current_profile:
9573 profile = None
9574 else:
9575 profile = get_current_profile(include_display_profile=True)
9576 if profile and not prefer_current_profile:
9577 dlg = ConfirmDialog(
9578 self,
9579 title=title,
9580 msg=msg,
9581 ok=lang.getstr("profile.current"),
9582 cancel=lang.getstr("cancel"),
9583 alt=lang.getstr("browse"),
9584 bitmap=get_icon(32, APPNAME + "-profile-info"),
9585 )
9586 dlg.ok.SetDefault()
9587 result = dlg.ShowModal()
9588 if result == wx.ID_CANCEL:
9589 return None
9590 if result != wx.ID_OK:
9591 profile = None
9592 if profile:
9593 return profile
9594 default_dir, default_file = get_verified_path("last_icc_path")
9595 dlg = wx.FileDialog(
9596 parent,
9597 msg,
9598 defaultDir=default_dir,
9599 defaultFile=default_file,
9600 wildcard=lang.getstr("filetype.icc") + "|*.icc;*.icm",
9601 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
9602 )
9603 dlg.Center(wx.BOTH)
9604 result = dlg.ShowModal()
9605 path = ""
9606 if result == wx.ID_OK:
9607 path = dlg.GetPath()
9608 setcfg("last_icc_path", path)
9609 setcfg("last_cal_or_icc_path", path)
9610 dlg.Destroy()
9611 if result != wx.ID_OK:
9612 return None
9613 try:
9614 profile = ICCProfile(path)
9615 except (OSError, ICCProfileInvalidError):
9616 InfoDialog(
9617 parent,
9618 msg=lang.getstr("profile.invalid") + "\n" + path,
9619 ok=lang.getstr("ok"),
9620 bitmap=get_icon(32, "dialog-error"),
9621 )
9622 return None
9623 if check_profile_class and (
9624 profile.profileClass != b"mntr" or profile.colorSpace != b"RGB"
9625 ):
9626 InfoDialog(
9627 parent,
9628 msg=lang.getstr(
9629 "profile.unsupported",
9630 (
9631 profile.profileClass.decode("utf-8"),
9632 profile.colorSpace.decode("utf-8"),
9633 ),
9634 )
9635 + "\n"
9636 + path,
9637 ok=lang.getstr("ok"),
9638 bitmap=get_icon(32, "dialog-error"),
9639 )
9640 return None
9641 return profile
9642
9643 def measurement_report_create_handler(self, event: wx.Event) -> None:
9644 """Assign and initialize the report creation window.
9645
9646 Args:
9647 event (wx.Event): The event that triggered the report creation.
9648 """
9649 if not getattr(self, "reportframe", None):
9650 self.init_reportframe()
9651 if self.reportframe.IsShownOnScreen():
9652 self.reportframe.Raise()
9653 else:
9654 self.reportframe.Show(not self.reportframe.IsShownOnScreen())
9655
9656 def measurement_report_handler(
9657 self, event: wx.Event, path: None | str = None
9658 ) -> None:
9659 """Create a measurement report from the current measurement data.
9660
9661 Args:
9662 event (wx.Event): The event that triggered the report creation.
9663 path (str, optional): Path to a CGATS file to use instead of the
9664 current measurement data. Defaults to None.
9665 """
9666 self_check_report = wx.GetKeyState(wx.WXK_ALT)
9667
9668 if sys.platform == "darwin" or DEBUG:
9669 self.focus_handler(event)
9670 if not check_set_argyll_bin():
9671 return
9672
9673 sim_ti3 = None
9674 sim_gray = None
9675
9676 # select measurement data (ti1 or ti3)
9677 chart = getcfg("measurement_report.chart")
9678 try:
9679 chart = CGATS(chart, True)
9680 except (OSError, CGATSError) as exception:
9681 show_result_dialog(exception, getattr(self, "reportframe", self))
9682 return
9683
9684 chart = self.worker.ensure_patch_sequence(chart, False)
9685 fields = getcfg("measurement_report.chart.fields")
9686
9687 # profile(s)
9688 paths = []
9689 use_sim = getcfg("measurement_report.use_simulation_profile")
9690 use_sim_as_output = getcfg(
9691 "measurement_report.use_simulation_profile_as_output"
9692 )
9693 use_devlink = (
9694 getcfg("measurement_report.use_devlink_profile")
9695 # Use device link also if doing self check report
9696 # when 3D LUT for verification is enabled, because it
9697 # is the only way to apply the 3D LUT
9698 or (
9699 use_sim
9700 and use_sim_as_output
9701 and getcfg("3dlut.enable")
9702 and self_check_report
9703 )
9704 )
9705 # if not use_sim or not use_sim_as_output:
9706 # paths.append(getcfg("measurement_report.output_profile"))
9707 if use_sim:
9708 if use_sim_as_output and use_devlink:
9709 devlink_path = getcfg("measurement_report.devlink_profile")
9710 if devlink_path:
9711 paths.append(devlink_path)
9712 else:
9713 use_devlink = False
9714 paths.append(getcfg("measurement_report.simulation_profile"))
9715 sim_profile = None
9716 devlink = None
9717 oprof = profile = get_current_profile(True)
9718 for i, profilepath in enumerate(paths):
9719 try:
9720 profile = ICCProfile(profilepath)
9721 except (OSError, ICCProfileInvalidError) as exception:
9722 if isinstance(exception, ICCProfileInvalidError):
9723 msg = "{}\n{}".format(lang.getstr("profile.invalid"), profilepath)
9724 else:
9725 msg = str(exception)
9726 InfoDialog(
9727 getattr(self, "reportframe", self),
9728 msg=msg,
9729 ok=lang.getstr("ok"),
9730 bitmap=get_icon(32, "dialog-error"),
9731 )
9732 return
9733 else:
9734 if profile.version >= 4 and not profile.convert_iccv4_tags_to_iccv2():
9735 msg = "\n".join(
9736 [
9737 lang.getstr("profile.iccv4.unsupported"),
9738 profile.getDescription(),
9739 ]
9740 )
9741 show_result_dialog(msg, self)
9742 return
9743 if i in (0, 1) and use_sim:
9744 if use_sim_as_output and profile.colorSpace == b"RGB":
9745 if i == 0 and use_devlink:
9746 devlink = profile
9747 else:
9748 if profile.colorSpace != b"RGB":
9749 use_sim_as_output = False
9750 devlink = None
9751 sim_profile = profile
9752 profile = oprof
9753 if not profile and not oprof:
9754 show_result_dialog(
9755 Error(
9756 lang.getstr(
9757 "display_profile.not_detected",
9758 config.get_display_name(None, True),
9759 )
9760 ),
9761 getattr(self, "reportframe", self),
9762 )
9763 return
9764 if not self.check_profile_b2a_hires(profile):
9765 return
9766 colormanaged = (
9767 use_sim
9768 and use_sim_as_output
9769 and not sim_profile
9770 and config.get_display_name(None, True) in ("madVR", "Prisma")
9771 and getcfg("3dlut.enable")
9772 )
9773 if DEBUG:
9774 for n, p in {
9775 "profile": profile,
9776 "devlink": devlink,
9777 "sim_profile": sim_profile,
9778 "oprof": oprof,
9779 }.items():
9780 if p:
9781 print(n, p.getDescription())
9782
9783 if use_sim:
9784 mprof = sim_profile if sim_profile else profile
9785 apply_map = (
9786 use_sim
9787 and mprof.colorSpace == b"RGB"
9788 and isinstance(mprof.tags.get("rXYZ"), XYZType)
9789 and isinstance(mprof.tags.get("gXYZ"), XYZType)
9790 and isinstance(mprof.tags.get("bXYZ"), XYZType)
9791 and not isinstance(mprof.tags.get("A2B0"), LUT16Type)
9792 )
9793 apply_off = apply_map and getcfg("measurement_report.apply_black_offset")
9794 apply_trc = apply_map and getcfg("measurement_report.apply_trc")
9795 bt1886 = None
9796 if apply_trc or apply_off:
9797 # TRC BT.1886-like, gamma with black offset, or just black offset
9798 try:
9799 odata = self.worker.xicclu(oprof, (0, 0, 0), pcs="x")
9800 if len(odata) != 1 or len(odata[0]) != 3:
9801 raise ValueError(f"Blackpoint is invalid: {odata}")
9802 except Exception as exception:
9803 show_result_dialog(exception, getattr(self, "reportframe", self))
9804 return
9805 if odata[0][1]:
9806 # Got above zero blackpoint from lookup
9807 XYZbp = odata[0] # noqa: N806
9808 else:
9809 # Got zero blackpoint from lookup.
9810 # Try chardata instead.
9811 XYZbp = oprof.get_chardata_bkpt() # noqa: N806
9812 if XYZbp:
9813 XYZbp = [v * XYZbp[1] for v in list(oprof.tags.wtpt.pcs.values())] # noqa: N806
9814 else:
9815 XYZbp = [0, 0, 0] # noqa: N806
9816 if apply_trc:
9817 # TRC BT.1886-like
9818 gamma = getcfg("measurement_report.trc_gamma")
9819 gamma_type = getcfg("measurement_report.trc_gamma_type")
9820 outoffset = getcfg("measurement_report.trc_output_offset")
9821 if gamma_type == "b":
9822 # Get technical gamma needed to achieve effective gamma
9823 gamma = colormath.xicc_tech_gamma(gamma, XYZbp[1], outoffset)
9824 else:
9825 # Just black offset
9826 outoffset = 1.0
9827 gamma = 0.0
9828 for channel in "rgb":
9829 gamma += mprof.tags[f"{channel}TRC"].get_gamma()
9830 gamma /= 3.0
9831 rXYZ = list(mprof.tags.rXYZ.values()) # noqa: N806
9832 gXYZ = list(mprof.tags.gXYZ.values()) # noqa: N806
9833 bXYZ = list(mprof.tags.bXYZ.values()) # noqa: N806
9834 mtx = colormath.Matrix3x3(
9835 [
9836 [rXYZ[0], gXYZ[0], bXYZ[0]],
9837 [rXYZ[1], gXYZ[1], bXYZ[1]],
9838 [rXYZ[2], gXYZ[2], bXYZ[2]],
9839 ]
9840 )
9841 bt1886 = colormath.BT1886(mtx, XYZbp, outoffset, gamma, apply_trc)
9842 if apply_trc:
9843 # Make sure the profile has the expected Rec. 709 TRC
9844 # for BT.1886
9845 for _i, channel in enumerate(("r", "g", "b")):
9846 if channel + "TRC" in mprof.tags:
9847 mprof.tags[channel + "TRC"].set_trc(-709)
9848 # Set profile filename to None so it gets written to temp
9849 # directory (this makes sure we're actually using the changed
9850 # profile for lookup)
9851 mprof.filename = None
9852
9853 if sim_profile:
9854 sim_intent = (
9855 "a" if getcfg("measurement_report.whitepoint.simulate") else "r"
9856 )
9857 void, sim_ti3, sim_gray = self.worker.chart_lookup(
9858 chart,
9859 sim_profile,
9860 check_missing_fields=True,
9861 intent=sim_intent,
9862 bt1886=bt1886,
9863 )
9864 # NOTE: we ignore the ti1 and gray patches here
9865 # only the ti3 is valuable at this point
9866 if not sim_ti3:
9867 return
9868 intent = (
9869 "r"
9870 if sim_intent == "r"
9871 or getcfg("measurement_report.whitepoint.simulate.relative")
9872 else "a"
9873 )
9874 bt1886 = None
9875 else:
9876 sim_intent = None
9877 intent = "r"
9878 if fields in ("LAB", "XYZ"):
9879 if getcfg("measurement_report.whitepoint.simulate"):
9880 sim_intent = "a"
9881 if not getcfg("measurement_report.whitepoint.simulate.relative"):
9882 intent = "a"
9883 else:
9884 chart.fix_device_values_scaling()
9885 chart.adapt(cat=profile.guess_cat() or "Bradford")
9886
9887 # lookup test patches
9888 ti1, ti3_ref, gray = self.worker.chart_lookup(
9889 sim_ti3 or chart,
9890 profile,
9891 bool(sim_ti3) or fields in ("LAB", "XYZ"),
9892 fields=None if bool(sim_ti3) else fields,
9893 intent=intent,
9894 bt1886=bt1886,
9895 )
9896 if not ti3_ref:
9897 return
9898 if not gray and sim_gray:
9899 gray = sim_gray
9900
9901 if devlink:
9902 void, ti1, void = self.worker.chart_lookup(
9903 ti1,
9904 devlink,
9905 check_missing_fields=True,
9906 white_patches=1,
9907 white_patches_total=False,
9908 )
9909 if not ti1:
9910 return
9911
9912 # let the user choose a location for the result
9913 report_type = "Self Check" if self_check_report else "Measurement"
9914 default_file = "{} Report {} - {} - {}".format(
9915 report_type,
9916 VERSION_STRING,
9917 re.sub(
9918 r"[\\/:;*?\"<>|]+",
9919 "_",
9920 self.display_ctrl.GetStringSelection().replace(
9921 f" {lang.getstr('display.primary')}", ""
9922 ),
9923 ),
9924 strftime("%Y-%m-%d %H-%M.html"),
9925 )
9926 if not path:
9927 default_dir = get_verified_path(
9928 None, os.path.join(getcfg("profile.save_path"), default_file)
9929 )[0]
9930 dlg = wx.FileDialog(
9931 getattr(self, "reportframe", self),
9932 lang.getstr("save_as"),
9933 default_dir,
9934 default_file,
9935 wildcard=f"{lang.getstr('filetype.html')}|*.html;*.htm",
9936 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
9937 )
9938 dlg.Center(wx.BOTH)
9939 result = dlg.ShowModal()
9940 if result == wx.ID_OK:
9941 path = make_argyll_compatible_path(dlg.GetPath())
9942 if not waccess(path, os.W_OK):
9943 show_result_dialog(
9944 Error(lang.getstr("error.access_denied.write", path)),
9945 getattr(self, "reportframe", self),
9946 )
9947 return
9948 dlg.Destroy()
9949 if result != wx.ID_OK:
9950 return
9951 else:
9952 path = make_argyll_compatible_path(path)
9953 save_path = f"{os.path.splitext(path)[0]}.html"
9954 setcfg("last_filedialog_path", save_path)
9955 # check if file(s) already exist
9956 if os.path.exists(save_path):
9957 dlg = ConfirmDialog(
9958 getattr(self, "reportframe", self),
9959 msg=lang.getstr("dialog.confirm_overwrite", save_path),
9960 ok=lang.getstr("overwrite"),
9961 cancel=lang.getstr("cancel"),
9962 bitmap=get_icon(32, "dialog-warning"),
9963 )
9964 result = dlg.ShowModal()
9965 dlg.Destroy()
9966 if result != wx.ID_OK:
9967 return
9968
9969 if self_check_report and oprof:
9970 # Instead of doing measurements, lookup ti1 through display profile
9971
9972 # setup temp dir
9973 temp = self.worker.create_tempdir()
9974 if isinstance(temp, Exception):
9975 show_result_dialog(temp, getattr(self, "reportframe", self))
9976 return
9977
9978 # filenames
9979 name, ext = os.path.splitext(os.path.basename(save_path))
9980 ti3_path = os.path.join(temp, f"{name}.ti3")
9981 profile_path = os.path.join(temp, f"{name}.icc")
9982
9983 # Argyll applycal can't deal with single gamma TRC tags
9984 # or TRC tags with less than 256 entries
9985 _applycal_bug_workaround(oprof)
9986
9987 # write profile to temp dir
9988 oprof.write(profile_path)
9989
9990 # Check if we need to apply calibration
9991 if devlink and "-a" in parse_argument_string(
9992 devlink.tags.get("meta", {})
9993 .get("collink.args", {})
9994 .get("value", "-a" if getcfg("3dlut.output.profile.apply_cal") else "")
9995 ):
9996 oprof_cal_path = os.path.join(temp, f"{name}.cal")
9997 extract_cal_from_profile(oprof, oprof_cal_path)
9998 profile_with_cal_path = os.path.join(temp, f"{name}_with_cal.icc")
9999
10000 applycal = get_argyll_util("applycal")
10001 if not applycal:
10002 show_result_dialog(
10003 Error(lang.getstr("argyll.util.not_found", "applycal")), self
10004 )
10005 return
10006 print(lang.getstr("apply_cal"))
10007 result = self.worker.exec_cmd(
10008 applycal,
10009 ["-v", oprof_cal_path, profile_path, profile_with_cal_path],
10010 capture_output=True,
10011 skip_scripts=True,
10012 )
10013 if not result:
10014 result = Error(
10015 "\n\n".join(
10016 [
10017 lang.getstr("apply_cal.error"),
10018 "\n".join(self.worker.errors),
10019 ]
10020 )
10021 )
10022 if isinstance(result, Exception) and not getcfg("dry_run"):
10023 show_result_dialog(result, self)
10024 return
10025 odesc = oprof.getDescription()
10026 oprof = ICCProfile(profile_with_cal_path)
10027 # Restore original description
10028 oprof.setDescription(odesc)
10029
10030 void, ti3, void = self.worker.chart_lookup(
10031 ti1, oprof, pcs="x", intent="a", white_patches=0
10032 )
10033 wtpt = list(oprof.tags.wtpt.values())
10034 if isinstance(oprof.tags.get("lumi"), XYZType):
10035 luminance = oprof.tags.lumi.Y
10036 else:
10037 luminance = 100
10038 white_XYZ_cdm2 = [v * luminance for v in wtpt] # noqa: N806
10039 ti3.add_keyword(
10040 "LUMINANCE_XYZ_CDM2", "{:.6f} {:.6f} {:.6f}".format(*white_XYZ_cdm2)
10041 )
10042
10043 # write ti3 to temp dir
10044 try:
10045 with open(ti3_path, "wb") as ti3_file:
10046 ti3_file.write(bytes(ti3))
10047 except OSError:
10048 InfoDialog(
10049 getattr(self, "reportframe", self),
10050 msg=lang.getstr("error.file.create", ti3_path),
10051 ok=lang.getstr("ok"),
10052 bitmap=get_icon(32, "dialog-error"),
10053 )
10054 self.worker.wrapup(False)
10055 return
10056
10057 print("-" * 80)
10058 print(lang.getstr("self_check_report"))
10059 self.measurement_report_consumer(
10060 True,
10061 ti3_path,
10062 profile,
10063 sim_profile,
10064 intent,
10065 sim_intent,
10066 devlink,
10067 ti3_ref,
10068 sim_ti3,
10069 save_path,
10070 chart,
10071 gray,
10072 apply_trc,
10073 use_sim,
10074 use_sim_as_output,
10075 oprof,
10076 True,
10077 )
10078 return
10079
10080 # setup for measurement
10081 self.setup_measurement(
10082 self.measurement_report,
10083 ti1,
10084 oprof,
10085 profile,
10086 sim_profile,
10087 intent,
10088 sim_intent,
10089 devlink,
10090 ti3_ref,
10091 sim_ti3,
10092 save_path,
10093 chart,
10094 gray,
10095 apply_trc,
10096 colormanaged,
10097 use_sim,
10098 use_sim_as_output,
10099 )
10100
10101 def measurement_report(
10102 self,
10103 ti1: CGATS,
10104 oprof: ICCProfile,
10105 profile: ICCProfile,
10106 sim_profile: None | ICCProfile,
10107 intent: str,
10108 sim_intent: None | str,
10109 devlink: None | ICCProfile,
10110 ti3_ref: CGATS,
10111 sim_ti3: None | CGATS,
10112 save_path: str,
10113 chart: CGATS,
10114 gray: list,
10115 apply_trc: bool,
10116 colormanaged: bool,
10117 use_sim: bool,
10118 use_sim_as_output: bool,
10119 ) -> None:
10120 """Start measurement report worker thread.
10121
10122 Args:
10123 ti1 (CGATS): The CGATS data to measure.
10124 oprof (ICCProfile): The original profile used for the measurement.
10125 profile (ICCProfile): The profile used for the measurement.
10126 sim_profile (None | ICCProfile): The simulation profile used, if
10127 any.
10128 intent (str): Rendering intent used for the measurement.
10129 sim_intent (None | str): Simulation rendering intent, if any.
10130 devlink (None | ICCProfile): Device link profile used, if any.
10131 ti3_ref (CGATS): Reference CGATS data.
10132 sim_ti3 (None | CGATS): Simulation CGATS data, if any.
10133 save_path (str): Path to save the report.
10134 chart (CGATS): The chart used for the measurement.
10135 gray (list): Gray patches data.
10136 apply_trc (bool): Whether to apply TRC.
10137 colormanaged (bool): Whether the measurement is color managed.
10138 use_sim (bool): Whether to use simulation profile.
10139 use_sim_as_output (bool): Whether to use simulation profile as
10140 output.
10141 """
10142 print("-" * 80)
10143 progress_msg = lang.getstr("measurement_report")
10144 print(progress_msg)
10145
10146 # setup temp dir
10147 temp = self.worker.create_tempdir()
10148 if isinstance(temp, Exception):
10149 show_result_dialog(temp, getattr(self, "reportframe", self))
10150 return
10151
10152 # filenames
10153 name, ext = os.path.splitext(os.path.basename(save_path))
10154 ti1_path = os.path.join(temp, f"{name}.ti1")
10155 profile_path = os.path.join(temp, f"{name}.icc")
10156
10157 debug_print(f"save_path: {save_path}")
10158 debug_print(f"name: {name}")
10159 debug_print(f"ext: {ext}")
10160 debug_print(f"ti1_path: {ti1_path}")
10161 debug_print(f"profile_path: {profile_path}")
10162
10163 # write ti1 to temp dir
10164 try:
10165 with open(ti1_path, "wb") as ti1_file:
10166 ti1_file.write(bytes(ti1))
10167 except OSError:
10168 traceback.print_exc()
10169 InfoDialog(
10170 getattr(self, "reportframe", self),
10171 msg=lang.getstr("error.file.create", ti1_path),
10172 ok=lang.getstr("ok"),
10173 bitmap=get_icon(32, "dialog-error"),
10174 )
10175 self.worker.wrapup(False)
10176 return
10177
10178 # write profile to temp dir
10179 profile.write(profile_path)
10180 # Check if we need to apply calibration
10181 if not use_sim_as_output or (
10182 devlink
10183 and "-a"
10184 not in parse_argument_string(
10185 devlink.tags.get("meta", {})
10186 .get("collink.args", {})
10187 .get("value", "-a" if getcfg("3dlut.output.profile.apply_cal") else "")
10188 )
10189 ):
10190 calprof = oprof
10191 else:
10192 calprof = profile
10193
10194 cal_path = os.path.join(temp, f"{name}.cal")
10195 try:
10196 # Extract calibration from profile
10197 cal = extract_cal_from_profile(calprof, cal_path, False)
10198 except Exception:
10199 traceback.print_exc()
10200 wx.CallAfter(
10201 show_result_dialog,
10202 Error(lang.getstr("cal_extraction_failed")),
10203 getattr(self, "reportframe", self),
10204 )
10205 self.Show()
10206 return
10207 if not cal:
10208 # Use linear calibration
10209 cal_path = get_data_path("linear.cal")
10210
10211 # start readings
10212 self.worker.dispread_after_dispcal = False
10213 self.worker.interactive = config.get_display_name() == "Untethered"
10214 self.worker.start(
10215 self.measurement_report_consumer,
10216 self.worker.measure_ti1,
10217 cargs=(
10218 os.path.splitext(ti1_path)[0] + ".ti3",
10219 profile,
10220 sim_profile,
10221 intent,
10222 sim_intent,
10223 devlink,
10224 ti3_ref,
10225 sim_ti3,
10226 save_path,
10227 chart,
10228 gray,
10229 apply_trc,
10230 use_sim,
10231 use_sim_as_output,
10232 oprof,
10233 ),
10234 wargs=(ti1_path, cal_path, colormanaged),
10235 progress_msg=progress_msg,
10236 pauseable=True,
10237 )
10238
10239 def measurement_report_consumer(
10240 self,
10241 result: bool | Exception,
10242 ti3_path: str,
10243 profile: ICCProfile,
10244 sim_profile: None | ICCProfile,
10245 intent: str,
10246 sim_intent: None | str,
10247 devlink: None | ICCProfile,
10248 ti3_ref: CGATS,
10249 sim_ti3: None | CGATS,
10250 save_path: str,
10251 chart: CGATS,
10252 gray: list,
10253 apply_trc: bool,
10254 use_sim: bool,
10255 use_sim_as_output: bool,
10256 oprof: ICCProfile,
10257 self_check_report: bool = False,
10258 ) -> None:
10259 """Consumer for measurement report worker thread.
10260
10261 Args:
10262 result (bool | Exception): Result of the measurement.
10263 ti3_path (str): Path to the resulting ti3 file.
10264 profile (ICCProfile): The profile used for the measurement.
10265 sim_profile (None | ICCProfile): The simulation profile used, if any.
10266 intent (str): Rendering intent used for the measurement.
10267 sim_intent (None | str): Simulation rendering intent, if any.
10268 devlink (None | ICCProfile): Device link profile used, if any.
10269 ti3_ref (CGATS): Reference CGATS data.
10270 sim_ti3 (None | CGATS): Simulation CGATS data, if any.
10271 save_path (str): Path to save the report.
10272 chart (CGATS): The chart used for the measurement.
10273 gray (list): Gray patches data.
10274 apply_trc (bool): Whether to apply TRC.
10275 use_sim (bool): Whether to use simulation profile.
10276 use_sim_as_output (bool): Whether to use simulation profile as output.
10277 oprof (ICCProfile): Original profile used for the measurement.
10278 self_check_report (bool): Whether this is a self-check report.
10279 """
10280 self.Show()
10281
10282 if not isinstance(result, Exception) and result:
10283 # get item 0 of the ti3 to strip the CAL part from the measured data
10284 try:
10285 ti3_measured = CGATS(ti3_path)[0]
10286 except (
10287 OSError,
10288 CGATSInvalidError,
10289 CGATSInvalidOperationError,
10290 CGATSKeyError,
10291 CGATSTypeError,
10292 CGATSValueError,
10293 ) as exc:
10294 result = exc
10295 else:
10296 print(lang.getstr("success"))
10297 result = self.measurement_file_check_confirm(ti3_measured)
10298
10299 if isinstance(result, Exception) or not result:
10300 if isinstance(result, Exception):
10301 wx.CallAfter(
10302 show_result_dialog, result, getattr(self, "reportframe", self)
10303 )
10304
10305 # cleanup
10306 self.worker.wrapup(False if not isinstance(result, Exception) else result)
10307 return
10308
10309 # Determine quantization
10310 qbits = None
10311 if config.get_display_name() != "Untethered":
10312 args = []
10313 if getcfg("extra_args.dispread").strip():
10314 args += parse_argument_string(getcfg("extra_args.dispread"))
10315 self.worker.add_measurement_features(
10316 args, True, allow_video_levels=True, quantize=True
10317 )
10318 quantize_arg = get_arg("-Z", args)
10319 if quantize_arg:
10320 try:
10321 if quantize_arg[1] == "-Z":
10322 # Next arg is quantization bit depth
10323 qbits = int(args[quantize_arg[0] + 1])
10324 else:
10325 # Quantization bit depth is part of arg string
10326 qbits = int(quantize_arg[1][2:])
10327 except (IndexError, TypeError, ValueError):
10328 pass
10329 elif "-E" in args:
10330 qbits = 8 # ArgyllCMS default for video encoding (see dispread doc)
10331 if qbits:
10332 print(f"Quantizing reference device values to {qbits:.0f} bits")
10333 ti3_ref.quantize_device_values(qbits)
10334 if gray:
10335 qmax = 2**qbits - 1.0
10336 gray = [
10337 [round(round(v / 100.0 * qmax) / qmax * 100.0, 4) for v in RGB]
10338 for RGB in gray
10339 ]
10340
10341 # Keep around ref TI3 for diagnostic purposes
10342 ti3_ref.write(f"{os.path.splitext(ti3_path)[0]}_ref.ti3")
10343
10344 # Account for additional white patches
10345 white_rgb = {"RGB_R": 100, "RGB_G": 100, "RGB_B": 100}
10346 white_ref = ti3_ref.queryi(white_rgb)
10347 if devlink:
10348 # Remove additional white patch (device white = 100 before
10349 # accounting for effect of devicelink)
10350 # This is always the first patch ONLY
10351 ti3_measured.DATA.remove(0)
10352 # The new offset is the difference in length between measured and
10353 # ref because the white patch is always added at the start
10354 offset = len(ti3_measured.DATA) - len(ti3_ref.DATA)
10355 # Set full white RGB to 100
10356 for i in range(offset):
10357 for label in ("RGB_R", "RGB_G", "RGB_B"):
10358 ti3_measured.DATA[i][label] = 100.0
10359 # Restore original device values
10360 for i in ti3_ref.DATA:
10361 for label in ("RGB_R", "RGB_G", "RGB_B"):
10362 ti3_measured.DATA[i + offset][label] = ti3_ref.DATA[i][label]
10363 # White patches (device white = 100 after accounting for effect of
10364 # devicelink)
10365 white_measured = ti3_measured.queryi(white_rgb)
10366 # Update white cd/m2
10367 luminance = float(ti3_measured.LUMINANCE_XYZ_CDM2.split()[1])
10368 white_XYZ_cdm2 = [0, 0, 0] # noqa: N806
10369 for i, label in enumerate(("XYZ_X", "XYZ_Y", "XYZ_Z")):
10370 white_XYZ_cdm2[i] = white_measured[0][label] * luminance / 100.0
10371 ti3_measured.LUMINANCE_XYZ_CDM2 = "{:.6f} {:.6f} {:.6f}".format(
10372 *white_XYZ_cdm2
10373 )
10374 # Scale to actual white Y after accounting for effect of devicelink
10375 scale = 100.0 / white_measured[0]["XYZ_Y"]
10376 for i in ti3_measured.DATA:
10377 for label in ("XYZ_X", "XYZ_Y", "XYZ_Z"):
10378 ti3_measured.DATA[i][label] *= scale
10379 else:
10380 white_measured = ti3_measured.queryi(white_rgb)
10381 offset = max(len(white_measured) - len(white_ref), 0)
10382
10383 # If patches were removed from the measured TI3, we need to remove them
10384 # from reference and simulation TI3
10385 if isinstance(result, tuple):
10386 ref_removed = []
10387 sim_removed = []
10388 for item in reversed(result[0]):
10389 key = item.key - offset
10390 ref_removed.insert(0, ti3_ref.DATA.pop(key))
10391 if sim_ti3:
10392 sim_removed.insert(0, sim_ti3.DATA.pop(key))
10393 for item in ref_removed:
10394 print(f"Removed patch #{item.key:.0f} from reference TI3: {item}")
10395 for item in sim_removed:
10396 print(f"Removed patch #{item.key} from simulation TI3: {item}")
10397 # Update offset
10398 white_ref = ti3_ref.queryi(white_rgb)
10399 offset = max(len(white_measured) - len(white_ref), 0)
10400
10401 # Determine if we should use planckian locus for assumed target wp
10402 # Detection will only work for profiles created by DisplayCAL
10403 planckian = False
10404 if (profile.tags.get("CIED", b"") or profile.tags.get("targ", b""))[
10405 0:4
10406 ] == b"CTI3":
10407 options_dispcal = get_options_from_profile(profile)[0]
10408 for option in options_dispcal:
10409 if option.startswith("T"):
10410 planckian = True
10411 break
10412
10413 # calculate amount of calibration grayscale tone values
10414 cal_entrycount = 256
10415 if isinstance(profile.tags.get("vcgt"), VideoCardGammaType):
10416 rgb = [[], [], []]
10417 vcgt = profile.tags.vcgt
10418 if "data" in vcgt:
10419 # table
10420 cal_entrycount = vcgt["entryCount"]
10421 for i in range(cal_entrycount):
10422 for j in range(3):
10423 rgb[j].append(
10424 float(vcgt["data"][j][i])
10425 / (math.pow(256, vcgt["entrySize"]) - 1)
10426 * 255
10427 )
10428 else:
10429 # formula
10430 step = 100.0 / 255.0
10431 for i in range(cal_entrycount):
10432 # float2dec(v) fixes miniscule deviations in the calculated gamma
10433 for j, name in enumerate(("red", "green", "blue")):
10434 vmin = float2dec(vcgt[name + "Min"] * 255)
10435 v = float2dec(math.pow(step * i / 100.0, vcgt[name + "Gamma"]))
10436 vmax = float2dec(vcgt[name + "Max"] * 255)
10437 rgb[j].append(float2dec(vmin + v * (vmax - vmin), 8))
10438 cal_rgblevels = [len({round(n) for n in channel}) for channel in rgb]
10439 else:
10440 # Assume linear with all steps
10441 cal_rgblevels = [256, 256, 256]
10442
10443 if not chart.filename.lower().endswith(".ti1") or sim_ti3:
10444 # make the device values match
10445 for i in ti3_ref.DATA:
10446 for color in ("RGB_R", "RGB_G", "RGB_B"):
10447 if sim_ti3 and sim_ti3.DATA[i].get(color) is not None:
10448 ti3_ref.DATA[i][color] = sim_ti3.DATA[i][color]
10449 else:
10450 ti3_ref.DATA[i][color] = ti3_measured.DATA[i + offset][color]
10451
10452 cat = "Bradford"
10453
10454 # create a 'joined' ti3 from ref ti3, with XYZ values from measured ti3
10455 # this makes sure CMYK data in the original ref will be present in
10456 # the newly joined ti3
10457 ti3_joined = CGATS(bytes(ti3_ref))[0]
10458 ti3_joined.LUMINANCE_XYZ_CDM2 = ti3_measured.LUMINANCE_XYZ_CDM2
10459 # add XYZ to DATA_FORMAT if not yet present
10460 labels_xyz = ("XYZ_X", "XYZ_Y", "XYZ_Z")
10461 if (
10462 "XYZ_X" not in list(ti3_joined.DATA_FORMAT.values())
10463 and "XYZ_Y" not in list(ti3_joined.DATA_FORMAT.values())
10464 and "XYZ_Z" not in list(ti3_joined.DATA_FORMAT.values())
10465 ):
10466 ti3_joined.DATA_FORMAT.add_data(labels_xyz)
10467 # set XYZ in joined ti3 to XYZ of measurements
10468 for i in ti3_joined.DATA:
10469 for color in labels_xyz:
10470 ti3_joined.DATA[i][color] = ti3_measured.DATA[i + offset][color]
10471
10472 # cleanup
10473 self.worker.wrapup(False if not isinstance(result, Exception) else result)
10474
10475 wtpt_profile_norm = tuple(n * 100 for n in list(profile.tags.wtpt.values()))
10476 if isinstance(profile.tags.get("chad"), ChromaticAdaptionTag):
10477 # undo chromatic adaption of profile whitepoint
10478 WX, WY, WZ = profile.tags.chad.inverted() * wtpt_profile_norm # noqa: N806
10479 wtpt_profile_norm = tuple((n / WY) * 100.0 for n in (WX, WY, WZ))
10480 # guess chromatic adaption transform (Bradford, CAT02...)
10481 cat = profile.guess_cat() or cat
10482 elif isinstance(profile.tags.get("arts"), ChromaticAdaptionTag):
10483 cat = profile.guess_cat() or cat
10484 if oprof and isinstance(oprof.tags.get("lumi"), XYZType):
10485 # calculate unscaled whitepoint
10486 scale = oprof.tags.lumi.Y / 100.0
10487 wtpt_profile = tuple(n * scale for n in wtpt_profile_norm)
10488 else:
10489 wtpt_profile = wtpt_profile_norm
10490
10491 if sim_profile:
10492 wtpt_sim_profile_norm = tuple(
10493 n * 100 for n in list(sim_profile.tags.wtpt.values())
10494 )
10495 if "chad" in sim_profile.tags:
10496 # undo chromatic adaption of profile whitepoint
10497 WX, WY, WZ = sim_profile.tags.chad.inverted() * wtpt_sim_profile_norm # noqa: N806
10498 wtpt_sim_profile_norm = tuple((n / WY) * 100.0 for n in (WX, WY, WZ))
10499
10500 wtpt_measured = tuple(float(n) for n in ti3_joined.LUMINANCE_XYZ_CDM2.split())
10501 # normalize so that Y = 100
10502 wtpt_measured_norm = tuple((n / wtpt_measured[1]) * 100 for n in wtpt_measured)
10503
10504 if intent != "a" and sim_intent != "a":
10505 white = ti3_joined.queryi(white_rgb)
10506 for i in white:
10507 white[i].update(
10508 {
10509 "XYZ_X": wtpt_measured_norm[0],
10510 "XYZ_Y": wtpt_measured_norm[1],
10511 "XYZ_Z": wtpt_measured_norm[2],
10512 }
10513 )
10514
10515 black = ti3_joined.queryi1({"RGB_R": 0, "RGB_G": 0, "RGB_B": 0})
10516 if black:
10517 bkpt_measured_norm = black["XYZ_X"], black["XYZ_Y"], black["XYZ_Z"]
10518 if self_check_report and not bkpt_measured_norm[1]:
10519 XYZbp = oprof.get_chardata_bkpt(True) # noqa: N806
10520 if XYZbp:
10521 bkpt_measured_norm = tuple(v * 100 for v in XYZbp)
10522 bkpt_measured = tuple(
10523 wtpt_measured[1] / 100 * n for n in bkpt_measured_norm
10524 )
10525 else:
10526 bkpt_measured_norm = None
10527 bkpt_measured = None
10528
10529 # set Lab values
10530 labels_Lab = ("LAB_L", "LAB_A", "LAB_B") # noqa: N806
10531 for data in (ti3_ref, ti3_joined):
10532 data_formats = list(data.DATA_FORMAT.values())
10533 if (
10534 b"XYZ_X" in data_formats
10535 and b"XYZ_Y" in data_formats
10536 and b"XYZ_Z" in data_formats
10537 ):
10538 if (
10539 b"LAB_L" not in data_formats
10540 and b"LAB_A" not in data_formats
10541 and b"LAB_B" not in data_formats
10542 ):
10543 # add Lab fields to DATA_FORMAT if not present
10544 data.DATA_FORMAT.add_data(labels_Lab)
10545 has_Lab = False # noqa: N806
10546 else:
10547 has_Lab = True # noqa: N806
10548 if data is ti3_joined or not has_Lab:
10549 for i in data.DATA:
10550 X, Y, Z = [data.DATA[i][color] for color in labels_xyz] # noqa: N806
10551 if data is ti3_joined:
10552 # we need to adapt the measured values to D50
10553 # print X, Y, Z, '->',
10554 X, Y, Z = colormath.adapt( # noqa: N806
10555 X, Y, Z, wtpt_measured_norm, cat=cat
10556 )
10557 # print X, Y, Z
10558 Lab = XYZ2Lab(X, Y, Z) # noqa: N806
10559 for j, color in enumerate(labels_Lab):
10560 data.DATA[i][color] = Lab[j]
10561 if data is ti3_ref and sim_intent == "a" and intent == "a":
10562 for i in data.DATA:
10563 # we need to adapt the reference values to D50
10564 L, a, b = [data.DATA[i][color] for color in labels_Lab] # noqa: N806
10565 X, Y, Z = colormath.Lab2XYZ(L, a, b, scale=100) # noqa: N806
10566 # print X, Y, Z, '->',
10567 X, Y, Z = colormath.adapt(X, Y, Z, wtpt_profile_norm, cat=cat) # noqa: N806
10568 # print X, Y, Z
10569 Lab = XYZ2Lab(X, Y, Z) # noqa: N806
10570 for j, color in enumerate(labels_Lab):
10571 data.DATA[i][color] = Lab[j]
10572
10573 # gather data for report
10574
10575 instrument = self.comport_ctrl.GetStringSelection()
10576 measurement_mode = self.measurement_mode_ctrl.GetStringSelection()
10577 instrument += " \u2014 " + measurement_mode
10578
10579 observer = get_cfg_option_from_args(
10580 "observer", "-Q", self.worker.options_dispread
10581 )
10582 if observer != DEFAULTS["observer"]:
10583 instrument += " \u2014 " + self.observers_ab.get(observer, observer)
10584
10585 ccmx = "None"
10586 reference_observer = None
10587 if not self_check_report and self.worker.instrument_can_use_ccxx():
10588 ccmx = getcfg("colorimeter_correction_matrix_file").split(":", 1)
10589 if len(ccmx) > 1 and ccmx[1]:
10590 ccmxpath = ccmx[1]
10591 ccmx = os.path.basename(ccmx[1])
10592 try:
10593 cgats = CGATS(ccmxpath)
10594 except (OSError, CGATSError) as exception:
10595 print(f"{ccmxpath}:", exception)
10596 else:
10597 filename, ext = os.path.splitext(ccmx)
10598 desc = cgats.get_descriptor()
10599 desc = lang.getstr(
10600 ext[1:] + "." + filename, default=desc.decode("utf-8")
10601 )
10602 # If the description is not the same as the 'sane'
10603 # filename, add the filename after the description
10604 # (max 31 chars)
10605 # See also colorimeter_correction_check_overwite, the
10606 # way the filename is processed must be the same
10607 argyll_compatible_path = make_argyll_compatible_path(
10608 desc, is_name=True
10609 )
10610 if argyll_compatible_path != filename:
10611 ccmx = "{} &amp;lt;{}&amp;gt;".format(
10612 desc,
10613 ellipsis_(ccmx, 31, "m"),
10614 )
10615 if cgats.get(0, cgats).type == "CCMX":
10616 reference_observer = cgats.queryv1("REFERENCE_OBSERVER")
10617 if (
10618 reference_observer
10619 and reference_observer != DEFAULTS["observer"]
10620 ):
10621 reference_observer = self.observers_ab.get(
10622 reference_observer, reference_observer
10623 )
10624 if reference_observer.lower() not in ccmx.lower():
10625 ccmx += " \u2014 " + reference_observer
10626 else:
10627 ccmx = "None"
10628
10629 if not sim_profile and use_sim and use_sim_as_output:
10630 sim_profile = profile
10631
10632 if (
10633 getcfg("measurement_report.trc_gamma") != 2.4
10634 or getcfg("measurement_report.trc_gamma_type") != "B"
10635 or getcfg("measurement_report.trc_output_offset")
10636 ):
10637 trc = ""
10638 else:
10639 trc = "BT.1886"
10640
10641 if self_check_report:
10642 display = oprof.getDeviceModelDescription() or "N/A"
10643 if oprof is not profile:
10644 display += f" (Profile: {oprof.getDescription()})"
10645 instrument = "N/A"
10646 ccmx = "N/A"
10647 report_type = "Self Check"
10648 else:
10649 display = self.display_ctrl.GetStringSelection().replace(
10650 " " + lang.getstr("display.primary"), ""
10651 )
10652 report_type = "Measurement"
10653 placeholders2data = {
10654 "${PLANCKIAN}": 'checked="checked"' if planckian else "",
10655 "${DISPLAY}": display,
10656 "${INSTRUMENT}": instrument,
10657 "${CORRECTION_MATRIX}": ccmx,
10658 "${BLACKPOINT}": "{:f} {:f} {:f}".format(
10659 *(bkpt_measured if bkpt_measured else (-1.0, -1.0, -1.0))
10660 ),
10661 "${WHITEPOINT}": "{:f} {:f} {:f}".format(*wtpt_measured),
10662 "${WHITEPOINT_NORMALIZED}": "{:f} {:f} {:f}".format(*wtpt_measured_norm),
10663 "${PROFILE}": profile.getDescription(),
10664 "${PROFILE_WHITEPOINT}": "{:f} {:f} {:f}".format(*wtpt_profile),
10665 "${PROFILE_WHITEPOINT_NORMALIZED}": "{:f} {:f} {:f}".format(
10666 *wtpt_profile_norm
10667 ),
10668 "${SIMULATION_PROFILE}": (
10669 sim_profile.getDescription() if sim_profile else ""
10670 ),
10671 "${TRC_GAMMA}": str(
10672 getcfg("measurement_report.trc_gamma") if apply_trc else "null"
10673 ),
10674 "${TRC_GAMMA_TYPE}": str(
10675 getcfg("measurement_report.trc_gamma_type") if apply_trc else ""
10676 ),
10677 "${TRC_OUTPUT_OFFSET}": str(
10678 getcfg("measurement_report.trc_output_offset") if apply_trc else 0
10679 ),
10680 "${TRC}": trc if apply_trc else "",
10681 "${WHITEPOINT_SIMULATION}": str(sim_intent == "a").lower(),
10682 "${WHITEPOINT_SIMULATION_RELATIVE}": str(
10683 sim_intent == "a" and intent == "r"
10684 ).lower(),
10685 "${DEVICELINK_PROFILE}": devlink.getDescription() if devlink else "",
10686 "${TESTCHART}": os.path.basename(chart.filename),
10687 "${ADAPTION}": str(profile.guess_cat(False) or cat),
10688 "${DATETIME}": strftime("%Y-%m-%d %H:%M:%S"),
10689 "${REF}": bytes(ti3_ref).decode(ENC, "replace").replace('"', "&quot;"),
10690 "${MEASURED}": bytes(ti3_joined)
10691 .decode(ENC, "replace")
10692 .replace('"', "&quot;"),
10693 "${CAL_ENTRYCOUNT}": str(cal_entrycount),
10694 "${CAL_RGBLEVELS}": repr(cal_rgblevels),
10695 "${GRAYSCALE}": repr(gray) if gray else "null",
10696 "${REPORT_VERSION}": VERSION_STRING,
10697 "${REPORT_TYPE}": report_type,
10698 }
10699
10700 # create report
10701 try:
10702 report.create(save_path, placeholders2data, getcfg("report.pack_js"))
10703 except OSError as exception:
10704 show_result_dialog(exception, self)
10705 else:
10706 # show report
10707 wx.CallAfter(launch_file, save_path)
10708
10709 def load_cal(self, cal: None | str = None, silent: bool = False) -> bool:
10710 """Load a calibration from a .cal file or ICC profile.
10711
10712 Defaults to currently configured file if cal parameter is not given.
10713
10714 Args:
10715 cal (str, optional): The path to the calibration file or ICC
10716 profile. Defaults to None, which uses the configured
10717 calibration file.
10718 silent (bool, optional): If True, suppresses output messages.
10719 Defaults to False.
10720
10721 Returns:
10722 bool: True if the calibration was loaded successfully, False
10723 otherwise.
10724 """
10725 load_vcgt = getcfg("calibration.autoload") or cal
10726 if not cal:
10727 cal = getcfg("calibration.file", False)
10728 if not cal or not check_set_argyll_bin():
10729 return False
10730 if load_vcgt:
10731 verbose_print(lang.getstr("calibration.loading"))
10732 verbose_print(cal)
10733 if (
10734 not load_vcgt
10735 or self.install_cal(
10736 capture_output=True,
10737 cal=cal,
10738 skip_scripts=True,
10739 silent=silent,
10740 title=lang.getstr("calibration.load_from_cal_or_profile"),
10741 )
10742 is True
10743 ):
10744 if cal.lower().endswith(".icc") or cal.lower().endswith(".icm"):
10745 try:
10746 profile = ICCProfile(cal)
10747 except (OSError, ICCProfileInvalidError) as exception:
10748 print(exception)
10749 profile = None
10750 else:
10751 profile = cal_to_fake_profile(cal)
10752 self.lut_viewer_load_lut(profile=profile)
10753 if silent and load_vcgt:
10754 verbose_print(lang.getstr("success"))
10755 return True
10756 if load_vcgt:
10757 verbose_print(lang.getstr("failure"))
10758 return False
10759
10760 def reset_cal(self, event: wx.Event = None) -> bool:
10761 """Reset video card gamma table to linear.
10762
10763 Args:
10764 event (wx.Event, optional): The event object. Defaults to None.
10765
10766 Returns:
10767 bool: True if the calibration was reset successfully, False
10768 otherwise.
10769 """
10770 if not check_set_argyll_bin():
10771 return False
10772 verbose_print(lang.getstr("calibration.resetting"))
10773 if (
10774 self.install_cal(
10775 capture_output=True,
10776 cal=False,
10777 skip_scripts=True,
10778 silent=not (getcfg("dry_run") and event),
10779 title=lang.getstr("calibration.reset"),
10780 )
10781 is True
10782 ):
10783 profile = ICCProfile()
10784 profile._data = "\0" * 128
10785 profile._tags.desc = TextDescriptionType("", "desc")
10786 profile._tags.vcgt = VideoCardGammaTableType("", "vcgt")
10787 profile._tags.vcgt.update(
10788 {
10789 "channels": 3,
10790 "entryCount": 256,
10791 "entrySize": 1,
10792 "data": [
10793 list(range(256)),
10794 list(range(256)),
10795 list(range(256)),
10796 ],
10797 }
10798 )
10799 profile.size = len(profile.data)
10800 profile.is_loaded = True
10801 self.lut_viewer_load_lut(profile=profile)
10802 verbose_print(lang.getstr("success"))
10803 return True
10804 if not getcfg("dry_run"):
10805 verbose_print(lang.getstr("failure"))
10806 return False
10807
10808 def load_display_profile_cal(
10809 self, event: None | wx.Event = None, lut_viewer_load_lut: bool = True
10810 ) -> bool:
10811 """Load calibration (vcgt) from current display profile.
10812
10813 Args:
10814 event (wx.Event, optional): The event object. Defaults to None.
10815 lut_viewer_load_lut (bool, optional): If True, load the LUT viewer
10816 with the loaded profile. Defaults to True.
10817
10818 Returns:
10819 bool: True if the calibration was loaded successfully, False
10820 otherwise.
10821 """
10822 profile = get_display_profile()
10823 if not check_set_argyll_bin():
10824 return False
10825 if getcfg("calibration.autoload") or event:
10826 verbose_print(lang.getstr("calibration.loading_from_display_profile"))
10827 if profile and profile.filename:
10828 verbose_print(profile.filename)
10829 if (not getcfg("calibration.autoload") and not event) or self.install_cal(
10830 capture_output=True,
10831 cal=True,
10832 skip_scripts=True,
10833 silent=not (getcfg("dry_run") and event),
10834 title=lang.getstr("calibration.load_from_display_profile"),
10835 ) is True:
10836 if lut_viewer_load_lut:
10837 self.lut_viewer_load_lut(profile=profile)
10838 if getcfg("calibration.autoload") or event:
10839 verbose_print(lang.getstr("success"))
10840 return True
10841 if not getcfg("dry_run") and (getcfg("calibration.autoload") or event):
10842 verbose_print(lang.getstr("failure"))
10843 return False
10844
10845 def report_calibrated_handler(self, event: wx.Event) -> None:
10846 """Report on calibrated display and exit.
10847
10848 Args:
10849 event (wx.Event): The event object.
10850 """
10851 self.setup_measurement(self.report)
10852
10853 def report_uncalibrated_handler(self, event: wx.Event) -> None:
10854 """Report on uncalibrated display and exit.
10855
10856 Args:
10857 event (wx.Event): The event object.s
10858 """
10859 self.setup_measurement(self.report, False)
10860
10861 def report(self, report_calibrated: bool = True) -> None:
10862 """Generate a report on the current display.
10863
10864 Args:
10865 report_calibrated (bool): If True, generate a report for a
10866 calibrated display. If False, generate a report for an
10867 uncalibrated display.
10868 """
10869 if not check_set_argyll_bin():
10870 return
10871 if self.measure_auto(self.report, report_calibrated):
10872 return
10873 print("-" * 80)
10874 if report_calibrated:
10875 self.report_title = lang.getstr("report.calibrated")
10876 else:
10877 self.report_title = lang.getstr("report.uncalibrated")
10878 print(self.report_title)
10879 self.worker.interactive = False
10880 self.worker.start(
10881 self.result_consumer,
10882 self.worker.report,
10883 wkwargs={"report_calibrated": report_calibrated},
10884 progress_msg=self.report_title,
10885 pauseable=True,
10886 resume=bool(getattr(self, "measure_auto_after", None)),
10887 )
10888
10889 def result_consumer(self, result: bool | Exception) -> None:
10890 """Generic result consumer.
10891
10892 Shows an info window on success or an info/warn/error dialog if result
10893 was an exception.
10894
10895 Args:
10896 result (bool | Exception): Result of the operation. If True, the
10897 operation was successful. If an Exception, the operation failed.
10898 """
10899 if isinstance(result, Exception) and result:
10900 wx.CallAfter(show_result_dialog, result, self)
10901 else:
10902 stream = FilteredStream(
10903 StringIO(),
10904 discard=self.worker.recent.discard,
10905 triggers=FilteredStream.triggers,
10906 prestrip=self.worker.recent.prestrip,
10907 )
10908 for line in self.worker.output:
10909 stream.write(line)
10910 stream.seek(0)
10911 wx.CallAfter(
10912 self.show_additional_infoframe,
10913 "".join([line for line in stream.readlines() if line.strip()]).strip(),
10914 self.report_title,
10915 )
10916 self.worker.wrapup(False)
10917 self.Show()
10918
10919 def show_additional_infoframe(self, txt: str, title: None | str = None) -> None:
10920 """Show an additional info frame with the given text.
10921
10922 Args:
10923 txt (str): The text to display in the info frame.
10924 title (None | str, optional): The title of the info frame. Defaults to
10925 None.
10926 """
10927 infoframe = LogWindow(self, title=title)
10928 infoframe.Unbind(wx.EVT_CLOSE)
10929 infoframe.Unbind(wx.EVT_MOVE)
10930 infoframe.Unbind(wx.EVT_SIZE)
10931 infoframe.Log(txt)
10932 wx.CallAfter(infoframe.Show)
10933
10934 def calibrate_btn_handler(self, event: wx.Event) -> None:
10935 """Handle calibrate button click event.
10936
10937 Args:
10938 event (wx.Event): The event object.
10939 """
10940 if sys.platform == "darwin" or DEBUG:
10941 self.focus_handler(event)
10942 if self.check_show_macos_bugs_warning(profile=False) is False:
10943 return
10944 if (
10945 not isinstance(event, CustomEvent)
10946 and not getcfg("profile.update")
10947 and (not getcfg("calibration.update") or is_profile())
10948 and getcfg("trc")
10949 ):
10950 update_profile = getcfg("calibration.update") and is_profile()
10951 if update_profile:
10952 msg = lang.getstr("calibration.update_profile_choice")
10953 ok = lang.getstr("profile.update")
10954 else:
10955 msg = lang.getstr("calibration.create_fast_matrix_shaper_choice")
10956 ok = lang.getstr("calibration.create_fast_matrix_shaper")
10957 dlg = ConfirmDialog(
10958 self,
10959 msg=msg,
10960 ok=ok,
10961 alt=lang.getstr("button.calibrate"),
10962 cancel=lang.getstr("cancel"),
10963 bitmap=get_icon(32, "dialog-question"),
10964 )
10965 result = dlg.ShowModal()
10966 dlg.Destroy()
10967 if result == wx.ID_CANCEL:
10968 return
10969 if update_profile and result == wx.ID_OK:
10970 setcfg("profile.update", 1)
10971 else:
10972 result = None
10973 self.worker.dispcal_create_fast_matrix_shaper = result == wx.ID_OK
10974 if (
10975 check_set_argyll_bin()
10976 and self.check_overwrite(".cal")
10977 and (
10978 (
10979 not getcfg("profile.update")
10980 and not self.worker.dispcal_create_fast_matrix_shaper
10981 )
10982 or self.check_overwrite(PROFILE_EXT)
10983 )
10984 ):
10985 self.setup_measurement(self.just_calibrate)
10986
10987 def just_calibrate(self) -> None:
10988 """Just calibrate, optionally creating a fast matrix shaper profile."""
10989 if self.measure_auto(self.just_calibrate):
10990 return
10991 print("-" * 80)
10992 print(lang.getstr("button.calibrate"))
10993 setcfg("calibration.continue_next", 0)
10994 if getcfg("calibration.interactive_display_adjustment") and not getcfg(
10995 "calibration.update"
10996 ):
10997 # Interactive adjustment, do not show progress dialog
10998 self.worker.interactive = True
10999 else:
11000 # No interactive adjustment, show progress dialog
11001 self.worker.interactive = False
11002 self.worker.start_calibration(
11003 self.just_calibrate_finish,
11004 remove=True,
11005 progress_msg=lang.getstr("calibration"),
11006 resume=bool(getattr(self, "measure_auto_after", None)),
11007 )
11008
11009 def just_calibrate_finish(self, result: bool | Exception) -> None:
11010 """Finish calibration.
11011
11012 Args:
11013 result (bool | Exception): Result of the calibration process.
11014 """
11015 start_timers = True
11016 if not isinstance(result, Exception) and result:
11017 wx.CallAfter(self.update_calibration_file_ctrl)
11018 if getcfg("log.autoshow"):
11019 wx.CallAfter(self.infoframe_toggle_handler, show=True)
11020 if (
11021 getcfg("profile.update")
11022 or self.worker.dispcal_create_fast_matrix_shaper
11023 ):
11024 start_timers = False
11025 wx.CallAfter(
11026 self.profile_finish,
11027 True,
11028 success_msg=lang.getstr("calibration.complete"),
11029 install_3dlut=getcfg("3dlut.create"),
11030 )
11031 elif getcfg("trc"):
11032 wx.CallAfter(self.load_cal, silent=True)
11033 wx.CallAfter(
11034 InfoDialog,
11035 self,
11036 msg=lang.getstr("calibration.complete"),
11037 ok=lang.getstr("ok"),
11038 bitmap=get_icon(32, "dialog-information"),
11039 )
11040 elif isinstance(result, Exception):
11041 wx.CallAfter(show_result_dialog, result, self)
11042 elif not getcfg("dry_run"):
11043 wx.CallAfter(
11044 InfoDialog,
11045 self,
11046 msg=lang.getstr("calibration.incomplete"),
11047 ok=lang.getstr("ok"),
11048 bitmap=get_icon(32, "dialog-error"),
11049 )
11050 self.Show(start_timers=start_timers)
11051
11052 def setup_measurement(
11053 self,
11054 pending_function: Callable,
11055 *pending_function_args: tuple,
11056 **pending_function_kwargs: dict,
11057 ) -> None:
11058 """Setup measurement.
11059
11060 Args:
11061 pending_function (callable): Function to call after setup.
11062 *pending_function_args: Positional arguments for pending_function.
11063 **pending_function_kwargs: Keyword arguments for pending_function.
11064 """
11065 display_name = config.get_display_name(None, True)
11066 if display_name == "Web @ localhost" or display_name.startswith("Chromecast "):
11067 for name, patterngenerator in list(self.worker.patterngenerators.items()):
11068 if (
11069 display_name.startswith("Chromecast ")
11070 and ChromeCastPatternGenerator
11071 and isinstance(patterngenerator, ChromeCastPatternGenerator)
11072 ):
11073 # Chromecast uses a single client session; reset it so dispwin
11074 # can establish a fresh connection for each run.
11075 patterngenerator.disconnect_client()
11076 self.worker.patterngenerators.pop(name)
11077 elif display_name == "Web @ localhost" and isinstance(
11078 patterngenerator, WebWinHTTPPatternGeneratorServer
11079 ):
11080 # Keep WebWin server running and reusable between setup/test
11081 # and interactive adjustment steps to avoid reconnect churn.
11082 continue
11083 elif not self.setup_patterngenerator(self):
11084 return
11085 writecfg()
11086 if sys.platform == "darwin":
11087 # Pre-create worker measurement sounds on the main thread. On
11088 # macOS, first-time sound/backend setup from the worker thread can
11089 # trigger Cocoa initialization via ctypes and crash.
11090 with contextlib.suppress(Exception):
11091 self.worker._init_sounds(dummy=False)
11092 if pending_function_kwargs.get("wrapup", True):
11093 self.worker.wrapup(False)
11094 pending_function_kwargs.pop("wrapup", None)
11095 self.HideAll()
11096 self.set_pending_function(
11097 pending_function, *pending_function_args, **pending_function_kwargs
11098 )
11099 if (
11100 config.is_virtual_display()
11101 and display_name not in ("Resolve", "Prisma")
11102 and not display_name.startswith("Chromecast ")
11103 and not display_name.startswith("Prisma ")
11104 ) or getcfg("dry_run"):
11105 self.call_pending_function()
11106 elif (
11107 sys.platform in ("darwin", "win32")
11108 or ISEXE
11109 or self.worker._use_patternwindow
11110 ):
11111 # Preliminary Wayland support. This still needs a lot
11112 # of work as Argyll doesn't support Wayland natively yet,
11113 # so we use virtual display to drive our own patch window.
11114 self.measureframe.Show()
11115 else:
11116 wx.CallAfter(self.start_measureframe_subprocess)
11117
11118 def setup_observer_ctrl(self) -> None:
11119 """Setup observer control.
11120
11121 Choice of available observers varies with ArgyllCMS version.
11122 """
11123 self.observers_ab = {}
11124 for observer in config.VALID_VALUES["observer"]:
11125 self.observers_ab[observer] = lang.getstr("observer." + observer)
11126 self.observers_ba = swap_dict_keys_values(self.observers_ab)
11127 self.observer_ctrl.SetItems(list(self.observers_ab.values()))
11128
11129 def setup_patterngenerator(
11130 self,
11131 parent: None | wx.Window = None,
11132 title: str = APPNAME,
11133 upload: bool = False,
11134 ) -> bool:
11135 """Setup pattern generator.
11136
11137 Args:
11138 parent (None | wx.Window, optional): Parent window for dialogs.
11139 title (str, optional): Title for dialogs.
11140 upload (bool, optional): If True, show preset selection and
11141 filename for upload to Prisma.
11142
11143 Returns:
11144 bool: True if successful, False if not.
11145 """
11146 if not parent:
11147 parent = self
11148 retval = True
11149 display_name = config.get_display_name(None, True)
11150 if display_name == "Prisma":
11151 # Ask for prisma hostname or IP
11152 dlg = ConfirmDialog(
11153 parent,
11154 title=title,
11155 msg=lang.getstr("patterngenerator.prisma.specify_host"),
11156 ok=lang.getstr("continue"),
11157 cancel=lang.getstr("cancel"),
11158 bitmap=get_icon(32, "dialog-question"),
11159 )
11160 host = getcfg("patterngenerator.prisma.host")
11161 dlg.host = wx.ComboBox(dlg, -1, host)
11162
11163 def check_host_empty(event: wx.Event) -> None:
11164 """Check if the host input is empty and enable/disable the OK button.
11165
11166 Args:
11167 event (wx.Event): The event object.
11168 """
11169 dlg.ok.Enable(bool(dlg.host.GetValue()))
11170
11171 dlg.host.Bind(wx.EVT_TEXT, check_host_empty)
11172 dlg.host.Bind(wx.EVT_COMBOBOX, check_host_empty)
11173 dlg.sizer3.Add(
11174 dlg.host, 0, flag=wx.TOP | wx.ALIGN_LEFT | wx.EXPAND, border=12
11175 )
11176 dlg.errormsg = wx.StaticText(dlg, -1, "")
11177 dlg.sizer3.Add(
11178 dlg.errormsg, 0, flag=wx.TOP | wx.ALIGN_LEFT | wx.EXPAND, border=6
11179 )
11180 if upload:
11181 # Show preset selection & filename
11182 sizer = wx.BoxSizer(wx.HORIZONTAL)
11183 dlg.sizer3.Add(
11184 sizer, 0, flag=wx.TOP | wx.ALIGN_LEFT | wx.EXPAND, border=12
11185 )
11186 sizer.Add(
11187 wx.StaticText(dlg, -1, lang.getstr("3dlut.holder.assign_preset")),
11188 flag=wx.ALIGN_CENTER_VERTICAL,
11189 )
11190 preset = wx.Choice(
11191 dlg,
11192 -1,
11193 choices=config.VALID_VALUES["patterngenerator.prisma.preset"],
11194 )
11195 preset.SetStringSelection(getcfg("patterngenerator.prisma.preset"))
11196 sizer.Add(preset, flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=8)
11197 # Filename
11198 basename = os.path.basename(getcfg("3dlut.input.profile"))
11199 name = os.path.splitext(basename)[0]
11200 # Shorten long name
11201 gamut = {
11202 "SMPTE_RP145_NTSC": "NTSC",
11203 "EBU3213_PAL": "PAL",
11204 "SMPTE431_P3": "P3",
11205 }.get(name, name)
11206 # Use file created date & time for filename
11207 filename = strftime(
11208 f"{gamut}-%Y%m%dT%H%M%S.3dl",
11209 localtime(os.stat(self.lut3d_path).st_ctime),
11210 )
11211 dlg.sizer3.Add(
11212 wx.StaticText(
11213 dlg,
11214 -1,
11215 "{}: {}".format(lang.getstr("filename.upload"), filename),
11216 ),
11217 flag=wx.TOP | wx.ALIGN_LEFT,
11218 border=12,
11219 )
11220 dlg.sizer0.SetSizeHints(dlg)
11221 dlg.sizer0.Layout()
11222
11223 def check_host(host: str) -> None:
11224 """Check if the given host is reachable.
11225
11226 Args:
11227 host (str): The host to check, either an IP address or a
11228 hostname.
11229 """
11230 try:
11231 ip = socket.gethostbyname(host)
11232 self.worker.patterngenerator.host = ip
11233 self.worker.patterngenerator.connect()
11234 except OSError as exception:
11235 result = exception
11236 else:
11237 result = ip
11238 wx.CallAfter(check_host_consumer, result)
11239
11240 def check_host_consumer(result: str | Exception) -> None:
11241 """Consumer for check_host result.
11242
11243 Args:
11244 result (str | Exception): Result of the host check.
11245 If successful, a string with the host IP address.
11246 If an error occurred, an Exception.
11247 """
11248 if not dlg:
11249 return
11250 if isinstance(result, Exception):
11251 dlg.Freeze()
11252 if isinstance(result, socket.gaierror):
11253 dlg.errormsg.Label = lang.getstr("host.invalid.lookup_failed")
11254 else:
11255 width = dlg.errormsg.Size[0]
11256 dlg.errormsg.Label = str(result)
11257 dlg.errormsg.Wrap(width)
11258 dlg.errormsg.ForegroundColour = wx.Colour(204, 0, 0)
11259 dlg.ok.Enable()
11260 dlg.sizer0.SetSizeHints(dlg)
11261 dlg.sizer0.Layout()
11262 dlg.Refresh()
11263 dlg.Thaw()
11264 wx.Bell()
11265 else:
11266 dlg.EndModal(wx.ID_OK)
11267
11268 def check_host_handler(event: wx.Event) -> None:
11269 host = dlg.host.GetValue()
11270 if host:
11271 dlg.Freeze()
11272 dlg.errormsg.Label = lang.getstr("please_wait")
11273 dlg.errormsg.ForegroundColour = wx.SystemSettings.GetColour(
11274 wx.SYS_COLOUR_WINDOWTEXT
11275 )
11276 dlg.ok.Disable()
11277 dlg.sizer0.SetSizeHints(dlg)
11278 dlg.sizer0.Layout()
11279 dlg.Refresh()
11280 dlg.Thaw()
11281 thread = threading.Thread(
11282 target=check_host,
11283 name=f"PrismaPatternGenerator.CheckHost({host})",
11284 args=(host,),
11285 )
11286 thread.start()
11287 else:
11288 wx.Bell()
11289
11290 def add_client(addr_client: tuple[str, dict]) -> None:
11291 """Add a discovered Prisma pattern generator client to the dialog.
11292
11293 Args:
11294 addr_client (tuple): A tuple containing the address and
11295 client information. The first element is the address,
11296 and the second element is a dictionary with client
11297 information, including the 'name'.
11298 """
11299 if not dlg:
11300 return
11301 name = addr_client[1]["name"]
11302 if sys.platform != "win32" and not name.endswith(".local"):
11303 name += ".local"
11304 dlg.host.Append(name)
11305 if not dlg.host.GetValue():
11306 dlg.host.SetSelection(0)
11307 check_host_empty(None)
11308
11309 def discover() -> None:
11310 """Discover Prisma pattern generator clients."""
11311 self.worker.patterngenerator.bind(
11312 "on_client_added",
11313 lambda addr_client: wx.CallAfter(add_client, addr_client),
11314 )
11315 self.worker.patterngenerator.listen()
11316 self.worker.patterngenerator.announce()
11317
11318 thread = threading.Thread(
11319 target=discover, name="PrismaPatternGenerator.ClientDiscovery"
11320 )
11321 dlg.ok.Bind(wx.EVT_BUTTON, check_host_handler)
11322 dlg.ok.Enable(bool(host))
11323 if self.worker.patterngenerator:
11324 self.worker.patterngenerator.disconnect_client()
11325 else:
11326 self.worker.setup_patterngenerator()
11327 wx.CallAfter(thread.start)
11328 result = dlg.ShowModal()
11329 self.worker.patterngenerator.listening = False
11330 host = dlg.host.GetValue()
11331 if result == wx.ID_OK and upload:
11332 setcfg("patterngenerator.prisma.preset", preset.GetStringSelection())
11333 retval = filename
11334 dlg.Destroy()
11335 if result != wx.ID_OK or not host:
11336 return None
11337 setcfg("patterngenerator.prisma.host", host)
11338 elif display_name == "madVR":
11339 # Connect to madTPG (launch local instance under Windows)
11340 def closedlg(self, action: int = wx.ID_OK) -> None: # noqa: D417, ANN001
11341 """Close the dialog if it exists.
11342
11343 Args:
11344 action (int): The action to take when closing the dialog.
11345 """
11346 dlg = getattr(self, "setup_patterngenerator_waitdialog", None)
11347 if dlg:
11348 dlg.EndModal(action)
11349 self.setup_patterngenerator_waitdialog = None
11350
11351 cancel_event = threading.Event()
11352
11353 def connect(self) -> None: # noqa: ANN001
11354 """Connect to madTPG and handle the connection result."""
11355 exception = None
11356 action = None
11357 try:
11358 if not self.worker.madtpg_connect():
11359 raise Error(lang.getstr("madtpg.launch.failure"))
11360 except Exception as e:
11361 action = wx.ID_CLOSE
11362 exception = e
11363 else:
11364 action = wx.ID_OK
11365 finally:
11366 if not cancel_event.is_set():
11367 wx.CallAfter(closedlg, self, action)
11368 if action != wx.ID_OK:
11369 wx.CallAfter(show_result_dialog, exception, parent)
11370
11371 thread = threading.Thread(
11372 target=connect, name="madTPG_Connect", args=(self,)
11373 )
11374 thread.start()
11375 sleep(0.2)
11376 if thread.is_alive():
11377 dlg = ConfirmDialog(
11378 parent,
11379 title=title,
11380 msg=lang.getstr("please_wait"),
11381 cancel=lang.getstr("cancel"),
11382 bitmap=get_icon(32, "dialog-information"),
11383 )
11384 dlg.ok.Hide()
11385 dlg.sizer0.SetSizeHints(dlg)
11386 dlg.sizer0.Layout()
11387 self.setup_patterngenerator_waitdialog = dlg
11388 result = dlg.ShowModal()
11389 dlg.Destroy()
11390 if result == wx.ID_CANCEL:
11391 cancel_event.set()
11392 if hasattr(self.worker, "madtpg") and hasattr(
11393 self.worker.madtpg, "shutdown"
11394 ):
11395 self.worker.madtpg.shutdown()
11396 return None
11397 if result != wx.ID_OK:
11398 # Error
11399 return False
11400 elif display_name in ("Resolve", "Web @ localhost") or display_name.startswith(
11401 "Chromecast "
11402 ):
11403 logfile = LineCache(3)
11404 try:
11405 self.worker.setup_patterngenerator(logfile)
11406 except Exception as exception:
11407 show_result_dialog(exception, parent)
11408 return None
11409 if not hasattr(self.worker.patterngenerator, "conn"):
11410 # Wait for connection
11411 def closedlg(self) -> None: # noqa: ANN001
11412 """Close the dialog if it exists."""
11413 dlg = getattr(self, "setup_patterngenerator_waitdialog", None)
11414 if dlg:
11415 dlg.EndModal(wx.ID_OK)
11416 self.setup_patterngenerator_waitdialog = None
11417
11418 def wait_for_connection(self) -> None: # noqa: ANN001
11419 """Wait for the pattern generator connection to be established."""
11420 self.worker.patterngenerator.wait()
11421 if hasattr(self.worker.patterngenerator, "conn"):
11422 # Close dialog
11423 wx.CallAfter(closedlg, self)
11424
11425 threading.Thread(
11426 target=wait_for_connection,
11427 name="PatternGeneratorConnectionListener",
11428 args=(self,),
11429 ).start()
11430 while not logfile.read():
11431 sleep(0.1)
11432 dlg = ConfirmDialog(
11433 parent,
11434 title=title,
11435 msg=logfile.read(),
11436 cancel=lang.getstr("cancel"),
11437 bitmap=get_icon(32, "dialog-information"),
11438 )
11439 dlg.ok.Hide()
11440 dlg.sizer0.SetSizeHints(dlg)
11441 dlg.sizer0.Layout()
11442 self.setup_patterngenerator_waitdialog = dlg
11443 result = dlg.ShowModal()
11444 dlg.Destroy()
11445 if result == wx.ID_CANCEL:
11446 self.worker.patterngenerator.listening = False
11447 return None
11448 elif (
11449 not config.is_uncalibratable_display()
11450 and not self.worker.has_lut_access()
11451 and not self.worker.has_separate_lut_access()
11452 and not self.worker._use_patternwindow
11453 ):
11454 show_result_dialog(Error(lang.getstr("lut_access.unsupported")), self)
11455 retval = False
11456 return retval
11457
11458 def start_measureframe_subprocess(self) -> None:
11459 """Start the measureframe subprocess."""
11460 script = (
11461 "import sys;"
11462 f"sys.path.insert(0, {PYDIR!r});"
11463 "from DisplayCAL import wx_measure_frame;"
11464 "wx_measure_frame.main();"
11465 "sys.exit(wx_measure_frame.MeasureFrame.exitcode)"
11466 )
11467 args = [
11468 EXE,
11469 "-c",
11470 script,
11471 ]
11472 env = os.environ.copy()
11473 if wx.Display.GetCount() == 1 and len(self.worker.display_rects) > 1:
11474 # Separate X screens, TwinView or similar
11475 display = wx.Display(0)
11476 geometry = display.Geometry
11477 union = wx.Rect()
11478 xy = []
11479 for rect in self.worker.display_rects:
11480 if rect[:2] in xy or rect[2:] == geometry[2:]:
11481 # Overlapping x y coordinates or screen filling whole
11482 # reported geometry, so assume separate X screens
11483 union = None
11484 break
11485 xy.append(rect[:2])
11486 union = union.Union(rect)
11487 if union == geometry:
11488 # Assume TwinView or similar where Argyll enumerates 1+n
11489 # displays but wx only 'sees' one that is the union of them
11490 pass
11491 else:
11492 # Assume separate X screens
11493 display_no = getcfg("display.number") - 1
11494 x_hostname, x_display, x_screen = util_x.get_display()
11495 x_screen = display_no
11496 try:
11497 from DisplayCAL import real_display_size_mm
11498 except ImportError as exception:
11499 InfoDialog(
11500 self,
11501 msg=str(exception),
11502 ok=lang.getstr("ok"),
11503 bitmap=get_icon(32, "dialog-warning"),
11504 )
11505 else:
11506 display = real_display_size_mm.get_x_display(display_no)
11507 if display:
11508 x_hostname, x_display, x_screen = display
11509 env["DISPLAY"] = f"{x_hostname}:{x_display}.{x_screen}"
11510 delayedresult.startWorker(
11511 self.measureframe_consumer, self.measureframe_subprocess, wargs=(args, env)
11512 )
11513
11514 def measureframe_subprocess(self, args: tuple, env: dict) -> tuple[int, str]:
11515 """Run the measureframe subprocess.
11516
11517 Args:
11518 args (tuple): The command to run.
11519 env (dict): The environment variables to set.
11520
11521 Returns:
11522 tuple[int, str]: A tuple containing the return code and stderr
11523 output.
11524 """
11525 returncode = -1
11526 try:
11527 p = sp.Popen(
11528 args,
11529 stdin=sp.PIPE,
11530 stdout=sp.PIPE,
11531 stderr=sp.PIPE,
11532 env=env,
11533 )
11534 except Exception as exception:
11535 stderr = safe_str(exception)
11536 else:
11537 self._measureframe_subprocess = p
11538 stdout, stderr = p.communicate()
11539 returncode = self._measureframe_subprocess.returncode
11540 del self._measureframe_subprocess
11541 return returncode, stderr
11542
11543 def measureframe_consumer(
11544 self, delayed_result: delayedresult.DelayedResult
11545 ) -> None:
11546 """Consumer for the measureframe subprocess.
11547
11548 Args:
11549 delayed_result (delayedResult.DelayedResult): The result of the
11550 measureframe subprocess.
11551 """
11552 returncode, stderr = delayed_result.get()
11553 if returncode != -1:
11554 config.initcfg()
11555 self.get_set_display()
11556 if returncode != 255:
11557 self.Show(start_timers=True)
11558 self.restore_measurement_mode()
11559 self.restore_testchart()
11560 if returncode != 0 and stderr and stderr.strip():
11561 InfoDialog(
11562 self,
11563 msg=str(stderr.strip()),
11564 ok=lang.getstr("ok"),
11565 bitmap=get_icon(32, "dialog-error"),
11566 )
11567 else:
11568 self.call_pending_function()
11569
11570 def get_set_display(self, update_ccmx_items: bool = False) -> None:
11571 """Set the display selection to the configured display number.
11572
11573 Args:
11574 update_ccmx_items (bool): If True, update the colorimeter
11575 correction matrix items in the UI.
11576 """
11577 debug_print("[D] get_set_display")
11578 if self.worker.displays:
11579 self.display_ctrl.SetSelection(
11580 min(
11581 max(0, len(self.worker.displays) - 1),
11582 max(0, getcfg("display.number") - 1),
11583 )
11584 )
11585 self.display_ctrl_handler(
11586 CustomEvent(wx.EVT_CHOICE.evtType[0], self.display_ctrl),
11587 load_lut=False,
11588 update_ccmx_items=update_ccmx_items,
11589 )
11590
11591 def get_ccxx_measurement_modes(
11592 self,
11593 instrument_name: str,
11594 swap: bool = False,
11595 ) -> dict:
11596 """Get measurement modes suitable for colorimeter correction creation.
11597
11598 Args:
11599 instrument_name (str): The name of the instrument.
11600 swap (bool): If True, swap the keys and values in the returned
11601 dictionary.
11602 """
11603 # IMPORTANT: Make changes aswell in the following locations:
11604 # - DisplayCAL.MainFrame.create_colorimeter_correction_handler
11605 # - DisplayCAL.MainFrame.set_ccxx_measurement_mode
11606 # - DisplayCAL.MainFrame.update_colorimeter_correction_matrix_ctrl_items
11607 # - worker.Worker.check_add_display_type_base_id
11608 # - worker.Worker.instrument_can_use_ccxx
11609 modes = {
11610 "ColorHug": {
11611 "F": lang.getstr("measurement_mode.factory"),
11612 "R": lang.getstr("measurement_mode.raw"),
11613 },
11614 "ColorHug2": {
11615 "F": lang.getstr("measurement_mode.factory"),
11616 "R": lang.getstr("measurement_mode.raw"),
11617 },
11618 "ColorMunki Smile": {"f": lang.getstr("measurement_mode.lcd.ccfl")},
11619 "Colorimtre HCFR": {"R": lang.getstr("measurement_mode.raw")},
11620 "K-10": {"F": lang.getstr("measurement_mode.factory")},
11621 "SpyderX": {
11622 "l": lang.getstr("measurement_mode.lcd"),
11623 "e": lang.getstr("measurement_mode.lcd.white_led"),
11624 "b": lang.getstr("measurement_mode.lcd.wide_gamut.led"),
11625 "i": lang.getstr("measurement_mode.lcd.wide_gamut.gb_led"),
11626 },
11627 "SpyderX2": {
11628 "l": lang.getstr("measurement_mode.lcd"),
11629 "e": lang.getstr("measurement_mode.lcd.white_led"),
11630 "b": lang.getstr("measurement_mode.lcd.wide_gamut.led"),
11631 "i": lang.getstr("measurement_mode.lcd.wide_gamut.gb_led"),
11632 "h": lang.getstr(
11633 "measurement_mode.lcd.high_brightness", "High brightness"
11634 ),
11635 },
11636 "Spyder 2024": {
11637 "l": lang.getstr("measurement_mode.lcd"),
11638 "e": lang.getstr("measurement_mode.lcd.white_led"),
11639 "b": lang.getstr("measurement_mode.lcd.wide_gamut.led"),
11640 "i": lang.getstr("measurement_mode.lcd.wide_gamut.gb_led"),
11641 "h": lang.getstr(
11642 "measurement_mode.lcd.high_brightness", "High brightness"
11643 ),
11644 "o": lang.getstr("measurement_mode.lcd.oled", "OLED"),
11645 "m": lang.getstr("measurement_mode.lcd.mini_led", "Mini-LED"),
11646 },
11647 }.get(
11648 instrument_name,
11649 {
11650 "c": lang.getstr("measurement_mode.refresh"),
11651 "l": lang.getstr("measurement_mode.lcd"),
11652 },
11653 )
11654 if swap:
11655 modes = swap_dict_keys_values(modes)
11656 return modes
11657
11658 def set_ccxx_measurement_mode(self) -> None:
11659 """Set measurement mode suitable for colorimeter correction creation."""
11660 # IMPORTANT: Make changes aswell in the following locations:
11661 # - DisplayCAL.MainFrame.create_colorimeter_correction_handler
11662 # - DisplayCAL.MainFrame.get_ccxx_measurement_modes
11663 # - DisplayCAL.MainFrame.update_colorimeter_correction_matrix_ctrl_items
11664 # - worker.Worker.check_add_display_type_base_id
11665 # - worker.Worker.instrument_can_use_ccxx
11666 measurement_mode = None
11667 if getcfg("measurement_mode") == "auto":
11668 # Make changes in worker.Worker.add_instrument_features too!
11669 if self.worker.get_instrument_name() == "ColorHug":
11670 measurement_mode = "R"
11671 elif self.worker.get_instrument_name() == "ColorHug2":
11672 measurement_mode = "F"
11673 else:
11674 measurement_mode = "l"
11675 elif self.worker.get_instrument_name() in ("ColorHug", "ColorHug2") and getcfg(
11676 "measurement_mode"
11677 ) not in ("F", "R"):
11678 # Automatically set factory measurement mode if not already
11679 # factory or raw measurement mode
11680 measurement_mode = "F"
11681 elif (
11682 self.worker.get_instrument_name() == "ColorMunki Smile"
11683 and getcfg("measurement_mode") != "f"
11684 ):
11685 # Automatically set LCD measurement mode if not already
11686 # LCD CCFL measurement mode
11687 measurement_mode = "f"
11688 elif (
11689 self.worker.get_instrument_name() == "Colorimtre HCFR"
11690 and getcfg("measurement_mode") != "R"
11691 ):
11692 # Automatically set raw measurement mode if not already
11693 # raw measurement mode
11694 measurement_mode = "R"
11695 elif self.worker.get_instrument_name() in ("Spyder4", "Spyder5") and getcfg(
11696 "measurement_mode"
11697 ) not in ("l", "c"):
11698 # Automatically set LCD measurement mode if not already
11699 # LCD or refresh measurement mode
11700 measurement_mode = "l"
11701 elif (
11702 self.worker.get_instrument_name() == "SpyderX"
11703 and getcfg("measurement_mode") != "l"
11704 ):
11705 # Automatically set LCD/generic measurement mode if not already
11706 # LCD/generic measurement mode
11707 measurement_mode = "l"
11708 if not getcfg("measurement_mode.backup", False):
11709 setcfg("measurement_mode.backup", getcfg("measurement_mode"))
11710 if measurement_mode:
11711 setcfg("measurement_mode", measurement_mode)
11712 self.update_measurement_mode()
11713
11714 def set_pending_function(
11715 self,
11716 pending_function: Callable,
11717 *pending_function_args: tuple,
11718 **pending_function_kwargs: dict,
11719 ) -> None:
11720 """Set the pending function to be called later.
11721
11722 Args:
11723 pending_function (callable): The function to call later.
11724 pending_function_args (tuple): Positional arguments for the
11725 function.
11726 pending_function_kwargs (dict): Keyword arguments for the function.
11727 """
11728 self.pending_function = pending_function
11729 self.pending_function_args = pending_function_args
11730 self.pending_function_kwargs = pending_function_kwargs
11731
11732 def call_pending_function(self) -> None:
11733 """Call the pending function with its arguments."""
11734 # Needed for proper display updates under GNOME
11735 writecfg()
11736 if (
11737 sys.platform in ("darwin", "win32")
11738 or ISEXE
11739 or self.worker._use_patternwindow
11740 ):
11741 if self.worker._use_patternwindow:
11742 # Preliminary Wayland support. This still needs a lot
11743 # of work as Argyll doesn't support Wayland natively yet,
11744 # so we use virtual display to drive our own patch window.
11745 self.measureframe.show_controls(False)
11746 else:
11747 self.measureframe.Hide()
11748 debug_print(
11749 "[D] Calling pending function with args:", self.pending_function_args
11750 )
11751 wx.CallLater(
11752 100,
11753 self.pending_function,
11754 *self.pending_function_args,
11755 **self.pending_function_kwargs,
11756 )
11757 self.pending_function = None
11758
11759 def calibrate_and_profile_btn_handler(self, event: wx.Event) -> None:
11760 """Setup calibration and characterization measurements.
11761
11762 Args:
11763 event (wx.Event): The event that triggered this handler.
11764 """
11765 if sys.platform == "darwin" or DEBUG:
11766 self.focus_handler(event)
11767 if self.check_show_macos_bugs_warning() is False:
11768 return
11769 if (
11770 check_set_argyll_bin()
11771 and self.check_overwrite(".cal")
11772 and self.check_overwrite(".ti3")
11773 and self.check_overwrite(PROFILE_EXT)
11774 ):
11775 self.setup_measurement(self.calibrate_and_profile)
11776
11777 def calibrate_and_profile(self) -> None:
11778 """Start calibration measurements."""
11779 if self.measure_auto(self.calibrate_and_profile):
11780 return
11781 print("-" * 80)
11782 print(lang.getstr("button.calibrate_and_profile").replace("&&", "&"))
11783 setcfg("calibration.continue_next", 1)
11784 self.worker.dispcal_create_fast_matrix_shaper = False
11785 self.worker.dispread_after_dispcal = True
11786 if getcfg("calibration.interactive_display_adjustment") and not getcfg(
11787 "calibration.update"
11788 ):
11789 # Interactive adjustment, do not show progress dialog
11790 self.worker.interactive = True
11791 else:
11792 # No interactive adjustment, show progress dialog
11793 self.worker.interactive = False
11794 self.worker.start_calibration(
11795 self.calibrate_finish,
11796 progress_msg=lang.getstr("calibration"),
11797 continue_next=True,
11798 resume=bool(getattr(self, "measure_auto_after", None)),
11799 )
11800
11801 def calibrate_finish(self, result: bool | Exception) -> None:
11802 """Start characterization measurements.
11803
11804 Returns:
11805 result (bool | Exception): True if the calibration was successful,
11806 an Exception if there was an error, or False if the operation
11807 was cancelled.
11808 """
11809 self.worker.interactive = False
11810 if not isinstance(result, Exception) and result:
11811 wx.CallAfter(self.update_calibration_file_ctrl)
11812 cal = True if getcfg("trc") else get_data_path("linear.cal")
11813 self.worker.start_measurement(
11814 self.calibrate_and_profile_finish,
11815 apply_calibration=cal,
11816 progress_msg=lang.getstr("measuring.characterization"),
11817 resume=True,
11818 continue_next=True,
11819 )
11820 else:
11821 if isinstance(result, Exception):
11822 wx.CallAfter(show_result_dialog, result, self)
11823 self.Show()
11824
11825 def calibrate_and_profile_finish(self, result: bool | Exception) -> None:
11826 """Build profile from characterization measurements.
11827
11828 Returns:
11829 result (bool | Exception): True if the profile was created
11830 successfully, an Exception if there was an error, or False if
11831 the operation was cancelled.
11832 """
11833 start_timers = True
11834 if not isinstance(result, Exception) and result:
11835 result = self.check_copy_ti3()
11836 if not isinstance(result, Exception) and result:
11837 start_timers = False
11838 wx.CallAfter(
11839 self.start_profile_worker,
11840 lang.getstr("calibration_profiling.complete"),
11841 resume=True,
11842 )
11843 elif isinstance(result, Exception):
11844 wx.CallAfter(show_result_dialog, result, self)
11845 elif not getcfg("dry_run"):
11846 wx.CallAfter(
11847 InfoDialog,
11848 self,
11849 msg=lang.getstr("profiling.incomplete"),
11850 ok=lang.getstr("ok"),
11851 bitmap=get_icon(32, "dialog-error"),
11852 )
11853 self.Show(start_timers=start_timers)
11854
11855 def check_copy_ti3(self) -> bool | Exception:
11856 """Check if the measurement file is valid and copy it if necessary.
11857
11858 Returns:
11859 bool | Exception: The result, True if the measurement file is valid
11860 and copied successfully, an Exception if there was an error, or
11861 False if the operation was cancelled.
11862 """
11863 result = self.measurement_file_check_confirm(
11864 parent=getattr(self.worker, "progress_wnd", self)
11865 )
11866 if isinstance(result, tuple):
11867 result = self.worker.wrapup(copy=True, remove=False, ext_filter=[".ti3"])
11868 if isinstance(result, Exception) or not result:
11869 self.worker.stop_progress()
11870 return result
11871
11872 def start_profile_worker(self, success_msg: str, resume: bool = False) -> None:
11873 """Start the profile worker to create a profile from measurements.
11874
11875 Args:
11876 success_msg (str): The message to show on successful profile creation.
11877 resume (bool): If True, resume the profile creation process.
11878 """
11879 name = getcfg("profile.name.expanded")
11880 path = os.path.join(getcfg("profile.save_path"), name, name + PROFILE_EXT)
11881 self.lut3d_set_path(path, set_mr_sim_profile=False)
11882 continue_next = getcfg("3dlut.create") and not os.path.isfile(self.lut3d_path)
11883 self.worker.interactive = False
11884 self.worker.start(
11885 self.profile_finish,
11886 self.worker.create_profile,
11887 ckwargs={
11888 "success_msg": success_msg,
11889 "failure_msg": lang.getstr("profiling.incomplete"),
11890 "install_3dlut": getcfg("3dlut.create"),
11891 },
11892 wkwargs={"tags": True},
11893 progress_msg=lang.getstr("create_profile"),
11894 resume=resume,
11895 continue_next=continue_next,
11896 )
11897
11898 def gamap_btn_handler(self, event: wx.Event) -> None:
11899 """Toggle the gamap frame.
11900
11901 Args:
11902 event (wx.Event): The event that triggered this handler.
11903 """
11904 if not hasattr(self, "gamapframe"):
11905 self.init_gamapframe()
11906 if self.gamapframe.IsShownOnScreen():
11907 self.gamapframe.Raise()
11908 else:
11909 self.gamapframe.Center()
11910 self.gamapframe.SetPosition(
11911 (
11912 -1,
11913 self.GetPosition()[1]
11914 + self.GetSize()[1]
11915 - self.gamapframe.GetSize()[1]
11916 - 100,
11917 )
11918 )
11919 self.gamapframe.Show(not self.gamapframe.IsShownOnScreen())
11920
11921 def current_cal_choice(self, silent: bool = False) -> None | bool | int | str:
11922 """Prompt user to keep, clear, or embed current calibration.
11923
11924 Args:
11925 silent (bool): If True, do not show any dialogs, just return the
11926 result.
11927
11928 Returns:
11929 None: If the current calibration should be embedded.
11930 bool: False, if no calibration should be embedded.
11931 str: The filename, if a .cal file should be used.
11932 int: wx.ID_CANCEL if whole operation should be cancelled.
11933 """
11934 if config.is_uncalibratable_display():
11935 return False
11936 cal = getcfg("calibration.file", False)
11937 options_dispcal = None
11938 if cal:
11939 filename, ext = os.path.splitext(cal)
11940 if ext.lower() in (".icc", ".icm"):
11941 self.worker.options_dispcal = []
11942 try:
11943 profile = ICCProfile(cal)
11944 except (OSError, ICCProfileInvalidError):
11945 InfoDialog(
11946 self,
11947 msg=lang.getstr("profile.invalid") + "\n" + cal,
11948 ok=lang.getstr("ok"),
11949 bitmap=get_icon(32, "dialog-error"),
11950 )
11951 self.start_timers()
11952 return wx.ID_CANCEL
11953 else:
11954 # get dispcal options if present
11955 options_dispcal = [
11956 f"-{arg}" for arg in get_options_from_profile(profile)[0]
11957 ]
11958 cal = f"{filename}.cal" if os.path.isfile(filename + ".cal") else None
11959 if self.worker.argyll_version < [1, 1, 0] or not self.worker.has_lut_access():
11960 # If Argyll < 1.1, we cannot save the current VideoLUT to use it.
11961 # For web, there is no point in using the current VideoLUT as it
11962 # may not be from the display we render on (and we cannot save it
11963 # to begin with as there is no VideoLUT access).
11964 # So an existing .cal file or no calibration are the only options.
11965 can_use_current_cal = False
11966 else:
11967 can_use_current_cal = True
11968 if cal:
11969 msgstr = "dialog.cal_info"
11970 icon = "information"
11971 elif can_use_current_cal:
11972 msgstr = "dialog.current_cal_warning"
11973 icon = "warning"
11974 else:
11975 msgstr = "dialog.linear_cal_info"
11976 icon = "information"
11977 dlg = ConfirmDialog(
11978 self,
11979 msg=lang.getstr(msgstr, os.path.basename(cal) if cal else None),
11980 ok=lang.getstr("continue"),
11981 cancel=lang.getstr("cancel"),
11982 bitmap=get_icon(32, f"dialog-{icon}"),
11983 )
11984 border = 12
11985 if can_use_current_cal or cal:
11986 dlg.reset_cal_ctrl = wx.CheckBox(
11987 dlg, -1, lang.getstr("calibration.use_linear_instead")
11988 )
11989 dlg.sizer3.Add(
11990 dlg.reset_cal_ctrl, flag=wx.TOP | wx.ALIGN_LEFT, border=border
11991 )
11992 border = 4
11993 dlg.embed_cal_ctrl = wx.CheckBox(dlg, -1, lang.getstr("calibration.embed"))
11994
11995 def embed_cal_ctrl_handler(event: wx.Event) -> None:
11996 """Handle the embed calibration checkbox event."""
11997 embed_cal = dlg.embed_cal_ctrl.GetValue()
11998 dlg.reset_cal_ctrl.Enable(embed_cal)
11999 if not embed_cal:
12000 dlg.reset_cal_ctrl.SetValue(True)
12001
12002 if can_use_current_cal or cal:
12003 dlg.embed_cal_ctrl.Bind(wx.EVT_CHECKBOX, embed_cal_ctrl_handler)
12004 dlg.embed_cal_ctrl.SetValue(bool(can_use_current_cal or cal))
12005 dlg.sizer3.Add(dlg.embed_cal_ctrl, flag=wx.TOP | wx.ALIGN_LEFT, border=border)
12006 dlg.sizer0.SetSizeHints(dlg)
12007 dlg.sizer0.Layout()
12008 result = wx.ID_OK if silent else dlg.ShowModal()
12009 if can_use_current_cal or cal:
12010 reset_cal = dlg.reset_cal_ctrl.GetValue()
12011 embed_cal = dlg.embed_cal_ctrl.GetValue()
12012 dlg.Destroy()
12013 if result == wx.ID_CANCEL:
12014 self.start_timers()
12015 return wx.ID_CANCEL
12016 if not embed_cal:
12017 if can_use_current_cal and reset_cal:
12018 self.reset_cal()
12019 return False
12020 if not (can_use_current_cal or cal) or reset_cal:
12021 return get_data_path("linear.cal")
12022 if cal:
12023 if options_dispcal:
12024 self.worker.options_dispcal = options_dispcal
12025 return cal
12026 return None
12027
12028 def restore_measurement_mode(self) -> None:
12029 """Restore the measurement mode from backup."""
12030 if getcfg("measurement_mode.backup", False):
12031 setcfg("measurement_mode", getcfg("measurement_mode.backup"))
12032 setcfg("measurement_mode.backup", None)
12033 if getcfg("comport.number.backup", False):
12034 setcfg("comport.number", getcfg("comport.number.backup"))
12035 setcfg("comport.number.backup", None)
12036 self.update_comports()
12037 else:
12038 self.update_measurement_mode()
12039 if getcfg("observer.backup", False):
12040 setcfg("observer", getcfg("observer.backup"))
12041 setcfg("observer.backup", None)
12042
12043 def restore_testchart(self) -> None:
12044 """Restore the testchart file from backup."""
12045 if getcfg("testchart.file.backup", False):
12046 self.set_testchart(getcfg("testchart.file.backup"))
12047 setcfg("testchart.file.backup", None)
12048
12049 def measure_auto(
12050 self, measure_auto_after: Callable, *measure_auto_after_args: tuple
12051 ) -> None | bool:
12052 """Automatically create a CCMX with EDID reference.
12053
12054 Args:
12055 measure_auto_after (callable): Function to call after measurement.
12056 measure_auto_after_args (tuple): Arguments to pass to the function.
12057
12058 Returns:
12059 None | bool: True if the automatic measurement was started, False
12060 otherwise, None if the measurement mode is not 'auto' or
12061 measure_auto_after is already set.
12062 """
12063 if getcfg("measurement_mode") != "auto" or getattr(
12064 self, "measure_auto_after", None
12065 ):
12066 return None
12067 if not self.worker.get_display_edid():
12068 self.measure_auto_finish(Error("EDID not available"))
12069 return True
12070 self.measure_auto_after = measure_auto_after
12071 self.measure_auto_after_args = measure_auto_after_args
12072 if not is_ccxx_testchart():
12073 ccxx_testchart = get_ccxx_testchart()
12074 if not ccxx_testchart:
12075 self.measure_auto_finish(
12076 Error(lang.getstr("not_found", lang.getstr("ccxx.ti1")))
12077 )
12078 return True
12079 setcfg("testchart.file.backup", getcfg("testchart.file"))
12080 self.set_testchart(ccxx_testchart)
12081 self.setup_ccxx_measurement()
12082 self.just_measure(get_data_path("linear.cal"), self.measure_auto_finish)
12083 return True
12084
12085 def measure_auto_finish(self, result: bool | Exception) -> None:
12086 """Finish the automatic CCMX creation.
12087
12088 Args:
12089 result (bool | Exception): The result of the measurement.
12090 """
12091 ti3_path = os.path.join(
12092 self.worker.tempdir or "", getcfg("profile.name.expanded") + ".ti3"
12093 )
12094 self.restore_testchart()
12095 if isinstance(result, Exception) or not result:
12096 self.measure_auto_after = None
12097 if isinstance(result, Exception):
12098 wx.CallAfter(show_result_dialog, result, self)
12099 self.Show()
12100 self.worker.stop_progress()
12101 return
12102
12103 edid = self.worker.get_display_edid()
12104 default_file = (
12105 edid.get("monitor_name", edid.get("ascii", str(edid["product_id"])))
12106 + PROFILE_EXT
12107 )
12108 profile_path = os.path.join(self.worker.tempdir, default_file)
12109 profile = ICCProfile.from_edid(edid)
12110 try:
12111 profile.write(profile_path)
12112 except Exception as exception:
12113 self.measure_auto_finish(exception)
12114 return
12115 luminance = None
12116 if self.worker.get_instrument_name() == "ColorHug":
12117 # Get the factory calibration so we can do luminance scaling
12118 # NOTE that this currently only works for the ColorHug,
12119 # NOT the ColorHug2! (but it's probably not needed for the
12120 # ColorHug2 anyway)
12121 for line in self.worker.output:
12122 if line.lower().startswith("serial number:"):
12123 serial = line.split(":", 1)[-1].strip()
12124 calibration = f"calibration-{serial}.ti3"
12125 path = os.path.join(config.get_argyll_data_dir(), calibration)
12126 if not os.path.isfile(path):
12127 print("Retrieving factory calibration for ColorHug", serial)
12128 url = (
12129 "https://raw.githubusercontent.com/hughski"
12130 f"/colorhug-calibration/master/data/{calibration}"
12131 )
12132 try:
12133 response = urllib.request.urlopen(url) # noqa: S310
12134 except Exception as exception:
12135 self.measure_auto_finish(exception)
12136 return
12137 body = response.read()
12138 response.close()
12139 if body.decode().strip().startswith("CTI3"):
12140 print("Successfully retrieved", url)
12141 try:
12142 with open(path, "wb") as calibrationfile:
12143 calibrationfile.write(body)
12144 except Exception as exception:
12145 print(exception)
12146 else:
12147 print(f"Got unexpected answer from {url}:")
12148 print(body)
12149 if os.path.isfile(path):
12150 print("Using factory calibration", path)
12151 try:
12152 cgats = CGATS(path)
12153 except (OSError, CGATSError) as exception:
12154 print(exception)
12155 else:
12156 white = cgats.queryi1({"RGB_R": 1, "RGB_G": 1, "RGB_B": 1})
12157 if white:
12158 luminance = white["XYZ_Y"]
12159 print(
12160 f"Using luminance {luminance:.2f} "
12161 "from factory calibration"
12162 )
12163 if self.create_colorimeter_correction_handler(
12164 None, [profile_path, ti3_path], luminance=luminance
12165 ):
12166 self.measure_auto_after(*self.measure_auto_after_args)
12167 else:
12168 self.Show()
12169 self.worker.stop_progress()
12170 self.measure_auto_after = None
12171
12172 def measure_handler(self, event: None | wx.Event = None) -> None:
12173 """Setup characterization measurements.
12174
12175 Args:
12176 event (wx.Event, optional): The event that triggered this handler.
12177 """
12178 self.setup_ccxx_measurement()
12179 if check_set_argyll_bin() and self.check_overwrite(".ti3"):
12180 if is_ccxx_testchart():
12181 # Use linear calibration for measuring CCXX testchart
12182 apply_calibration = get_data_path("linear.cal")
12183 else:
12184 apply_calibration = self.current_cal_choice()
12185 if apply_calibration != wx.ID_CANCEL:
12186 self.setup_measurement(self.just_measure, apply_calibration)
12187 else:
12188 self.restore_measurement_mode()
12189 self.restore_testchart()
12190
12191 def specplot_handler(self, event: wx.Event) -> None:
12192 """Run Argyll specplot for a selected file."""
12193 if not check_set_argyll_bin():
12194 return
12195 path = None
12196 default_dir, default_file = get_verified_path("last_specplot_path")
12197 dlg = wx.FileDialog(
12198 self,
12199 lang.getstr("specplot.choose"),
12200 defaultDir=default_dir,
12201 defaultFile=default_file,
12202 wildcard=lang.getstr("filetype.any") + "|*.*",
12203 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
12204 )
12205 dlg.Center(wx.BOTH)
12206 result = dlg.ShowModal()
12207 if result == wx.ID_OK:
12208 path = dlg.GetPath()
12209 dlg.Destroy()
12210 if not path:
12211 return
12212 setcfg("last_specplot_path", path)
12213 cmd = get_argyll_util("specplot")
12214 if not cmd:
12215 show_result_dialog(
12216 Error(lang.getstr("argyll.util.not_found", "specplot")), self
12217 )
12218 return
12219 args = ["-v"]
12220 if getcfg("extra_args.specplot").strip():
12221 args += parse_argument_string(getcfg("extra_args.specplot"))
12222 args.append(path)
12223 self.worker.interactive = False
12224 self.worker.start(
12225 self.specplot_consumer,
12226 self.worker.exec_cmd,
12227 wargs=(cmd, args),
12228 wkwargs={"skip_scripts": True},
12229 progress_msg=lang.getstr("specplot.run"),
12230 fancy=False,
12231 )
12232
12233 def specplot_consumer(self, result: bool | Exception) -> None:
12234 """Handle completion of a specplot run."""
12235 if isinstance(result, Exception):
12236 show_result_dialog(result, self)
12237 self.worker.wrapup(False)
12238 self.Show()
12239
12240 def profile_btn_handler(self, event: wx.Event) -> None:
12241 """Setup characterization measurements.
12242
12243 Args:
12244 event (wx.Event): The event that triggered this handler.
12245 """
12246 if sys.platform == "darwin" or DEBUG:
12247 self.focus_handler(event)
12248 if self.check_show_macos_bugs_warning(cal=False) is False:
12249 return
12250 if (
12251 check_set_argyll_bin()
12252 and self.check_overwrite(".ti3")
12253 and self.check_overwrite(PROFILE_EXT)
12254 ):
12255 apply_calibration = self.current_cal_choice(
12256 silent=isinstance(event, CustomEvent)
12257 )
12258 if apply_calibration != wx.ID_CANCEL:
12259 self.setup_measurement(self.just_profile, apply_calibration)
12260
12261 def setup_ccxx_measurement(self) -> None:
12262 """Setup measurement for CCXX testchart."""
12263 if not is_ccxx_testchart():
12264 return
12265 # Allow different location to store measurements
12266 path = getcfg("profile.save_path")
12267 if not path:
12268 self.profile_save_path_btn_handler(None)
12269 path = getcfg("profile.save_path")
12270 if not path:
12271 return
12272 if not waccess(path, os.W_OK):
12273 show_result_dialog(
12274 Error(lang.getstr("error.access_denied.write", path)), self
12275 )
12276 return
12277 setcfg("measurement.save_path", path)
12278 if getcfg("observer") == "1931_2":
12279 basename = "{} & {} {}".format(
12280 self.worker.get_instrument_name(),
12281 self.worker.get_display_name(True, True),
12282 strftime("%Y-%m-%d %H-%M-%S"),
12283 )
12284 else:
12285 basename = "{} ({} {}) & {} {}".format(
12286 self.worker.get_instrument_name(),
12287 lang.getstr(f"observer.{getcfg('observer')}"),
12288 lang.getstr("observer"),
12289 self.worker.get_display_name(True, True),
12290 strftime("%Y-%m-%d %H-%M-%S"),
12291 )
12292 setcfg("measurement.name.expanded", make_filename_safe(basename))
12293
12294 def just_measure(
12295 self,
12296 apply_calibration: None | bool | str,
12297 consumer: None | Callable = None,
12298 ) -> None:
12299 """Start characterization measurements.
12300
12301 Args:
12302 apply_calibration (str | bool): Path to the calibration file to
12303 apply, or True for linear calibration.
12304 consumer (callable, optional): Function to call when the
12305 measurements are finished. If None, the default
12306 `just_measure_finish` function will be used.
12307 """
12308 if self.measure_auto(self.just_measure, apply_calibration):
12309 return
12310 print("-" * 80)
12311 print(lang.getstr("measure"))
12312 self.worker.dispread_after_dispcal = False
12313 self.worker.interactive = config.get_display_name() == "Untethered"
12314 setcfg("calibration.file.previous", None)
12315 continue_next = bool(consumer)
12316 resume = bool(getattr(self, "measure_auto_after", None))
12317 if not consumer:
12318 consumer = self.just_measure_finish
12319 self.worker.start_measurement(
12320 consumer,
12321 apply_calibration,
12322 progress_msg=lang.getstr("measuring.characterization"),
12323 continue_next=continue_next,
12324 resume=resume,
12325 )
12326
12327 def just_measure_finish(self, result: bool | Exception) -> None:
12328 """Finish characterization measurements.
12329
12330 Args:
12331 result (bool | Exception): Result of the measurements.
12332 """
12333 if not isinstance(result, Exception) and result:
12334 result = self.check_copy_ti3()
12335 self.worker.wrapup(copy=False, remove=True)
12336 if isinstance(result, Exception) or not result:
12337 if isinstance(result, Exception):
12338 wx.CallAfter(show_result_dialog, result, self)
12339 elif is_ccxx_testchart():
12340 try:
12341 cgats = CGATS(
12342 os.path.join(
12343 getcfg("measurement.save_path"),
12344 getcfg("measurement.name.expanded"),
12345 getcfg("measurement.name.expanded"),
12346 )
12347 + ".ti3"
12348 )
12349 except Exception as exception:
12350 wx.CallAfter(show_result_dialog, exception, self)
12351 else:
12352 if cgats.queryv1("INSTRUMENT_TYPE_SPECTRAL") == b"YES":
12353 setcfg("last_reference_ti3_path", cgats.filename)
12354 else:
12355 setcfg("last_colorimeter_ti3_path", cgats.filename)
12356 if getcfg("comport.number.backup", False):
12357 # Measurements were started from colorimeter correction
12358 # creation dialog
12359 paths = []
12360 if (
12361 getcfg("last_reference_ti3_path", False)
12362 and os.path.isfile(getcfg("last_reference_ti3_path"))
12363 and (
12364 getcfg("colorimeter_correction.type") == "spectral"
12365 or (
12366 getcfg("last_colorimeter_ti3_path", False)
12367 and os.path.isfile(getcfg("last_colorimeter_ti3_path"))
12368 and self.worker.get_instrument_name()
12369 == getcfg("colorimeter_correction.instrument")
12370 )
12371 )
12372 ):
12373 paths.append(getcfg("last_reference_ti3_path"))
12374 if self.worker.get_instrument_name() == getcfg(
12375 "colorimeter_correction.instrument"
12376 ):
12377 paths.append(getcfg("last_colorimeter_ti3_path"))
12378 wx.CallAfter(
12379 self.create_colorimeter_correction_handler, True, paths=paths
12380 )
12381 else:
12382 wx.CallAfter(
12383 self.just_measure_show_result,
12384 os.path.join(
12385 getcfg("profile.save_path"),
12386 getcfg("profile.name.expanded"),
12387 getcfg("profile.name.expanded") + ".ti3",
12388 ),
12389 )
12390 self.Show(start_timers=True)
12391 self.restore_measurement_mode()
12392 self.restore_testchart()
12393
12394 def just_measure_show_result(self, path: str) -> None:
12395 """Show a dialog to confirm the completion of the measurements.
12396
12397 Args:
12398 path (str): Path to the measurement file.
12399 """
12400 dlg = ConfirmDialog(
12401 self,
12402 msg=lang.getstr("measurements.complete"),
12403 ok=lang.getstr("ok"),
12404 cancel=lang.getstr("cancel"),
12405 bitmap=get_icon(32, "dialog-question"),
12406 )
12407 if dlg.ShowModal() == wx.ID_OK:
12408 launch_file(os.path.dirname(path))
12409 dlg.Destroy()
12410
12411 def just_profile(self, apply_calibration: bool | str) -> None:
12412 """Start characterization measurements.
12413
12414 Args:
12415 apply_calibration (bool | str): Path to the calibration file to
12416 apply, or True for linear calibration.
12417 """
12418 if self.measure_auto(self.just_profile, apply_calibration):
12419 return
12420 print("-" * 80)
12421 print(lang.getstr("button.profile"))
12422 self.worker.dispread_after_dispcal = False
12423 self.worker.interactive = config.get_display_name() == "Untethered"
12424 setcfg("calibration.file.previous", None)
12425 self.worker.start_measurement(
12426 self.just_profile_finish,
12427 apply_calibration,
12428 progress_msg=lang.getstr("measuring.characterization"),
12429 continue_next=config.get_display_name() != "Untethered",
12430 resume=bool(getattr(self, "measure_auto_after", None)),
12431 )
12432
12433 def just_profile_finish(self, result: bool | Exception) -> None:
12434 """Build profile from characterization measurements.
12435
12436 Args:
12437 result (bool | Exception): Result of the profile creation.
12438 """
12439 start_timers = True
12440 if not isinstance(result, Exception) and result:
12441 result = self.check_copy_ti3()
12442 if not isinstance(result, Exception) and result:
12443 start_timers = False
12444 wx.CallAfter(
12445 self.start_profile_worker,
12446 lang.getstr("profiling.complete"),
12447 resume=True,
12448 )
12449 elif isinstance(result, Exception):
12450 wx.CallAfter(show_result_dialog, result, self)
12451 elif not getcfg("dry_run"):
12452 wx.CallAfter(
12453 InfoDialog,
12454 self,
12455 msg=lang.getstr("profiling.incomplete"),
12456 ok=lang.getstr("ok"),
12457 bitmap=get_icon(32, "dialog-error"),
12458 )
12459 self.Show(start_timers=start_timers)
12460
12461 def profile_finish(
12462 self,
12463 result: bool | Exception,
12464 profile_path: None | str = None,
12465 success_msg: str = "",
12466 failure_msg: str = "",
12467 preview: bool = True,
12468 skip_scripts: bool = False,
12469 allow_show_log: bool = True,
12470 install_3dlut: bool = False,
12471 ) -> None:
12472 """Finish profile creation.
12473
12474 Show result dialog, update controls and save profile path.
12475
12476 Args:
12477 result (bool | Exception): Result of the profile creation.
12478 profile_path (None | str, optional): Path to the created profile.
12479 success_msg (str): Message to show on success.
12480 failure_msg (str): Message to show on failure.
12481 preview (bool): Whether to show a preview of the profile.
12482 skip_scripts (bool): Whether to skip running scripts.
12483 allow_show_log (bool): Whether to allow showing the log.
12484 install_3dlut (bool): Whether to install the 3D LUT.
12485 """
12486 if isinstance(result, Exception) or not result:
12487 if isinstance(result, Exception):
12488 show_result_dialog(result, self)
12489 else:
12490 InfoDialog(
12491 self,
12492 msg=failure_msg,
12493 ok=lang.getstr("ok"),
12494 bitmap=get_icon(32, "dialog-error"),
12495 )
12496
12497 if sys.platform == "darwin":
12498 # For some reason, the call to enable_menus() in Show()
12499 # sometimes isn't enough under MacOS (e.g. after calibrate &
12500 # profile)
12501 self.enable_menus()
12502 self.start_timers(True)
12503 if not getcfg("dry_run"):
12504 setcfg("calibration.file.previous", None)
12505 return
12506 if getcfg("log.autoshow") and allow_show_log:
12507 self.infoframe_toggle_handler(show=True)
12508 self.install_3dlut = install_3dlut
12509 if profile_path:
12510 profile_save_path = os.path.splitext(profile_path)[0]
12511 else:
12512 profile_save_path = os.path.join(
12513 getcfg("profile.save_path"),
12514 getcfg("profile.name.expanded"),
12515 getcfg("profile.name.expanded"),
12516 )
12517 profile_path = profile_save_path + PROFILE_EXT
12518 self.cal = profile_path
12519 profile = None
12520 filename, ext = os.path.splitext(profile_path)
12521 extra = []
12522 cinfo = []
12523 vinfo = []
12524 has_cal = False
12525 try:
12526 profile = ICCProfile(profile_path)
12527 except (OSError, ICCProfileInvalidError):
12528 InfoDialog(
12529 self,
12530 msg=lang.getstr("profile.invalid") + "\n" + profile_path,
12531 ok=lang.getstr("ok"),
12532 bitmap=get_icon(32, "dialog-error"),
12533 )
12534 self.start_timers(True)
12535 setcfg("calibration.file.previous", None)
12536 return
12537
12538 has_cal = isinstance(profile.tags.get("vcgt"), VideoCardGammaType)
12539 if profile.profileClass != b"mntr" or profile.colorSpace != b"RGB":
12540 InfoDialog(
12541 self,
12542 msg=lang.getstr("profiling.complete"),
12543 ok=lang.getstr("ok"),
12544 bitmap=get_icon(32, "dialog-information"),
12545 )
12546 self.start_timers(True)
12547 setcfg("calibration.file.previous", None)
12548 return
12549 if getcfg("calibration.file", False) != profile_path:
12550 # Load profile
12551 (options_dispcal, options_colprof) = get_options_from_profile(profile)
12552 if options_dispcal or options_colprof:
12553 cal = profile_save_path + ".cal"
12554 sel = self.calibration_file_ctrl.GetSelection()
12555 if options_dispcal and self.recent_cals[sel] == cal:
12556 self.recent_cals.remove(cal)
12557 self.calibration_file_ctrl.Delete(sel)
12558 if options_dispcal and options_colprof:
12559 setcfg("settings.changed", 0)
12560 self.load_cal_handler(
12561 None,
12562 path=profile_path,
12563 update_profile_name=False,
12564 silent=True,
12565 load_vcgt=False,
12566 )
12567 else:
12568 setcfg("calibration.file", profile_path)
12569 setcfg("3dlut.output.profile", profile_path)
12570 setcfg("measurement_report.output_profile", profile_path)
12571 self.update_controls(update_profile_name=False)
12572 # Get 3D LUT options
12573 self.lut3d_set_path()
12574 # Check if we want to automatically create 3D LUT
12575 if (
12576 install_3dlut
12577 and getcfg("3dlut.create")
12578 and not os.path.isfile(self.lut3d_path)
12579 ):
12580 # Update curve viewer if shown
12581 self.lut_viewer_load_lut(profile=profile)
12582 # Create 3D LUT
12583 self.lut3d_create_handler(None)
12584 return
12585 if hasattr(self.worker, "_disabler"):
12586 # This shouldn't happen
12587 self.worker.stop_progress()
12588 if "meta" in profile.tags:
12589 for key in ("avg", "max", "rms"):
12590 try:
12591 dE = float(profile.tags.meta.getvalue(f"ACCURACY_dE76_{key}")) # noqa: N806
12592 except (TypeError, ValueError):
12593 pass
12594 else:
12595 lstr = f"{lang.getstr('profile.self_check')}:"
12596 if lstr not in extra:
12597 extra.append(lstr)
12598 extra.append(
12599 " {} {:.2f}".format(
12600 lang.getstr(f"profile.self_check.{key}"), dE
12601 )
12602 )
12603 gamuts = (
12604 ("srgb", "sRGB", GAMUT_VOLUME_SRGB),
12605 ("adobe-rgb", "Adobe RGB", GAMUT_VOLUME_ADOBERGB),
12606 ("dci-p3", "DCI P3", GAMUT_VOLUME_SMPTE431_P3),
12607 )
12608 for key, name, _volume in gamuts:
12609 try:
12610 gamut_coverage = profile.tags.meta.getvalue(
12611 f"GAMUT_coverage({key})"
12612 )
12613 gamut_coverage = (
12614 float(gamut_coverage)
12615 if gamut_coverage is not None
12616 else gamut_coverage
12617 )
12618 except (TypeError, ValueError):
12619 traceback.print_exc()
12620 gamut_coverage = None
12621 if gamut_coverage:
12622 cinfo.append(f"{gamut_coverage:.1%} {name}")
12623 try:
12624 gamut_volume = float(profile.tags.meta.getvalue("GAMUT_volume"))
12625 except (TypeError, ValueError):
12626 traceback.print_exc()
12627 gamut_volume = None
12628 if gamut_volume:
12629 for _key, name, volume in gamuts:
12630 vinfo.append(
12631 f"{gamut_volume * GAMUT_VOLUME_SRGB / volume:.1%} {name}"
12632 )
12633 if len(vinfo) == len(cinfo):
12634 break
12635 if config.is_virtual_display() or install_3dlut:
12636 installable = False
12637 title = APPNAME
12638 if self.lut3d_path and os.path.isfile(self.lut3d_path):
12639 # 3D LUT file already exists
12640 if getcfg("3dlut.format") in (
12641 "madVR",
12642 "ReShade",
12643 ) or config.check_3dlut_format("Prisma"):
12644 ok = lang.getstr("3dlut.install")
12645 else:
12646 ok = lang.getstr("3dlut.save_as")
12647 else:
12648 ok = lang.getstr("3dlut.create")
12649 cancel = lang.getstr("cancel")
12650 else:
12651 if not self.check_profile_b2a_hires(profile):
12652 return
12653 installable = True
12654 title = lang.getstr("profile.install")
12655 ok = lang.getstr("profile.install")
12656 cancel = lang.getstr("profile.do_not_install")
12657 if not success_msg:
12658 if installable:
12659 success_msg = lang.getstr(
12660 "dialog.install_profile",
12661 (
12662 os.path.basename(profile_path),
12663 self.display_ctrl.GetStringSelection(),
12664 ),
12665 )
12666 else:
12667 success_msg = lang.getstr("profiling.complete")
12668 if extra:
12669 extra = ",".join(extra).replace(":,", ":").replace(",,", "\n")
12670 success_msg = f"{success_msg}\n\n{extra}".strip()
12671 # Always load calibration curves
12672 self.load_cal(cal=profile_path, silent=True)
12673 # Check profile metadata
12674 share_profile = None
12675 if not self.profile_share_get_meta_error(profile):
12676 share_profile = lang.getstr("profile.share")
12677 dlg = ConfirmDialog(
12678 self,
12679 msg=success_msg,
12680 title=title,
12681 ok=ok,
12682 cancel=cancel,
12683 bitmap=get_icon(32, APPNAME + "-profile-info"),
12684 alt=share_profile,
12685 )
12686 if cinfo or vinfo:
12687 gamut_info_sizer = wx.FlexGridSizer(2, 2, 0, 24)
12688 dlg.sizer3.Add(gamut_info_sizer, flag=wx.TOP, border=14)
12689 if cinfo:
12690 label = wx.StaticText(dlg, -1, lang.getstr("gamut.coverage"))
12691 font = label.GetFont()
12692 font.SetWeight(wx.FONTWEIGHT_BOLD)
12693 label.SetFont(font)
12694 gamut_info_sizer.Add(label)
12695 if vinfo:
12696 label = wx.StaticText(dlg, -1, lang.getstr("gamut.volume"))
12697 font = label.GetFont()
12698 font.SetWeight(wx.FONTWEIGHT_BOLD)
12699 label.SetFont(font)
12700 else:
12701 label = (1, 1)
12702 gamut_info_sizer.Add(label)
12703 if cinfo:
12704 gamut_info_sizer.Add(wx.StaticText(dlg, -1, "\n".join(cinfo)))
12705 if vinfo:
12706 gamut_info_sizer.Add(wx.StaticText(dlg, -1, "\n".join(vinfo)))
12707 self.modaldlg = dlg
12708 if share_profile:
12709 # Show share profile button
12710 dlg.Unbind(wx.EVT_BUTTON, dlg.alt)
12711 dlg.Bind(wx.EVT_BUTTON, self.profile_share_handler, id=dlg.alt.GetId())
12712 if preview and has_cal and self.worker.calibration_loading_supported:
12713 # Show calibration preview checkbox
12714 self.preview = wx.CheckBox(dlg, -1, lang.getstr("calibration.preview"))
12715 self.preview.SetValue(True)
12716 dlg.Bind(wx.EVT_CHECKBOX, self.preview_handler, id=self.preview.GetId())
12717 dlg.sizer3.Add(self.preview, flag=wx.TOP | wx.ALIGN_LEFT, border=14)
12718 if LUTFrame and not ProfileInfoFrame:
12719 # Disabled, use profile information window instead
12720 self.show_lut = wx.CheckBox(
12721 dlg, -1, lang.getstr("calibration.show_lut")
12722 )
12723 dlg.Bind(
12724 wx.EVT_CHECKBOX, self.show_lut_handler, id=self.show_lut.GetId()
12725 )
12726 dlg.sizer3.Add(self.show_lut, flag=wx.TOP | wx.ALIGN_LEFT, border=4)
12727 self.show_lut.SetValue(bool(getcfg("lut_viewer.show")))
12728 if not getattr(self, "lut_viewer", None):
12729 self.init_lut_viewer(
12730 profile=profile, show=getcfg("lut_viewer.show")
12731 )
12732 else:
12733 dlg.sizer3.Add((0, 10))
12734 self.show_profile_info = wx.CheckBox(dlg, -1, lang.getstr("profile.info.show"))
12735 dlg.Bind(
12736 wx.EVT_CHECKBOX,
12737 self.profile_info_handler,
12738 id=self.show_profile_info.GetId(),
12739 )
12740 dlg.sizer3.Add(self.show_profile_info, flag=wx.TOP | wx.ALIGN_LEFT, border=4)
12741 id_ = profile.calculate_id(False) if profile.ID == "\0" * 16 else profile.ID
12742 if id_ in self.profile_info:
12743 self.show_profile_info.SetValue(self.profile_info[id_].IsShownOnScreen())
12744 if installable:
12745 if sys.platform == "win32":
12746 # Get profile loader config
12747 cur = self.send_command(
12748 "apply-profiles", "getcfg profile.load_on_login"
12749 )
12750 if cur:
12751 try:
12752 cur = int(cur.split()[-1])
12753 except Exception:
12754 pass
12755 else:
12756 setcfg("profile.load_on_login", cur)
12757 else:
12758 # Profile loader not running? Fall back to config files
12759
12760 # 1. Remember current config
12761 items = config.CFG.items(config.configparser.DEFAULTSECT)
12762
12763 # 2. Read in profile loader config. Result is unison of
12764 # current config and profile loader config.
12765 initcfg("apply-profiles", force_load=True)
12766
12767 # 3. Restore current config (but do not override profile
12768 # loader options)
12769 for name, value in items:
12770 if name != "profile.load_on_login" and not name.startswith(
12771 "profile_loader"
12772 ):
12773 config.CFG.set(config.configparser.DEFAULTSECT, name, value)
12774
12775 # 4. Remove profile loader options from current config
12776 for name in DEFAULTS:
12777 if name.startswith("profile_loader"):
12778 setcfg(name, None)
12779 if sys.platform != "darwin" or TEST:
12780 os_cal = (
12781 sys.platform == "win32"
12782 and sys.getwindowsversion() >= (6, 1)
12783 and util_win.calibration_management_isenabled()
12784 )
12785 label = get_profile_load_on_login_label(os_cal)
12786 self.profile_load_on_login = wx.CheckBox(dlg, -1, label)
12787 self.profile_load_on_login.SetValue(
12788 bool(getcfg("profile.load_on_login") or os_cal)
12789 )
12790 dlg.Bind(
12791 wx.EVT_CHECKBOX,
12792 self.profile_load_on_login_handler,
12793 id=self.profile_load_on_login.GetId(),
12794 )
12795 dlg.sizer3.Add(
12796 self.profile_load_on_login,
12797 flag=wx.TOP | wx.ALIGN_LEFT,
12798 border=14,
12799 )
12800 dlg.sizer3.Add((1, 4))
12801 if sys.platform == "win32" and sys.getwindowsversion() >= (6, 1):
12802 self.profile_load_by_os = wx.CheckBox(
12803 dlg, -1, lang.getstr("profile.load_on_login.handled_by_os")
12804 )
12805 self.profile_load_by_os.SetValue(bool(os_cal))
12806 dlg.Bind(
12807 wx.EVT_CHECKBOX,
12808 self.profile_load_by_os_handler,
12809 id=self.profile_load_by_os.GetId(),
12810 )
12811 dlg.sizer3.Add(
12812 self.profile_load_by_os,
12813 flag=wx.LEFT | wx.ALIGN_LEFT,
12814 border=16,
12815 )
12816 dlg.sizer3.Add((1, 4))
12817 self.profile_load_on_login_handler()
12818 if (
12819 (
12820 (
12821 sys.platform == "darwin"
12822 or (
12823 sys.platform != "win32"
12824 and self.worker.argyll_version >= [1, 1, 0]
12825 )
12826 )
12827 and (os.geteuid() == 0 or which("sudo"))
12828 )
12829 or (
12830 sys.platform == "win32"
12831 and sys.getwindowsversion() >= (6,)
12832 and self.worker.argyll_version > [1, 1, 1]
12833 )
12834 or TEST
12835 ):
12836 # Linux, OSX or Vista and later
12837 # NOTE: System install scope is currently not implemented
12838 # correctly in dispwin 1.1.0, but a patch is trivial and
12839 # should be in the next version
12840 # 2010-06-18: Do not offer system install in DisplayCAL when
12841 # installing via GCM or oyranos FIXME: oyranos-monitor can't
12842 # be run via sudo
12843 self.install_profile_user = wx.RadioButton(
12844 dlg, -1, lang.getstr("profile.install_user"), style=wx.RB_GROUP
12845 )
12846 self.install_profile_user.SetValue(
12847 getcfg("profile.install_scope") == "u"
12848 )
12849 dlg.Bind(
12850 wx.EVT_RADIOBUTTON,
12851 self.install_profile_scope_handler,
12852 id=self.install_profile_user.GetId(),
12853 )
12854 dlg.sizer3.Add(
12855 self.install_profile_user,
12856 flag=wx.TOP | wx.ALIGN_LEFT,
12857 border=10,
12858 )
12859 self.install_profile_systemwide = wx.RadioButton(
12860 dlg, -1, lang.getstr("profile.install_local_system")
12861 )
12862 self.install_profile_systemwide.SetValue(
12863 getcfg("profile.install_scope") == "l"
12864 )
12865 dlg.Bind(
12866 wx.EVT_RADIOBUTTON,
12867 self.install_profile_scope_handler,
12868 id=self.install_profile_systemwide.GetId(),
12869 )
12870 dlg.sizer3.Add(
12871 self.install_profile_systemwide,
12872 flag=wx.TOP | wx.ALIGN_LEFT,
12873 border=4,
12874 )
12875 if sys.platform == "darwin" and os.path.isdir(
12876 "/Network/Library/ColorSync/Profiles"
12877 ):
12878 self.install_profile_network = wx.RadioButton(
12879 dlg, -1, lang.getstr("profile.install_network")
12880 )
12881 self.install_profile_network.SetValue(
12882 getcfg("profile.install_scope") == "n"
12883 )
12884 dlg.Bind(
12885 wx.EVT_RADIOBUTTON,
12886 self.install_profile_scope_handler,
12887 id=self.install_profile_network.GetId(),
12888 )
12889 dlg.sizer3.Add(
12890 self.install_profile_network,
12891 flag=wx.TOP | wx.ALIGN_LEFT,
12892 border=4,
12893 )
12894 self.install_profile_scope_handler(None)
12895 else:
12896 setcfg("profile.install_scope", "u")
12897 dlg.sizer0.SetSizeHints(dlg)
12898 dlg.sizer0.Layout()
12899 dlg.ok.SetDefault()
12900 dlg.profile = profile
12901 dlg.profile_path = profile_path
12902 dlg.skip_scripts = skip_scripts
12903 dlg.preview = preview
12904 dlg.ok.Unbind(wx.EVT_BUTTON)
12905 dlg.ok.Bind(wx.EVT_BUTTON, lambda event: self.profile_finish_action(event.Id))
12906 result = dlg.ShowWindowModalBlocking()
12907 if result == wx.ID_CANCEL:
12908 self.profile_finish_action(result)
12909
12910 def profile_finish_action(self, result: int) -> None:
12911 """Handle the action after finishing profile installation.
12912
12913 Args:
12914 result (int): The result of the dialog action, typically wx.ID_OK
12915 or wx.ID_CANCEL.
12916 """
12917 lut3d = config.is_virtual_display() or self.install_3dlut
12918 if (
12919 result == wx.ID_OK
12920 and getcfg("3dlut.format") == "madVR"
12921 and not hasattr(self.worker, "madtpg")
12922 ):
12923 # madVR has an API for installing 3D LUTs
12924 # Prisma has a HTTP REST interface for uploading and
12925 # configuring 3D LUTs
12926 try:
12927 self.worker.madtpg_init()
12928 except Exception as exception:
12929 print("Could not initialize madTPG:", exception)
12930 madtpg = getattr(self.worker, "madtpg", None)
12931 # Note: madVR HDR 3D LUT install API was added September 2017,
12932 # we don't require it so check availability
12933 install_3dlut_api = (
12934 getcfg("3dlut.format") == "madVR"
12935 and (
12936 not getcfg("3dlut.trc").startswith("smpte2084")
12937 or hasattr(madtpg, "load_hdr_3dlut_file")
12938 )
12939 ) or config.check_3dlut_format("Prisma")
12940 if result != wx.ID_OK or lut3d:
12941 if self.modaldlg.preview:
12942 if getcfg("calibration.file", False):
12943 # Load LUT curves from last used .cal file
12944 self.load_cal(silent=True)
12945 if not getcfg("calibration.autoload"):
12946 # Reload display profile into videoLUT
12947 self.load_display_profile_cal(True, False)
12948 else:
12949 # Load LUT curves from current display profile (if any,
12950 # and if it contains curves)
12951 self.load_display_profile_cal(True)
12952 if getattr(self, "preview", None):
12953 self.preview.SetValue(False)
12954 if (
12955 result != wx.ID_OK
12956 or not self.lut3d_path
12957 or not os.path.isfile(self.lut3d_path)
12958 or not install_3dlut_api
12959 ):
12960 self.profile_finish_consumer()
12961 if result == wx.ID_OK:
12962 producer = None
12963 if lut3d:
12964 if self.lut3d_path and os.path.isfile(self.lut3d_path):
12965 # 3D LUT file already exists
12966 if install_3dlut_api:
12967 filename = self.setup_patterngenerator(
12968 self, lang.getstr("3dlut.install"), True
12969 )
12970 if not filename:
12971 if filename is None:
12972 # User cancelled
12973 self.profile_finish_consumer()
12974 return
12975 producer = self.worker.install_3dlut
12976 wargs = (self.lut3d_path, filename)
12977 wkwargs = None
12978 progress_msg = lang.getstr("3dlut.install")
12979 else:
12980 # Copy to user-selectable location
12981 wx.CallAfter(
12982 self.lut3d_create_handler,
12983 None,
12984 copy_from_path=self.lut3d_path,
12985 )
12986 else:
12987 # Need to create 3D LUT
12988 wx.CallAfter(self.lut3d_create_handler, None)
12989 else:
12990 if getcfg("profile.install_scope") in ("l", "n"):
12991 result = self.worker.authenticate(
12992 "dispwin", lang.getstr("profile.install"), self
12993 )
12994 if result not in (True, None):
12995 if isinstance(result, Exception):
12996 show_result_dialog(result, parent=self)
12997 return
12998 producer = self.worker.install_profile
12999 wargs = ()
13000 wkwargs = {
13001 "profile_path": self.modaldlg.profile_path,
13002 "skip_scripts": self.modaldlg.skip_scripts,
13003 }
13004 progress_msg = lang.getstr("profile.install")
13005 if producer:
13006 print("-" * 80)
13007 print(progress_msg)
13008 self.worker.interactive = False
13009 self.worker.start(
13010 self.profile_finish_consumer,
13011 producer,
13012 wargs=wargs,
13013 wkwargs=wkwargs,
13014 parent=self,
13015 progress_msg=progress_msg,
13016 stop_timers=False,
13017 fancy=False,
13018 )
13019
13020 def profile_finish_consumer(
13021 self,
13022 result: None | tuple[str, str, str, str] | Exception = None,
13023 ) -> None:
13024 """Handle the result of the profile installation process.
13025
13026 Args:
13027 result (None | tuple | Exception, optional): The result of the
13028 profile installation process. If an exception occurred, it will
13029 be passed as an instance of Exception. If the installation was
13030 successful, it will be a tuple containing the results of the
13031 profile installation methods (ArgyllCMS, colord, Oyranos, and
13032 profile loader). Defaults to None.
13033 """
13034 if isinstance(result, Exception):
13035 show_result_dialog(result, parent=self)
13036 if not getcfg("dry_run") and not isinstance(result, (Info, Warning)):
13037 return
13038 elif result:
13039 # Check all profile install methods
13040 argyll_install, colord_install, oy_install, loader_install = result
13041 all_good = (
13042 argyll_install in (None, True)
13043 and colord_install in (None, True)
13044 and oy_install in (None, True)
13045 and loader_install in (None, True)
13046 )
13047 some_good = (
13048 argyll_install is True
13049 or colord_install is True
13050 or oy_install is True
13051 or loader_install is True
13052 )
13053 linux = sys.platform not in ("darwin", "win32")
13054 if all_good:
13055 msg = lang.getstr("profile.install.success")
13056 icon = "dialog-information"
13057 elif some_good and linux:
13058 msg = lang.getstr("profile.install.warning")
13059 icon = "dialog-warning"
13060 else:
13061 msg = lang.getstr("profile.install.error")
13062 icon = "dialog-error"
13063 dlg = InfoDialog(
13064 self,
13065 msg=msg,
13066 ok=lang.getstr("ok"),
13067 bitmap=get_icon(32, icon),
13068 show=False,
13069 )
13070 if not all_good and linux:
13071 sizer = wx.FlexGridSizer(0, 2, 8, 8)
13072 dlg.sizer3.Add(sizer, 1, flag=wx.TOP, border=12)
13073 for name, result_ in (
13074 ("ArgyllCMS", argyll_install),
13075 ("colord", colord_install),
13076 ("Oyranos", oy_install),
13077 (lang.getstr("profile_loader"), loader_install),
13078 ):
13079 if result_ is not None:
13080 if result_ is True:
13081 icon = "checkmark"
13082 result_ = lang.getstr("ok")
13083 elif isinstance(result_, Warning):
13084 icon = "dialog-warning"
13085 else:
13086 icon = "x"
13087 if not result_:
13088 result_ = lang.getstr("failure")
13089 result_ = wrap(str(result_))
13090 sizer.Add(
13091 wx.StaticBitmap(dlg, -1, get_icon(16, icon)),
13092 flag=wx.TOP,
13093 border=2,
13094 )
13095 sizer.Add(wx.StaticText(dlg, -1, f"{name}: {result_}"))
13096 dlg.sizer0.SetSizeHints(dlg)
13097 dlg.sizer0.Layout()
13098 dlg.ok.SetDefault()
13099 dlg.ShowModalThenDestroy()
13100 if self.modaldlg.IsShown():
13101 self.modaldlg.EndModal(wx.ID_CLOSE)
13102 self.modaldlg.Destroy()
13103 # The C part of modaldlg will not be gone instantly, so we must
13104 # dereference it before we can delete the python attribute
13105 self.modaldlg = None
13106 del self.modaldlg
13107 if sys.platform == "darwin":
13108 # For some reason, the call to enable_menus() in Show()
13109 # sometimes isn't enough under Mac OS X (e.g. after calibrate &
13110 # profile)
13111 self.enable_menus()
13112 self.start_timers(True)
13113 setcfg("calibration.file.previous", None)
13114
13115 def profile_info_close_handler(self, event: wx.Event) -> None:
13116 """Handle the close event for the profile information window.
13117
13118 Args:
13119 event (wx.Event): The close event triggered by the window.
13120 """
13121 if getattr(self, "show_profile_info", None):
13122 # If the profile install dialog is shown, just hide info window
13123 self.profile_info[event.GetEventObject().profileID].Hide()
13124 self.show_profile_info.SetValue(False)
13125 else:
13126 # Remove the frame from the hash table
13127 self.profile_info.pop(event.GetEventObject().profileID)
13128 # Closes the window
13129 event.Skip()
13130
13131 def profile_info_handler(
13132 self, event: None | wx.Event = None, profile: None | ICCProfile = None
13133 ) -> None:
13134 """Show profile information window.
13135
13136 Args:
13137 event (wx.Event, optional): The event that triggered this handler.
13138 profile (ICCProfile, optional): The profile to show information
13139 for. Defaults to None, in which case the user is prompted to
13140 select a profile.
13141 """
13142 if not ProfileInfoFrame:
13143 wx.Bell()
13144 return
13145
13146 if profile:
13147 pass
13148 elif event and event.GetEventObject() is getattr(
13149 self, "show_profile_info", False
13150 ):
13151 # Use the profile that was requested to be installed
13152 profile = self.modaldlg.profile
13153 else:
13154 profile = self.select_profile(
13155 title=lang.getstr("profile.info"),
13156 check_profile_class=False,
13157 prefer_current_profile=True,
13158 ignore_current_profile=event
13159 and event.GetEventObject() is not self.profile_info_btn,
13160 )
13161 if not profile:
13162 return
13163 id_ = profile.calculate_id(False) if profile.ID == "\0" * 16 else profile.ID
13164 show = (
13165 not getattr(self, "show_profile_info", None)
13166 or self.show_profile_info.GetValue()
13167 )
13168 if show:
13169 if id_ not in self.profile_info:
13170 # Create profile info window and store in hash table
13171 self.profile_info[id_] = ProfileInfoFrame(None, -1)
13172 self.profile_info[id_].Unbind(wx.EVT_CLOSE)
13173 self.profile_info[id_].Bind(
13174 wx.EVT_CLOSE, self.profile_info_close_handler
13175 )
13176 if (
13177 not self.profile_info[id_].profile
13178 or self.profile_info[id_].profile.calculate_id(False) != id_
13179 ):
13180 # Load profile if info window has no profile or ID is different
13181 self.profile_info[id_].profileID = id_
13182 self.profile_info[id_].LoadProfile(profile)
13183 if self.profile_info.get(id_):
13184 if self.profile_info[id_].IsIconized() and show:
13185 self.profile_info[id_].Restore()
13186 else:
13187 self.profile_info[id_].Show(show)
13188 if show:
13189 self.profile_info[id_].Raise()
13190
13191 def get_commands(self) -> list[str]:
13192 """Get a list of commands that this application can process.
13193
13194 Returns:
13195 list[str]: List of command strings that this application can
13196 process.
13197 """
13198 return [
13199 *self.get_common_commands(),
13200 "3DLUT-maker [create filename]",
13201 "calibrate",
13202 "calibrate-profile",
13203 "create-colorimeter-correction",
13204 "create-profile [filename]",
13205 "curve-viewer [filename]",
13206 f"{APPNAME} [filename]",
13207 "enable-spyder2",
13208 "import-colorimeter-corrections [filename...]",
13209 "install-profile [filename]",
13210 "load <filename>",
13211 "measure",
13212 "measure-uniformity",
13213 "measurement-report [filename]",
13214 "profile",
13215 "profile-info [filename]",
13216 "report-calibrated",
13217 "report-uncalibrated",
13218 "set-argyll-dir [dirname]",
13219 "synthprofile [filename]",
13220 "testchart-editor [filename | create filename]",
13221 "verify-calibration",
13222 ]
13223
13224 def process_data(self, data: list[str]) -> str:
13225 """Process data.
13226
13227 Args:
13228 data (list[str]): List of strings containing the command and its
13229 arguments.
13230
13231 Returns:
13232 str: Response indicating the result of the processing.
13233 """
13234 if not self.IsShownOnScreen() and data[0] != "measure":
13235 # If we were hidden, perform necessary cleanup in case the
13236 # measurement window is shown and we're not starting measurements
13237 if isinstance(getattr(self, "_measureframe_subprocess", None), sp.Popen):
13238 self._measureframe_subprocess.terminate()
13239 elif self.measureframe.IsShown():
13240 self.measureframe.close_handler(None)
13241 else:
13242 return "busy"
13243 response = "ok"
13244 if data[0] == "3DLUT-maker" and (
13245 len(data) == 1 or (len(data) == 3 and data[1] == "create")
13246 ):
13247 # 3D LUT maker
13248 if len(data) == 3:
13249 self.lut3d_create_handler(None, data[-1])
13250 else:
13251 self.tab_select_handler(self.lut3d_settings_btn, True)
13252 elif data[0] == "curve-viewer" and len(data) < 3:
13253 # Curve viewer
13254 profile = None
13255 if len(data) == 2:
13256 path = data[1]
13257 if not os.path.isfile(path) and not os.path.isabs(path):
13258 path = get_data_path(path)
13259 if not path:
13260 return "fail"
13261 try:
13262 profile = ICCProfile(path)
13263 except (OSError, ICCProfileInvalidError):
13264 return "fail"
13265 wx.CallAfter(self.init_lut_viewer, profile=profile, show=True)
13266 elif data[0] == "profile-info" and len(data) < 3:
13267 # Profile info
13268 profile = None
13269 if len(data) == 2:
13270 path = data[1]
13271 if not os.path.isfile(path) and not os.path.isabs(path):
13272 path = get_data_path(path)
13273 if not path:
13274 return "fail"
13275 try:
13276 profile = ICCProfile(path)
13277 except (OSError, ICCProfileInvalidError):
13278 return "fail"
13279 wx.CallAfter(self.profile_info_handler, profile=profile)
13280 elif data[0] == "synthprofile" and len(data) < 3:
13281 # Synthetic profile creator
13282 self.synthicc_create_handler(None)
13283 if len(data) == 2:
13284 response = self.synthiccframe.process_data(data)
13285 elif data[0] == "testchart-editor" and (
13286 len(data) < 3 or (len(data) == 3 and data[1] == "create")
13287 ):
13288 # Testchart editor
13289 if len(data) == 2:
13290 path = data[1]
13291 if not os.path.isfile(path) and not os.path.isabs(path):
13292 path = get_data_path(path)
13293 if not path:
13294 return "fail"
13295 else:
13296 path = None
13297 if not hasattr(self, "tcframe"):
13298 self.init_tcframe(path=path)
13299 setcfg("tc.show", 1)
13300 self.tcframe.Show()
13301 else:
13302 if self.tcframe.IsIconized():
13303 self.tcframe.Restore()
13304 else:
13305 self.tcframe.Show()
13306 if path:
13307 self.tcframe.tc_load_cfg_from_ti1(path=path)
13308 self.tcframe.Raise()
13309 if len(data) == 3:
13310 # Create testchart
13311 response = self.tcframe.process_data(data)
13312 elif (data[0] == APPNAME and len(data) < 3) or (
13313 data[0] == "load" and len(data) == 2
13314 ):
13315 # Main window
13316 if self.IsIconized():
13317 self.Restore()
13318 self.Raise()
13319 if len(data) == 2:
13320 path = data[1]
13321 if not os.path.isfile(path) and not os.path.isabs(path):
13322 path = get_data_path(path)
13323 if not path:
13324 return "fail"
13325 self.droptarget.OnDropFiles(0, 0, [path])
13326 elif data[0] == "calibrate" and len(data) == 1:
13327 # Calibrate
13328 wx.CallAfter(
13329 self.calibrate_btn_handler,
13330 CustomEvent(wx.EVT_BUTTON.evtType[0], self.calibrate_btn),
13331 )
13332 elif data[0] == "calibrate-profile" and len(data) == 1:
13333 # Calibrate & profile
13334 wx.CallAfter(
13335 self.calibrate_and_profile_btn_handler,
13336 CustomEvent(wx.EVT_BUTTON.evtType[0], self.calibrate_and_profile_btn),
13337 )
13338 elif data[0] == "create-profile" and len(data) < 3:
13339 profile_path = data[1] if len(data) == 2 else None
13340 wx.CallAfter(self.create_profile_handler, None, path=profile_path)
13341 elif data[0] == "import-colorimeter-corrections":
13342 wx.CallAfter(
13343 self.import_colorimeter_corrections_handler, None, paths=data[1:]
13344 )
13345 elif data[0] == "install-profile" and len(data) < 3:
13346 if len(data) == 2:
13347 wx.CallAfter(
13348 self.install_profile_handler,
13349 profile_path=data[1],
13350 install_3dlut=False,
13351 )
13352 else:
13353 wx.CallAfter(self.select_install_profile_handler, None)
13354 elif data[0] == "measure" and len(data) == 1:
13355 # Start measurement
13356 if getattr(self, "pending_function", None):
13357 if isinstance(
13358 getattr(self, "_measureframe_subprocess", None), sp.Popen
13359 ):
13360 p = self._measureframe_subprocess
13361 self._measureframe_subprocess = Dummy()
13362 self._measureframe_subprocess.returncode = 255
13363 p.terminate()
13364 else:
13365 self.worker.wrapup(False)
13366 self.HideAll()
13367 self.call_pending_function()
13368 else:
13369 response = "fail"
13370 elif data[0] == "measurement-report" and len(data) < 3:
13371 # Measurement report
13372 if len(data) == 2:
13373 wx.CallAfter(
13374 self.measurement_report_handler,
13375 CustomEvent(wx.EVT_BUTTON.evtType[0], self.measurement_report_btn),
13376 path=data[1],
13377 )
13378 else:
13379 self.tab_select_handler(self.mr_settings_btn, True)
13380 elif data[0] == "profile" and len(data) == 1:
13381 # Profile
13382 wx.CallAfter(
13383 self.profile_btn_handler,
13384 CustomEvent(wx.EVT_BUTTON.evtType[0], self.profile_btn),
13385 )
13386 elif data[0] == "refresh" and len(data) == 1:
13387 # Refresh main window
13388 self.update_displays()
13389 self.update_controls()
13390 self.update_menus()
13391 if hasattr(self, "tcframe"):
13392 self.tcframe.tc_update_controls()
13393 elif data[0] == "restore-defaults":
13394 # Restore defaults
13395 wx.CallAfter(self.restore_defaults_handler, include=data[1:])
13396 elif data[0] == "setlanguage" and len(data) == 2:
13397 setcfg("lang", data[1])
13398 menuitem = self.menubar.FindItemById(lang.LDICT[lang.getcode()].menuitem_id)
13399 event = CustomEvent(wx.EVT_MENU.typeId, menuitem)
13400 wx.CallAfter(self.set_language_handler, event)
13401 elif (
13402 data[0]
13403 in (
13404 "create-colorimeter-correction",
13405 "enable-spyder2",
13406 "measure-uniformity",
13407 "report-calibrated",
13408 "report-uncalibrated",
13409 "verify-calibration",
13410 )
13411 ) and len(data) == 1:
13412 wx.CallAfter(getattr(self, data[0].replace("-", "_") + "_handler"), True)
13413 elif data[0] == "set-argyll-dir" and len(data) <= 2:
13414 if getattr(self.worker, "thread", None) and self.worker.thread.is_alive():
13415 return "blocked"
13416 if len(data) == 2:
13417 setcfg("argyll.dir", data[1])
13418 # Always write cfg directly after setting Argyll directory so
13419 # subprocesses that read the configuration will use the right
13420 # executables
13421 writecfg()
13422 wx.CallAfter(self.check_update_controls, True)
13423 else:
13424 wx.CallAfter(self.set_argyll_bin_handler, True)
13425 else:
13426 response = "invalid"
13427 return response
13428
13429 def observer_ctrl_handler(self, event: wx.Event) -> None:
13430 """Handle changes to the observer control.
13431
13432 Args:
13433 event (wx.Event): The event that triggered this handler.
13434 """
13435 observer = self.observers_ba.get(self.observer_ctrl.GetStringSelection())
13436 setcfg("observer", observer)
13437
13438 def output_levels_handler(self, event: wx.Event) -> None:
13439 """Handle changes to output levels settings.
13440
13441 Args:
13442 event (wx.Event): The event that triggered this handler.
13443 """
13444 auto = self.output_levels_auto.GetValue()
13445 setcfg("patterngenerator.detect_video_levels", int(auto))
13446 use_video_levels = self.output_levels_limited_range.GetValue()
13447 setcfg("patterngenerator.use_video_levels", int(use_video_levels))
13448 self.update_use_video_lut()
13449
13450 def init_lut_viewer(
13451 self,
13452 event: None | wx.Event = None,
13453 profile: None | ICCProfile = None,
13454 show: None | bool = None,
13455 ) -> None:
13456 """Initialize the LUT viewer.
13457
13458 Args:
13459 event (wx.Event, optional): The event that triggered this handler.
13460 profile (ICCProfile, optional): The profile to load in the LUT
13461 viewer. If None, the current calibration profile will be used.
13462 show (bool, optional): Whether to show or hide the LUT viewer. If
13463 None, it will be determined based on the current state of the
13464 viewer and the configuration setting.
13465 """
13466 debug_print(
13467 "[D] init_lut_viewer",
13468 profile.getDescription() if profile else None,
13469 "show:",
13470 show,
13471 )
13472 if not LUTFrame:
13473 return
13474 lut_viewer = getattr(self, "lut_viewer", None)
13475 if not lut_viewer:
13476 self.lut_viewer = LUTFrame(None, -1)
13477 self.lut_viewer.client.worker = self.worker
13478 self.lut_viewer.update_controls()
13479 self.lut_viewer.Bind(
13480 wx.EVT_CLOSE, self.lut_viewer_close_handler, self.lut_viewer
13481 )
13482 if not profile and not hasattr(self, "current_cal"):
13483 path = getcfg("calibration.file", False)
13484 if path:
13485 name, ext = os.path.splitext(path)
13486 if ext.lower() in (".icc", ".icm"):
13487 try:
13488 profile = ICCProfile(path)
13489 except (OSError, ICCProfileInvalidError):
13490 msg = lang.getstr("profile.invalid") + "\n" + path
13491 if event or not lut_viewer:
13492 show_result_dialog(Error(msg), self)
13493 else:
13494 print(msg)
13495 profile = None
13496 else:
13497 profile = cal_to_fake_profile(path)
13498 else:
13499 profile = get_display_profile() or False
13500 if show is None:
13501 show = not self.lut_viewer.IsShownOnScreen()
13502 debug_print(
13503 "[D] init_lut_viewer (2)",
13504 profile.getDescription() if profile else None,
13505 "show:",
13506 show,
13507 )
13508 self.show_lut_handler(profile=profile, show=show)
13509
13510 def lut_viewer_load_lut(
13511 self,
13512 event: None | wx.Event = None,
13513 profile: None | ICCProfile = None,
13514 force_draw: bool = False,
13515 ) -> None:
13516 """Load a LUT into the LUT viewer.
13517
13518 Args:
13519 event (None | wx.Event, optional): The event that triggered this
13520 handler.
13521 profile (None | ICCProfile, optional): The profile to load in the
13522 LUT viewer. If None, the current calibration profile will be
13523 used.
13524 force_draw (bool, optional): If True, the LUT viewer will be forced
13525 to redraw even if it is already shown. Defaults to False.
13526 """
13527 debug_print(
13528 "[D] lut_viewer_load_lut",
13529 profile.getDescription() if profile else None,
13530 "force_draw:",
13531 force_draw,
13532 )
13533 if LUTFrame:
13534 self.current_cal = profile
13535 if getattr(self, "lut_viewer", None) and (
13536 self.lut_viewer.IsShownOnScreen() or force_draw
13537 ):
13538 self.lut_viewer.load_lut(profile)
13539
13540 def show_lut_handler(
13541 self,
13542 event: wx.Event = None,
13543 profile: None | ICCProfile = None,
13544 show: None | bool = None,
13545 ) -> None:
13546 """Show or hide the LUT viewer.
13547
13548 Args:
13549 event (None | wx.Event, optional): The event that triggered this
13550 handler.
13551 profile (None | ICCProfile, optional): The profile to load in the
13552 LUT viewer.
13553 show (None | bool, optional): Whether to show or hide the LUT
13554 viewer. If None, it will be determined based on the current
13555 state of the viewer and the configuration setting.
13556 """
13557 debug_print(
13558 "[D] show_lut_handler",
13559 profile.getDescription() if profile else None,
13560 "show:",
13561 show,
13562 )
13563 if show is None:
13564 show = bool(
13565 (
13566 hasattr(self, "show_lut")
13567 and self.show_lut
13568 and self.show_lut.GetValue()
13569 )
13570 or (not hasattr(self, "show_lut") or not self.show_lut)
13571 )
13572 setcfg("lut_viewer.show", int(show))
13573 if not profile and hasattr(self, "current_cal"):
13574 profile = self.current_cal
13575 if show:
13576 self.lut_viewer_load_lut(event, profile, force_draw=True)
13577 if getattr(self, "lut_viewer", None):
13578 self.menuitem_show_lut.Check(show)
13579 if self.lut_viewer.IsIconized() and show:
13580 self.lut_viewer.Restore()
13581 else:
13582 self.lut_viewer.Show(show)
13583 if show:
13584 self.lut_viewer.Raise()
13585
13586 def lut_viewer_close_handler(self, event: wx.Event = None) -> None:
13587 """Handle the close event for the LUT viewer.
13588
13589 Args:
13590 event (wx.Event, optional): The event that triggered this handler.
13591 """
13592 setcfg("lut_viewer.show", 0)
13593 self.lut_viewer.Hide()
13594 self.menuitem_show_lut.Check(False)
13595 if hasattr(self, "show_lut") and self.show_lut:
13596 self.show_lut.SetValue(self.lut_viewer.IsShownOnScreen())
13597
13598 def show_advanced_options_handler(self, event: wx.Event = None) -> None:
13599 """Show or hide advanced calibration settings.
13600
13601 Args:
13602 event (wx.Event, optional): The event that triggered this handler.
13603 """
13604 show_advanced_options = bool(getcfg("show_advanced_options"))
13605 if event:
13606 show_advanced_options = not show_advanced_options
13607 setcfg("show_advanced_options", int(show_advanced_options))
13608 self.panel.Freeze()
13609 self.menuitem_show_advanced_options.Check(show_advanced_options)
13610 self.menuitem_advanced_options.Enable(show_advanced_options)
13611 for ctrl in ( # Calibration options
13612 self.black_luminance_label,
13613 self.black_luminance_ctrl,
13614 # Profiling options
13615 self.black_point_compensation_cb,
13616 self.profile_type_label,
13617 self.profile_type_ctrl,
13618 self.gamap_btn,
13619 # Patch sequence
13620 self.testchart_patch_sequence_label,
13621 self.testchart_patch_sequence_ctrl,
13622 ):
13623 ctrl.GetContainingSizer().Show(ctrl, show_advanced_options)
13624 self.show_display_delay_ctrls()
13625 self.show_ffp_ctrls()
13626 self.show_output_levels_ctrls()
13627 self.whitepoint_colortemp_locus_label.Show(
13628 show_advanced_options and self.whitepoint_ctrl.GetSelection() != 2
13629 )
13630 self.whitepoint_colortemp_locus_ctrl.Show(
13631 show_advanced_options and self.whitepoint_ctrl.GetSelection() != 2
13632 )
13633 self.black_luminance_textctrl.Show(
13634 show_advanced_options and bool(getcfg("calibration.black_luminance", False))
13635 )
13636 self.black_luminance_textctrl_label.Show(
13637 show_advanced_options and bool(getcfg("calibration.black_luminance", False))
13638 )
13639 self.lut3d_show_controls()
13640 self.mr_show_trc_controls()
13641 if event:
13642 self.show_observer_ctrl()
13643 self.show_trc_controls()
13644 self.calpanel.Layout()
13645 self.calpanel.Refresh()
13646 self.panel.Thaw()
13647 if event:
13648 self.set_size(True)
13649 self.update_scrollbars()
13650
13651 def show_display_delay_ctrls(self) -> None:
13652 """Show or hide the display delay controls based on configuration."""
13653 show_advanced_options = bool(getcfg("show_advanced_options"))
13654 not_untethered = config.get_display_name(None, True) != "Untethered"
13655 for ctrl in (
13656 self.override_min_display_update_delay_ms,
13657 self.min_display_update_delay_ms,
13658 self.min_display_update_delay_ms_label,
13659 ):
13660 ctrl.GetContainingSizer().Show(
13661 ctrl, show_advanced_options and not_untethered
13662 )
13663 self.override_display_settle_time_mult.Show(
13664 show_advanced_options
13665 and getcfg("argyll.version") >= "1.7"
13666 and not_untethered
13667 )
13668 self.display_settle_time_mult.Show(
13669 show_advanced_options
13670 and getcfg("argyll.version") >= "1.7"
13671 and not_untethered
13672 )
13673
13674 def show_ffp_ctrls(self) -> None:
13675 """Show or hide the full field pattern controls based on configuration."""
13676 # Full field pattern insertion
13677 show_advanced_options = bool(getcfg("show_advanced_options"))
13678 display_name = config.get_display_name(None, True)
13679 ffp_show = show_advanced_options and (
13680 (
13681 display_name == "Prisma"
13682 and not DEFAULTS["patterngenerator.prisma.argyll"]
13683 )
13684 or display_name == "Resolve"
13685 or (
13686 display_name == "madVR"
13687 and (
13688 sys.platform != "win32"
13689 or not getcfg("madtpg.native")
13690 or bool(self.worker.argyll_virtual_display)
13691 )
13692 )
13693 )
13694 for ctrl in (
13695 self.ffp_insertion,
13696 self.ffp_insertion_interval_label,
13697 self.ffp_insertion_interval,
13698 self.ffp_insertion_interval_s_label,
13699 self.ffp_insertion_duration_label,
13700 self.ffp_insertion_duration,
13701 self.ffp_insertion_duration_s_label,
13702 self.ffp_insertion_level_label,
13703 self.ffp_insertion_level,
13704 self.ffp_insertion_level_percentage_label,
13705 ):
13706 ctrl.GetContainingSizer().Show(ctrl, ffp_show)
13707
13708 def show_output_levels_ctrls(self) -> None:
13709 """Show or hide the output levels controls based on configuration."""
13710 show_levels_config = config.get_display_name(None, True) not in (
13711 "madVR",
13712 "Untethered",
13713 ) and bool(getcfg("show_advanced_options"))
13714 for ctrl in (
13715 self.output_levels_label,
13716 self.output_levels_auto,
13717 self.output_levels_full_range,
13718 self.output_levels_limited_range,
13719 ):
13720 ctrl.Show(show_levels_config)
13721
13722 def show_observer_ctrl(self) -> None:
13723 """Show or hide the observer control based on configuration."""
13724 self.panel.Freeze()
13725 show = bool(
13726 (getcfg("calibration.interactive_display_adjustment") or getcfg("trc"))
13727 and getcfg("show_advanced_options")
13728 and self.worker.instrument_can_use_nondefault_observer()
13729 )
13730 self.observer_label.Show(show)
13731 self.observer_ctrl.Show(show)
13732 self.calpanel.Layout()
13733 self.panel.Thaw()
13734 self.update_scrollbars()
13735
13736 def update_observer_ctrl(self) -> None:
13737 """Update the observer control with available observers."""
13738 self.observer_ctrl.SetStringSelection(self.observers_ab[getcfg("observer")])
13739
13740 def install_profile_scope_handler(self, event: wx.Event) -> None:
13741 """Handle the selection of the profile installation scope.
13742
13743 Args:
13744 event (wx.Event): The event that triggered this handler.
13745 """
13746 if self.install_profile_systemwide.GetValue():
13747 setcfg("profile.install_scope", "l")
13748 if hasattr(self.modaldlg.ok, "SetAuthNeeded"):
13749 self.modaldlg.ok.SetAuthNeeded(True)
13750 elif (
13751 sys.platform == "darwin"
13752 and os.path.isdir("/Network/Library/ColorSync/Profiles")
13753 and self.install_profile_network.GetValue()
13754 ):
13755 setcfg("profile.install_scope", "n")
13756 elif self.install_profile_user.GetValue():
13757 setcfg("profile.install_scope", "u")
13758 if hasattr(self.modaldlg.ok, "SetAuthNeeded"):
13759 self.modaldlg.ok.SetAuthNeeded(False)
13760 self.modaldlg.buttonpanel.Layout()
13761
13762 def start_timers(self, wrapup: bool = False) -> None:
13763 """Start timers for profile name updates and keydown checks.
13764
13765 Args:
13766 wrapup (bool, optional): If True, wrap up the worker before
13767 starting the timers. Defaults to False.
13768 """
13769 if wrapup:
13770 self.worker.wrapup(False)
13771 if not self.update_profile_name_timer.IsRunning():
13772 self.update_profile_name_timer.Start(1000)
13773 if not self.check_keydown_timer.IsRunning():
13774 self.check_keydown_timer.Start(250)
13775 if (
13776 sys.platform == "darwin"
13777 and getcfg("profile_loader.macos_reapply_watch")
13778 and not self.lut_watch_timer.IsRunning()
13779 ):
13780 interval = max(
13781 1, int(getcfg("profile_loader.macos_reapply_watch_interval"))
13782 )
13783 self.lut_watch_timer.Start(interval * 1000)
13784
13785 def stop_timers(self) -> None:
13786 """Stop timers for profile name updates and keydown checks."""
13787 self.update_profile_name_timer.Stop()
13788 self.check_keydown_timer.Stop()
13789 self.lut_watch_timer.Stop()
13790
13791 def check_lut_clobbered(self, event: "wx.TimerEvent | None" = None) -> None:
13792 """Re-load calibration if macOS has clobbered the VideoLUT (issue #694).
13793
13794 Idle backstop to the in-session recovery in worker.exec_cmd: runs only on
13795 macOS and only while idle (no measurement in progress, so it can never
13796 disturb a running calibration). Any display whose VideoLUT has gone black
13797 is detected via CoreGraphics and re-loaded with ``dispwin -L``.
13798 """
13799 if sys.platform != "darwin" or self.worker.is_working():
13800 return
13801 if not getcfg("profile_loader.macos_reapply_watch"):
13802 return
13803 dispwin = get_argyll_util("dispwin")
13804 if dispwin:
13805 reload_black_videoluts(dispwin, log=self.worker.log)
13806
13807 def synthicc_create_handler(self, event: wx.Event) -> None:
13808 """Assign and initialize the synthetic ICC creation window."""
13809 if not getattr(self, "synthiccframe", None):
13810 self.init_synthiccframe()
13811 if self.synthiccframe.IsShownOnScreen():
13812 if self.synthiccframe.IsIconized():
13813 self.synthiccframe.Restore()
13814 self.synthiccframe.Raise()
13815 else:
13816 self.synthiccframe.Show(not self.synthiccframe.IsShownOnScreen())
13817
13818 def tab_select_handler(
13819 self,
13820 event: wx.Event,
13821 update_main_controls: bool = False,
13822 ) -> None:
13823 """Handle tab selection in the calibration panel.
13824
13825 Args:
13826 event (wx.Event): The event that triggered this handler.
13827 update_main_controls (bool): Whether to update the main controls
13828 after changing the tab. Defaults to False.
13829 """
13830 if hasattr(event, "EventObject") and not event.EventObject.IsEnabled():
13831 return
13832 self.panel.Freeze()
13833 btn2tab = {
13834 self.display_instrument_btn: self.display_instrument_panel,
13835 self.calibration_settings_btn: self.calibration_settings_panel,
13836 self.profile_settings_btn: self.profile_settings_panel,
13837 self.lut3d_settings_btn: self.lut3d_settings_panel,
13838 self.mr_settings_btn: self.mr_settings_panel,
13839 }
13840 for btn in btn2tab:
13841 tab = btn2tab[btn]
13842 if event.GetId() == btn.Id:
13843 if tab is self.mr_settings_panel and not tab.IsShown():
13844 self.mr_update_controls()
13845 elif tab is self.lut3d_settings_panel and not tab.IsShown():
13846 self.set_profile("output")
13847 self.lut3d_show_trc_controls()
13848 if hasattr(self, "install_profile_btn"):
13849 if tab is self.lut3d_settings_panel:
13850 self.install_profile_btn.SetToolTipString(
13851 lang.getstr("3dlut.install")
13852 )
13853 else:
13854 self.install_profile_btn.SetToolTipString(
13855 lang.getstr("profile.install")
13856 )
13857 tab.Show()
13858 btn._pressed = True
13859 btn._SetState(platebtn.PLATE_PRESSED)
13860 else:
13861 tab.Hide()
13862 btn._pressed = False
13863 btn._SetState(platebtn.PLATE_NORMAL)
13864 self.calpanel.Layout()
13865 if isinstance(event, wx.Event) or update_main_controls:
13866 self.update_main_controls()
13867 self.panel.Thaw()
13868 self.update_scrollbars()
13869 self.calpanel.Layout()
13870 self.calpanel.Update()
13871
13872 def colorimeter_correction_matrix_ctrl_handler(
13873 self, event: wx.Event, path: None | str = None
13874 ) -> None:
13875 """Handle the colorimeter correction matrix control.
13876
13877 Args:
13878 event (wx.Event): The event that triggered this handler.
13879 path (str, optional): The path to the colorimeter correction matrix
13880 file. If not provided, the current configuration will be used
13881 to determine the path.
13882 """
13883 measurement_mode = getcfg("measurement_mode")
13884 if event and event.GetId() == self.colorimeter_correction_matrix_ctrl.GetId():
13885 ccmx = getcfg("colorimeter_correction_matrix_file").split(":", 1)
13886 if self.colorimeter_correction_matrix_ctrl.GetSelection() == 0:
13887 # Off
13888 ccmx = ["", ""]
13889 elif self.colorimeter_correction_matrix_ctrl.GetSelection() == 1:
13890 # Auto
13891 ccmx = ["AUTO", ""]
13892 else:
13893 path = self.ccmx_item_paths[
13894 self.colorimeter_correction_matrix_ctrl.GetSelection() - 2
13895 ]
13896 ccmx = ["", path]
13897 setcfg("colorimeter_correction_matrix_file", ":".join(ccmx))
13898 self.update_colorimeter_correction_matrix_ctrl_items()
13899 else:
13900 if not path:
13901 ccmx = getcfg("colorimeter_correction_matrix_file").split(":", 1)
13902 default_dir, default_file = get_verified_path(None, ccmx.pop())
13903 dlg = wx.FileDialog(
13904 self,
13905 lang.getstr("colorimeter_correction_matrix_file.choose"),
13906 defaultDir=(
13907 default_dir if default_file else config.get_argyll_data_dir()
13908 ),
13909 defaultFile=default_file,
13910 wildcard=lang.getstr("filetype.ccmx") + "|*.ccmx;*.ccss",
13911 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
13912 )
13913 dlg.Center(wx.BOTH)
13914 if dlg.ShowModal() == wx.ID_OK:
13915 path = dlg.GetPath()
13916 dlg.Destroy()
13917 if path:
13918 if (
13919 getcfg("colorimeter_correction_matrix_file").split(":")[0] != "AUTO"
13920 or path not in self.ccmx_cached_paths
13921 ):
13922 setcfg("colorimeter_correction_matrix_file", ":" + path)
13923 self.update_colorimeter_correction_matrix_ctrl_items(
13924 warn_on_mismatch=True
13925 )
13926 if measurement_mode != getcfg("measurement_mode"):
13927 # Check if black point correction should be turned on
13928 self.measurement_mode_ctrl_handler()
13929
13930 def colorimeter_correction_info_handler(
13931 self, event: wx.Event, ccxx: None | str = None
13932 ) -> None:
13933 """Plot spectra or matrix.
13934
13935 Args:
13936 event (wx.Event): The event that triggered this handler.
13937 ccxx (None | str, optional): The path to the colorimeter correction
13938 matrix file. If not provided, the current configuration will be
13939 used to determine the path.
13940 """
13941 if not CCXXPlot:
13942 wx.Bell()
13943 return
13944
13945 if not ccxx:
13946 ccxx = getcfg("colorimeter_correction_matrix_file").split(":", 1)
13947 if len(ccxx) < 2 or not os.path.isfile(ccxx[1]):
13948 wx.Bell()
13949 return
13950
13951 ccxx = ccxx[1]
13952
13953 try:
13954 cgats = CGATS(ccxx)
13955 except Exception as exception:
13956 show_result_dialog(exception, self)
13957 return
13958
13959 if 0 not in cgats:
13960 wx.Bell()
13961 return
13962
13963 key = md5(bytes(cgats)).digest() # noqa: S324
13964 plotwindow = self.ccxx_plot_windows.get(key)
13965 if not plotwindow:
13966 plotwindow = CCXXPlot(self, cgats, self.worker)
13967 self.ccxx_plot_windows[key] = plotwindow
13968
13969 plotwindow.Show()
13970 plotwindow.Raise()
13971
13972 def colorimeter_correction_web_handler(self, event: wx.Event) -> None:
13973 """Check the web for cccmx or ccss files.
13974
13975 Args:
13976 event (wx.Event): The event that triggered this handler.
13977 """
13978 filetype = "ccss,ccmx" if self.worker.instrument_supports_ccss() else "ccmx"
13979 params = {
13980 "get": True,
13981 "type": filetype,
13982 "manufacturer_id": self.worker.get_display_edid().get(
13983 "manufacturer_id", ""
13984 ),
13985 "display": self.worker.get_display_name(False, True) or "Unknown",
13986 "instrument": self.worker.get_instrument_name() or "Unknown",
13987 "json": 1,
13988 }
13989 self.worker.interactive = False
13990 self.worker.start(
13991 colorimeter_correction_web_check_choose,
13992 http_request,
13993 ckwargs={"parent": self},
13994 wargs=(
13995 self,
13996 f"colorimetercorrections.{DOMAIN}",
13997 "GET",
13998 "/index.php",
13999 params,
14000 ),
14001 progress_msg=lang.getstr("colorimeter_correction.web_check"),
14002 stop_timers=False,
14003 cancelable=False,
14004 show_remaining_time=False,
14005 fancy=False,
14006 )
14007
14008 def create_colorimeter_correction_handler(
14009 self,
14010 event: None | wx.Event = None,
14011 paths: None | list[str] = None,
14012 luminance: None | float = None,
14013 ) -> None:
14014 """Create a CCSS or CCMX file from one or more .ti3 files.
14015
14016 Atleast one of the ti3 files must be a measured with a spectrometer.
14017
14018 Args:
14019 event (wx.Event): The event that triggered this handler.
14020 paths (list, optional): List of paths to .ti3 files.
14021 luminance (float, optional): Optional luminance value to use for
14022 the colorimeter correction. If not provided, the luminance will
14023 be determined from the reference instrument's measurement.
14024 """
14025 parent = self if event else None
14026 if wx.VERSION >= (3,):
14027 id_measure_reference = wx.Window.NewControlId()
14028 id_measure_colorimeter = wx.Window.NewControlId()
14029 else:
14030 id_measure_reference = IdFactory.NewId()
14031 id_measure_colorimeter = IdFactory.NewId()
14032 if not paths:
14033 dlg = ConfirmDialog(
14034 parent,
14035 title=lang.getstr("colorimeter_correction.create"),
14036 msg=lang.getstr("colorimeter_correction.create.info"),
14037 ok=lang.getstr("colorimeter_correction.create"),
14038 cancel=lang.getstr("cancel"),
14039 # alt=lang.getstr("browse"),
14040 bitmap=get_icon(32, "dialog-information"),
14041 wrap=90,
14042 )
14043 boxsizer = wx.BoxSizer(wx.HORIZONTAL)
14044 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
14045 warning_icon = wx.StaticBitmap(dlg, -1, get_icon(16, "dialog-warning"))
14046 boxsizer.Add(warning_icon)
14047 warning_text = wx.StaticText(
14048 dlg, -1, wrap(lang.getstr("colorimeter_correction.create.warning"), 86)
14049 )
14050 warning_text.ForegroundColour = "#F07F00"
14051 boxsizer.Add(warning_text, flag=wx.LEFT, border=8)
14052 # Colorimeter correction type
14053 # We deliberately don't use RadioBox because there's no way to
14054 # set the correct background color (this matters under MSWindows
14055 # where the dialog background is usually white) unless you use
14056 # Phoenix.
14057 boxsizer = wx.StaticBoxSizer(
14058 wx.StaticBox(dlg, -1, lang.getstr("type")), wx.VERTICAL
14059 )
14060 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
14061 if sys.platform not in ("darwin", "win32"):
14062 boxsizer.Add((1, 8))
14063 dlg.correction_type_matrix = wx.RadioButton(
14064 dlg, -1, lang.getstr("matrix"), style=wx.RB_GROUP
14065 )
14066 hsizer = wx.BoxSizer(wx.HORIZONTAL)
14067 boxsizer.Add(hsizer, flag=wx.ALL | wx.EXPAND, border=4)
14068 hsizer.Add(dlg.correction_type_matrix)
14069 dlg.four_color_matrix = wx.CheckBox(
14070 dlg, -1, lang.getstr("ccmx.use_four_color_matrix_method")
14071 )
14072 dlg.four_color_matrix.SetValue(
14073 bool(getcfg("ccmx.use_four_color_matrix_method"))
14074 )
14075 hsizer.Add(dlg.four_color_matrix, flag=wx.LEFT, border=8)
14076 dlg.correction_type_spectral = wx.RadioButton(
14077 dlg,
14078 -1,
14079 lang.getstr("spectral") + " (i1 DisplayPro, "
14080 "ColorMunki "
14081 "Display, Spyder4/5)",
14082 )
14083 boxsizer.Add(dlg.correction_type_spectral, flag=wx.ALL, border=4)
14084 {
14085 "matrix": dlg.correction_type_matrix,
14086 "spectral": dlg.correction_type_spectral,
14087 }.get(getcfg("colorimeter_correction.type"), "matrix").SetValue(True)
14088 # Get instruments
14089 reference_instruments = []
14090 colorimeters = []
14091 for instrument in self.worker.instruments:
14092 if instruments.get(instrument, {}).get("spectral"):
14093 reference_instruments.append(instrument)
14094 else:
14095 colorimeters.append(instrument)
14096 # Reference instrument
14097 boxsizer = wx.StaticBoxSizer(
14098 wx.StaticBox(
14099 dlg,
14100 -1,
14101 "{} ({})".format(
14102 lang.getstr("instrument"), lang.getstr("reference")
14103 ),
14104 ),
14105 wx.VERTICAL,
14106 )
14107 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
14108 if sys.platform not in ("darwin", "win32"):
14109 boxsizer.Add((1, 8))
14110 hsizer = wx.BoxSizer(wx.HORIZONTAL)
14111 boxsizer.Add(hsizer, flag=wx.EXPAND)
14112 dlg.reference_instrument = wx.Choice(dlg, -1, choices=reference_instruments)
14113 hsizer.Add(
14114 dlg.reference_instrument,
14115 1,
14116 flag=wx.LEFT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
14117 border=4,
14118 )
14119 hsizer.Add(
14120 wx.StaticText(dlg, -1, lang.getstr("measurement_mode")),
14121 flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
14122 border=8,
14123 )
14124 dlg.measurement_mode_reference = wx.Choice(dlg, -1, choices=[])
14125
14126 def set_ok_btn_state() -> None:
14127 """Set the state of the OK button based on the selected files."""
14128 dlg.ok.Enable(
14129 bool(
14130 getcfg("last_reference_ti3_path", False)
14131 and os.path.isfile(getcfg("last_reference_ti3_path"))
14132 and (
14133 (
14134 getcfg("last_colorimeter_ti3_path", False)
14135 and os.path.isfile(getcfg("last_colorimeter_ti3_path"))
14136 )
14137 or dlg.correction_type_spectral.GetValue()
14138 )
14139 )
14140 )
14141
14142 def check_last_ccxx_ti3(event: wx.Event) -> None:
14143 """Check the last ti3 file for the colorimeter or reference.
14144
14145 Args:
14146 event (wx.Event): The event that triggered this handler.
14147 """
14148 cfgname = "colorimeter_correction.measurement_mode"
14149 if event.GetId() in (
14150 dlg.instrument.Id,
14151 dlg.measurement_mode.Id,
14152 dlg.observer_ctrl.Id,
14153 dlg.colorimeter_ti3.textControl.Id,
14154 ):
14155 name = "colorimeter"
14156 instrument = dlg.instrument.GetStringSelection()
14157 measurement_mode = self.get_ccxx_measurement_modes(
14158 instrument, True
14159 ).get(dlg.measurement_mode.GetStringSelection())
14160 observer_ctrl = dlg.observer_ctrl
14161 else:
14162 name = "reference"
14163 cfgname += "." + name
14164 instrument = dlg.reference_instrument.GetStringSelection()
14165 if hasattr(dlg, "modes_ab"):
14166 measurement_mode = dlg.modes_ab["spect"][
14167 dlg.measurement_mode_reference.GetSelection()
14168 ]
14169 else:
14170 measurement_mode = None
14171 observer_ctrl = dlg.observer_reference_ctrl
14172 if DEBUG or VERBOSE >= 2:
14173 print("check_last_ccxx_ti3", name)
14174 print("instrument =", instrument)
14175 print("measurement_mode =", measurement_mode)
14176 if event.GetId() == getattr(dlg, f"{name}_ti3").textControl.Id:
14177 setcfg(
14178 f"last_{name}_ti3_path",
14179 getattr(dlg, f"{name}_ti3").GetValue(),
14180 )
14181 ti3 = getcfg(f"last_{name}_ti3_path", False)
14182 if DEBUG or VERBOSE >= 2:
14183 print(f"last_{name}_ti3_path =", ti3)
14184 if ti3:
14185 if os.path.isfile(ti3):
14186 try:
14187 cgats = CGATS(ti3)
14188 except (OSError, CGATSError) as exception:
14189 show_result_dialog(exception, dlg)
14190 cgats = CGATS()
14191 cgats_instrument = cgats.queryv1("TARGET_INSTRUMENT")
14192 if cgats_instrument:
14193 cgats_instrument = get_canonical_instrument_name(
14194 cgats_instrument
14195 )
14196 if DEBUG or VERBOSE >= 2:
14197 print("cgats_instrument =", cgats_instrument)
14198 if name == "reference":
14199 if getcfg(cfgname + ".projector"):
14200 cgats_measurement_mode = "p"
14201 else:
14202 cgats_measurement_mode = getcfg(cfgname)
14203 else:
14204 cgats_measurement_mode = get_cgats_measurement_mode(
14205 cgats, cgats_instrument
14206 )
14207 if cgats_measurement_mode:
14208 instrument_features = self.worker.get_instrument_features(
14209 instrument
14210 )
14211 if instrument_features.get("adaptive_mode") and getcfg(
14212 cfgname + ".adaptive"
14213 ):
14214 cgats_measurement_mode += "V"
14215 if (
14216 instrument_features.get("highres_mode")
14217 and cgats.queryv1("SPECTRAL_BANDS") is not None
14218 and cgats.queryv1("SPECTRAL_BANDS") > 36
14219 ):
14220 cgats_measurement_mode += "H"
14221 if DEBUG or VERBOSE >= 2:
14222 print("cgats_measurement_mode =", cgats_measurement_mode)
14223 cgats_observer = cgats.queryv1("OBSERVER")
14224 if not cgats_observer:
14225 cgats_observer = DEFAULTS["observer"].encode("utf-8")
14226 if event.GetId() == dlg.reference_ti3.textControl.Id:
14227 setcfg(
14228 "colorimeter_correction.observer.reference",
14229 cgats_observer.decode("utf-8"),
14230 )
14231 observer_ctrl.SetStringSelection(
14232 self.observers_ab[
14233 getcfg("colorimeter_correction.observer.reference")
14234 ]
14235 )
14236 if self.worker.instrument_can_use_nondefault_observer(
14237 instrument
14238 ):
14239 observer = self.observers_ba[
14240 observer_ctrl.GetStringSelection()
14241 ]
14242 else:
14243 observer = DEFAULTS["observer"]
14244 if DEBUG or VERBOSE >= 2:
14245 print("observer =", observer)
14246 if DEBUG or VERBOSE >= 2:
14247 print("cgats_observer =", cgats_observer)
14248 if (
14249 cgats_instrument.decode("utf-8") != instrument
14250 or cgats_measurement_mode != measurement_mode
14251 or cgats_observer.decode("utf-8") != observer
14252 ):
14253 ti3 = None
14254 else:
14255 ti3 = None
14256 if DEBUG or VERBOSE >= 2:
14257 print(f"last_{name}_ti3_path =", ti3)
14258 bmp = get_icon(16, "checkmark") if ti3 else get_icon(16, "empty")
14259 getattr(dlg, f"measure_{name}").SetBitmapLabel(bmp)
14260 getattr(dlg, f"measure_{name}").Refresh()
14261 getattr(dlg, f"measure_{name}")._bmp.SetToolTipString(ti3 or "")
14262 if isinstance(event, wx.Event):
14263 set_ok_btn_state()
14264
14265 dlg.measurement_mode_reference.Bind(wx.EVT_CHOICE, check_last_ccxx_ti3)
14266 hsizer.Add(
14267 dlg.measurement_mode_reference,
14268 flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
14269 border=8,
14270 )
14271 # Make measure button height match instrument choice height
14272 btn_h = dlg.reference_instrument.Size[1]
14273 if sys.platform == "win32" and sys.getwindowsversion() < (6, 2):
14274 # Windows 7 / Vista / XP
14275 btn_h += 2
14276 dlg.measure_reference = BitmapWithThemedButton(
14277 dlg,
14278 id_measure_reference,
14279 get_icon(16, "empty"),
14280 lang.getstr("measure"),
14281 size=(-1, btn_h),
14282 )
14283 if sys.platform == "win32":
14284 dlg.measure_reference.SetBackgroundColour(dlg.BackgroundColour)
14285 dlg.measure_reference.Bind(wx.EVT_BUTTON, dlg.OnClose)
14286 hsizer.Add(
14287 dlg.measure_reference,
14288 flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
14289 border=4,
14290 )
14291 dlg.measure_reference.Enable(
14292 bool(self.worker.displays and reference_instruments)
14293 )
14294 dlg.observer_reference_label = wx.StaticText(
14295 dlg, -1, lang.getstr("observer")
14296 )
14297 hsizer = wx.BoxSizer(wx.HORIZONTAL)
14298 boxsizer.Add(hsizer, flag=wx.BOTTOM, border=4)
14299 hsizer.Add(
14300 dlg.observer_reference_label,
14301 flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
14302 border=4,
14303 )
14304 dlg.observer_reference_ctrl = wx.Choice(
14305 dlg, -1, choices=list(self.observers_ab.values())
14306 )
14307 dlg.observer_reference_ctrl.Bind(wx.EVT_CHOICE, check_last_ccxx_ti3)
14308 hsizer.Add(
14309 dlg.observer_reference_ctrl,
14310 flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
14311 border=8,
14312 )
14313 dlg.observer_reference_ctrl.SetStringSelection(
14314 self.observers_ab[getcfg("colorimeter_correction.observer.reference")]
14315 )
14316 dlg.observer_reference_label.Show(bool(getcfg("show_advanced_options")))
14317 dlg.observer_reference_ctrl.Show(bool(getcfg("show_advanced_options")))
14318
14319 # Reference TI3
14320 default_dir, default_file = get_verified_path("last_reference_ti3_path")
14321 dlg.reference_ti3 = FileBrowseBitmapButtonWithChoiceHistory(
14322 dlg,
14323 -1,
14324 dialogTitle=lang.getstr("measurement_file.choose.reference"),
14325 toolTip=lang.getstr("browse"),
14326 startDirectory=default_dir,
14327 fileMask=lang.getstr("filetype.ti3") + "|*.ti3;*.icm;*.icc",
14328 )
14329 if default_file:
14330 dlg.reference_ti3.SetPath(os.path.join(default_dir, default_file))
14331 wx.CallAfter(dlg.reference_ti3.setupControl)
14332 dlg.reference_ti3.changeCallback = check_last_ccxx_ti3
14333 dlg.reference_ti3.SetMaxFontSize(11)
14334 dlg.reference_ti3_droptarget = FileDrop(dlg)
14335
14336 def reference_ti3_drop_handler(path: str) -> None:
14337 """Handle dropping a file onto the reference TI3 control.
14338
14339 Args:
14340 path (str): The path of the dropped file.
14341 """
14342 dlg.reference_ti3.SetPath(path)
14343 check_last_ccxx_ti3(dlg.reference_ti3.textControl)
14344 set_ok_btn_state()
14345
14346 dlg.reference_ti3_droptarget.drophandlers = {
14347 ".icc": reference_ti3_drop_handler,
14348 ".icm": reference_ti3_drop_handler,
14349 ".ti3": reference_ti3_drop_handler,
14350 }
14351 dlg.reference_ti3.SetDropTarget(dlg.reference_ti3_droptarget)
14352 boxsizer.Add(
14353 dlg.reference_ti3,
14354 flag=wx.RIGHT | wx.BOTTOM | wx.LEFT | wx.EXPAND,
14355 border=4,
14356 )
14357
14358 def reference_instrument_handler(event: wx.Event) -> None:
14359 """Handle the selection of the reference instrument.
14360
14361 Args:
14362 event (wx.Event): The event that triggered this handler.
14363 """
14364 mode, modes, dlg.modes_ab, modes_ba = self.get_measurement_modes(
14365 dlg.reference_instrument.GetStringSelection(),
14366 "spect",
14367 "colorimeter_correction.measurement_mode.reference",
14368 )
14369 dlg.measurement_mode_reference.SetItems(modes["spect"])
14370 dlg.measurement_mode_reference.SetSelection(
14371 min(modes_ba["spect"].get(mode, 1), len(modes["spect"]) - 1)
14372 )
14373 dlg.measurement_mode_reference.Enable(bool(modes["spect"]))
14374 boxsizer.Layout()
14375 if event:
14376 check_last_ccxx_ti3(event)
14377
14378 instrument = getcfg("colorimeter_correction.instrument.reference")
14379 if instrument in reference_instruments:
14380 dlg.reference_instrument.SetStringSelection(instrument)
14381 elif reference_instruments:
14382 dlg.reference_instrument.SetSelection(0)
14383 else:
14384 dlg.measurement_mode_reference.Disable()
14385 if reference_instruments:
14386 reference_instrument_handler(None)
14387 if len(reference_instruments) < 2:
14388 dlg.reference_instrument.Disable()
14389 else:
14390 dlg.reference_instrument.Bind(
14391 wx.EVT_CHOICE, reference_instrument_handler
14392 )
14393 # Instrument
14394 boxsizer = wx.StaticBoxSizer(
14395 wx.StaticBox(dlg, -1, lang.getstr("instrument")), wx.VERTICAL
14396 )
14397 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
14398 if sys.platform not in ("darwin", "win32"):
14399 boxsizer.Add((1, 8))
14400 hsizer = wx.BoxSizer(wx.HORIZONTAL)
14401 boxsizer.Add(hsizer, flag=wx.EXPAND)
14402 dlg.instrument = wx.Choice(dlg, -1, choices=colorimeters)
14403 hsizer.Add(
14404 dlg.instrument,
14405 1,
14406 flag=wx.LEFT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
14407 border=4,
14408 )
14409 hsizer.Add(
14410 wx.StaticText(dlg, -1, lang.getstr("measurement_mode")),
14411 flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
14412 border=8,
14413 )
14414 dlg.measurement_mode = wx.Choice(dlg, -1, choices=[])
14415 dlg.measurement_mode.Bind(wx.EVT_CHOICE, check_last_ccxx_ti3)
14416 hsizer.Add(
14417 dlg.measurement_mode,
14418 flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
14419 border=8,
14420 )
14421 dlg.measure_colorimeter = BitmapWithThemedButton(
14422 dlg,
14423 id_measure_colorimeter,
14424 get_icon(16, "empty"),
14425 lang.getstr("measure"),
14426 size=(-1, btn_h),
14427 )
14428 if sys.platform == "win32":
14429 dlg.measure_colorimeter.SetBackgroundColour(dlg.BackgroundColour)
14430 dlg.measure_colorimeter.Bind(wx.EVT_BUTTON, dlg.OnClose)
14431 hsizer.Add(
14432 dlg.measure_colorimeter,
14433 flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
14434 border=4,
14435 )
14436 dlg.measure_colorimeter.Enable(bool(self.worker.displays and colorimeters))
14437 dlg.observer_label = wx.StaticText(dlg, -1, lang.getstr("observer"))
14438 hsizer = wx.BoxSizer(wx.HORIZONTAL)
14439 boxsizer.Add(hsizer, flag=wx.BOTTOM, border=4)
14440 hsizer.Add(
14441 dlg.observer_label, flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=4
14442 )
14443 dlg.observer_ctrl = wx.Choice(
14444 dlg, -1, choices=list(self.observers_ab.values())
14445 )
14446 dlg.observer_ctrl.Bind(wx.EVT_CHOICE, check_last_ccxx_ti3)
14447 hsizer.Add(
14448 dlg.observer_ctrl, flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=8
14449 )
14450 dlg.observer_ctrl.SetStringSelection(
14451 self.observers_ab[getcfg("colorimeter_correction.observer")]
14452 )
14453
14454 # Colorimeter TI3
14455 default_dir, default_file = get_verified_path("last_colorimeter_ti3_path")
14456 dlg.colorimeter_ti3 = FileBrowseBitmapButtonWithChoiceHistory(
14457 dlg,
14458 -1,
14459 dialogTitle=lang.getstr("measurement_file.choose.colorimeter"),
14460 toolTip=lang.getstr("browse"),
14461 startDirectory=default_dir,
14462 fileMask=lang.getstr("filetype.ti3") + "|*.ti3;*.icm;*.icc",
14463 )
14464 if default_file:
14465 dlg.colorimeter_ti3.SetPath(os.path.join(default_dir, default_file))
14466 wx.CallAfter(dlg.colorimeter_ti3.setupControl)
14467 dlg.colorimeter_ti3.changeCallback = check_last_ccxx_ti3
14468 dlg.colorimeter_ti3.SetMaxFontSize(11)
14469 dlg.colorimeter_ti3_droptarget = FileDrop(dlg)
14470
14471 def colorimeter_ti3_drop_handler(path: str) -> None:
14472 """Handle dropping a file onto the colorimeter TI3 control.
14473
14474 Args:
14475 path (str): The path of the dropped file.
14476 """
14477 dlg.colorimeter_ti3.SetPath(path)
14478 check_last_ccxx_ti3(dlg.colorimeter_ti3.textControl)
14479 set_ok_btn_state()
14480
14481 dlg.colorimeter_ti3_droptarget.drophandlers = {
14482 ".icc": colorimeter_ti3_drop_handler,
14483 ".icm": colorimeter_ti3_drop_handler,
14484 ".ti3": colorimeter_ti3_drop_handler,
14485 }
14486 dlg.colorimeter_ti3.SetDropTarget(dlg.colorimeter_ti3_droptarget)
14487 boxsizer.Add(
14488 dlg.colorimeter_ti3,
14489 flag=wx.RIGHT | wx.BOTTOM | wx.LEFT | wx.EXPAND,
14490 border=4,
14491 )
14492
14493 def show_observer_ctrl() -> None:
14494 """Show or hide the observer control based on the instrument."""
14495 instrument_name = dlg.instrument.GetStringSelection()
14496 show = bool(
14497 getcfg("show_advanced_options")
14498 and self.worker.instrument_can_use_nondefault_observer(
14499 instrument_name
14500 )
14501 and getcfg("colorimeter_correction.observer")
14502 != DEFAULTS["colorimeter_correction.observer"]
14503 )
14504 dlg.observer_label.Show(show)
14505 dlg.observer_ctrl.Show(show)
14506 instrument_name = dlg.reference_instrument.GetStringSelection()
14507 show = bool(
14508 dlg.correction_type_matrix.GetValue()
14509 and getcfg("show_advanced_options")
14510 and self.worker.instrument_can_use_nondefault_observer(
14511 instrument_name
14512 )
14513 )
14514 dlg.observer_reference_label.Show(show)
14515 dlg.observer_reference_ctrl.Show(show)
14516
14517 def instrument_handler(event: wx.Event) -> None:
14518 """Handle the instrument selection.
14519
14520 Args:
14521 event (wx.Event): The event that triggered this handler.
14522 """
14523 dlg.Freeze()
14524 modes = self.get_ccxx_measurement_modes(
14525 dlg.instrument.GetStringSelection()
14526 )
14527 dlg.measurement_mode.SetItems(list(modes.values()))
14528 dlg.measurement_mode.SetStringSelection(
14529 modes.get(
14530 getcfg("colorimeter_correction.measurement_mode"),
14531 list(modes.values())[-1],
14532 )
14533 )
14534 dlg.measurement_mode.Enable(bool(modes))
14535 show_observer_ctrl()
14536 boxsizer.Layout()
14537 if event:
14538 check_last_ccxx_ti3(event)
14539 dlg.sizer0.SetSizeHints(dlg)
14540 dlg.sizer0.Layout()
14541 dlg.Refresh()
14542 dlg.Thaw()
14543
14544 instrument = getcfg("colorimeter_correction.instrument")
14545 if instrument in colorimeters:
14546 dlg.instrument.SetStringSelection(instrument)
14547 elif colorimeters:
14548 dlg.instrument.SetSelection(0)
14549 else:
14550 dlg.measurement_mode.Disable()
14551 if colorimeters:
14552 instrument_handler(None)
14553 if len(colorimeters) < 2:
14554 dlg.instrument.Disable()
14555 else:
14556 dlg.instrument.Bind(wx.EVT_CHOICE, instrument_handler)
14557
14558 # Bind event handlers
14559 def correction_type_handler(event: wx.Event) -> None:
14560 """Handle the correction type selection.
14561
14562 Args:
14563 event (wx.Event): The event that triggered this handler.
14564 """
14565 dlg.Freeze()
14566 for item in [*list(boxsizer.Children), boxsizer.StaticBox]:
14567 if isinstance(item, (wx.SizerItem, wx.Window)):
14568 item.Show(dlg.correction_type_matrix.GetValue())
14569 matrix = dlg.correction_type_matrix.GetValue()
14570 dlg.four_color_matrix.Enable(matrix)
14571 if not matrix:
14572 dlg.four_color_matrix.SetValue(False)
14573 show_observer_ctrl()
14574 set_ok_btn_state()
14575 dlg.sizer0.SetSizeHints(dlg)
14576 dlg.sizer0.Layout()
14577 dlg.Refresh()
14578 dlg.Thaw()
14579
14580 dlg.correction_type_matrix.Bind(wx.EVT_RADIOBUTTON, correction_type_handler)
14581 dlg.correction_type_spectral.Bind(
14582 wx.EVT_RADIOBUTTON, correction_type_handler
14583 )
14584 # Layout
14585 check_last_ccxx_ti3(dlg.measurement_mode_reference)
14586 check_last_ccxx_ti3(dlg.measurement_mode)
14587 correction_type_handler(None)
14588 result = dlg.ShowWindowModalBlocking()
14589 if result != wx.ID_CANCEL:
14590 observer = self.observers_ba.get(
14591 dlg.observer_reference_ctrl.GetStringSelection()
14592 )
14593 setcfg("colorimeter_correction.observer.reference", observer)
14594 if result in (id_measure_reference, id_measure_colorimeter):
14595 setcfg(
14596 "colorimeter_correction.instrument.reference",
14597 dlg.reference_instrument.GetStringSelection(),
14598 )
14599 mode, modes, modes_ab, modes_ba = self.get_measurement_modes(
14600 dlg.reference_instrument.GetStringSelection(),
14601 "spect",
14602 "colorimeter_correction.measurement_mode.reference",
14603 )
14604 mode = (
14605 modes_ab.get("spect", {}).get(
14606 dlg.measurement_mode_reference.GetSelection()
14607 )
14608 or "l"
14609 )
14610 setcfg(
14611 "colorimeter_correction.measurement_mode.reference",
14612 (strtr(mode, {"V": "", "H": ""}) if mode else None) or None,
14613 )
14614 setcfg(
14615 "colorimeter_correction.measurement_mode.reference.adaptive",
14616 1 if mode and "V" in mode else 0,
14617 )
14618 setcfg(
14619 "colorimeter_correction.measurement_mode.reference.highres",
14620 1 if mode and "H" in mode else 0,
14621 )
14622 setcfg(
14623 "colorimeter_correction.measurement_mode.reference.projector",
14624 1 if mode and "p" in mode else None,
14625 )
14626 observer = self.observers_ba.get(dlg.observer_ctrl.GetStringSelection())
14627 setcfg("colorimeter_correction.observer", observer)
14628 setcfg(
14629 "colorimeter_correction.instrument",
14630 dlg.instrument.GetStringSelection(),
14631 )
14632 modes = self.get_ccxx_measurement_modes(
14633 dlg.instrument.GetStringSelection(), True
14634 )
14635 if dlg.measurement_mode.GetStringSelection() in modes:
14636 setcfg(
14637 "colorimeter_correction.measurement_mode",
14638 modes[dlg.measurement_mode.GetStringSelection()],
14639 )
14640 elif result == wx.ID_OK:
14641 paths = [getcfg("last_reference_ti3_path")]
14642 if dlg.correction_type_matrix.GetValue():
14643 paths.append(getcfg("last_colorimeter_ti3_path"))
14644 setcfg(
14645 "ccmx.use_four_color_matrix_method",
14646 int(dlg.four_color_matrix.GetValue()),
14647 )
14648 if result != wx.ID_CANCEL:
14649 setcfg(
14650 "colorimeter_correction.type",
14651 {True: "matrix", False: "spectral"}[
14652 dlg.correction_type_matrix.GetValue()
14653 ],
14654 )
14655 dlg.Destroy()
14656 else:
14657 result = -1
14658 if result == wx.ID_CANCEL:
14659 return None
14660 if result in (id_measure_reference, id_measure_colorimeter):
14661 # Select CCXX testchart
14662 ccxx_testchart = get_ccxx_testchart()
14663 if not ccxx_testchart:
14664 show_result_dialog(
14665 Error(lang.getstr("not_found", lang.getstr("ccxx.ti1"))), self
14666 )
14667 return None
14668 if not is_ccxx_testchart():
14669 # Backup testchart selection
14670 setcfg("testchart.file.backup", getcfg("testchart.file"))
14671 self.set_testchart(ccxx_testchart)
14672 # Backup instrument selection
14673 setcfg("comport.number.backup", getcfg("comport.number"))
14674 # Backup observer
14675 setcfg("observer.backup", getcfg("observer"))
14676 if result == id_measure_reference:
14677 # Switch to reference instrument
14678 setcfg(
14679 "comport.number",
14680 self.worker.instruments.index(
14681 getcfg("colorimeter_correction.instrument.reference")
14682 )
14683 + 1,
14684 )
14685 # Set measurement mode
14686 setcfg(
14687 "measurement_mode",
14688 getcfg("colorimeter_correction.measurement_mode.reference"),
14689 )
14690 setcfg(
14691 "measurement_mode.adaptive",
14692 getcfg(
14693 "colorimeter_correction.measurement_mode.reference.adaptive"
14694 ),
14695 )
14696 setcfg(
14697 "measurement_mode.highres",
14698 getcfg("colorimeter_correction.measurement_mode.reference.highres"),
14699 )
14700 setcfg(
14701 "measurement_mode.projector",
14702 getcfg(
14703 "colorimeter_correction.measurement_mode.reference.projector"
14704 ),
14705 )
14706 # Set observer
14707 setcfg("observer", getcfg("colorimeter_correction.observer.reference"))
14708 else:
14709 # Switch to colorimeter
14710 setcfg(
14711 "comport.number",
14712 self.worker.instruments.index(
14713 getcfg("colorimeter_correction.instrument")
14714 )
14715 + 1,
14716 )
14717 # Set measurement mode
14718 setcfg(
14719 "measurement_mode",
14720 getcfg("colorimeter_correction.measurement_mode"),
14721 )
14722 # Set observer
14723 setcfg("observer", getcfg("colorimeter_correction.observer"))
14724 self.measure_handler()
14725 return None
14726 try:
14727 ccxx_testchart = get_ccxx_testchart()
14728 if not ccxx_testchart:
14729 raise Error(lang.getstr("not_found", lang.getstr("ccxx.ti1")))
14730 ccxx = CGATS(ccxx_testchart)
14731 except (
14732 OSError,
14733 Error,
14734 CGATSInvalidError,
14735 CGATSInvalidOperationError,
14736 CGATSKeyError,
14737 CGATSTypeError,
14738 CGATSValueError,
14739 ) as exception:
14740 show_result_dialog(exception, self)
14741 return None
14742 cgats_list = []
14743 reference_ti3 = None
14744 colorimeter_ti3 = None
14745 spectral = False
14746 if getcfg("colorimeter_correction.type") == "matrix":
14747 ti3_range = (0, 1)
14748 else:
14749 ti3_range = (0,)
14750 for n in range(len(paths or ti3_range)):
14751 path = None
14752 if not paths:
14753 if reference_ti3:
14754 default_dir, default_file = get_verified_path(
14755 "last_colorimeter_ti3_path"
14756 )
14757 msg = lang.getstr("measurement_file.choose.colorimeter")
14758 else:
14759 default_dir, default_file = get_verified_path(
14760 "last_reference_ti3_path"
14761 )
14762 msg = lang.getstr("measurement_file.choose.reference")
14763 dlg = wx.FileDialog(
14764 parent,
14765 msg,
14766 defaultDir=default_dir,
14767 defaultFile=default_file,
14768 wildcard=lang.getstr("filetype.ti3") + "|*.ti3;*.icm;*.icc",
14769 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
14770 )
14771 dlg.Center(wx.BOTH)
14772 if dlg.ShowModal() == wx.ID_OK:
14773 path = dlg.GetPath()
14774 dlg.Destroy()
14775 else:
14776 path = paths[n]
14777 if path:
14778 try:
14779 if os.path.splitext(path.lower())[1] in (".icm", ".icc"):
14780 profile = ICCProfile(path)
14781 meta = profile.tags.get("meta", {})
14782 cgats = self.worker.ti1_lookup_to_ti3(
14783 ccxx, profile, pcs="x", intent="a"
14784 )[1]
14785 cgats.add_keyword(
14786 "DATA_SOURCE",
14787 meta.get("DATA_source", {}).get("value", "").upper()
14788 or "Unknown",
14789 )
14790 if cgats.DATA_SOURCE == "EDID":
14791 instrument = "EDID"
14792 else:
14793 targ = profile.tags.get(
14794 "CIED", profile.tags.get("targ", b"")
14795 )
14796 instrument = None
14797 if targ[0:4] == b"CTI3":
14798 targ = CGATS(targ)
14799 instrument = targ.queryv1("TARGET_INSTRUMENT")
14800 if not instrument:
14801 instrument = meta.get("MEASUREMENT_device", {}).get(
14802 "value", "Unknown"
14803 )
14804 cgats.add_keyword("TARGET_INSTRUMENT", instrument)
14805 spec_type = (
14806 "YES"
14807 if instruments.get(
14808 get_canonical_instrument_name(cgats.TARGET_INSTRUMENT),
14809 {},
14810 ).get("spectral", False)
14811 else "NO"
14812 )
14813 cgats.add_keyword("INSTRUMENT_TYPE_SPECTRAL", spec_type)
14814 cgats.ARGYLL_COLPROF_ARGS = CGATS()
14815 cgats.ARGYLL_COLPROF_ARGS.key = "ARGYLL_COLPROF_ARGS"
14816 cgats.ARGYLL_COLPROF_ARGS.parent = cgats
14817 cgats.ARGYLL_COLPROF_ARGS.root = cgats
14818 cgats.ARGYLL_COLPROF_ARGS.type = "SECTION"
14819 display = (
14820 meta.get("EDID_model", meta.get("EDID_model_id", {}))
14821 .get("value", "")
14822 .encode("utf-7")
14823 )
14824 manufacturer = (
14825 meta.get("EDID_manufacturer", {})
14826 .get("value", "")
14827 .encode("utf-7")
14828 )
14829 cgats.ARGYLL_COLPROF_ARGS.add_data(
14830 f'-M "{display}" -A "{manufacturer}"'
14831 )
14832 cgats = CGATS(bytes(cgats))
14833 else:
14834 cgats = CGATS(path)
14835 if not cgats.queryv1("DATA"):
14836 raise CGATSError("Missing DATA")
14837 except Exception:
14838 traceback.print_exc()
14839 InfoDialog(
14840 self,
14841 title=lang.getstr("colorimeter_correction.create"),
14842 msg=lang.getstr("error.measurement.file_invalid", path),
14843 ok=lang.getstr("ok"),
14844 bitmap=get_icon(32, "dialog-error"),
14845 )
14846 return None
14847 else:
14848 cgats_list.append(cgats)
14849 # Check if measurement contains spectral values
14850 # Check if instrument type is spectral
14851 if (
14852 cgats.queryv1("SPECTRAL_BANDS")
14853 or cgats.queryv1("DATA_SOURCE") == b"EDID"
14854 ):
14855 if reference_ti3:
14856 # We already have a reference ti3
14857 reference_ti3 = None
14858 break
14859 reference_ti3 = cgats
14860 setcfg("last_reference_ti3_path", path)
14861 if cgats.queryv1("SPECTRAL_BANDS"):
14862 spectral = True
14863 if (
14864 event
14865 and getcfg("colorimeter_correction.type") == "matrix"
14866 ):
14867 result = -1
14868 else:
14869 result = wx.ID_OK
14870 if result == wx.ID_OK:
14871 break
14872 if result == wx.ID_CANCEL:
14873 return None
14874 elif cgats.queryv1("INSTRUMENT_TYPE_SPECTRAL") == b"YES":
14875 if reference_ti3:
14876 # We already have a reference ti3
14877 reference_ti3 = None
14878 break
14879 reference_ti3 = cgats
14880 setcfg("last_reference_ti3_path", path)
14881 elif cgats.queryv1("INSTRUMENT_TYPE_SPECTRAL") == b"NO":
14882 if colorimeter_ti3:
14883 # We already have a colorimeter ti3
14884 colorimeter_ti3 = None
14885 break
14886 colorimeter_ti3 = cgats
14887 setcfg("last_colorimeter_ti3_path", path)
14888 else:
14889 # User canceled dialog
14890 return None
14891 # Check if atleast one file has been measured with a reference
14892 if not reference_ti3:
14893 InfoDialog(
14894 self,
14895 title=lang.getstr("colorimeter_correction.create"),
14896 msg=lang.getstr("error.measurement.one_reference"),
14897 ok=lang.getstr("ok"),
14898 bitmap=get_icon(32, "dialog-error"),
14899 )
14900 return None
14901 if event:
14902 cfgname = "colorimeter_correction.measurement_mode"
14903 else:
14904 cfgname = "measurement_mode"
14905 if len(cgats_list) == 2:
14906 if not colorimeter_ti3:
14907 # If 2 files, check if atleast one file has NOT been measured
14908 # with a spectro (CCMX creation)
14909 InfoDialog(
14910 self,
14911 title=lang.getstr("colorimeter_correction.create"),
14912 msg=lang.getstr("error.measurement.one_colorimeter"),
14913 ok=lang.getstr("ok"),
14914 bitmap=get_icon(32, "dialog-error"),
14915 )
14916 return None
14917 # Use only the device combinations from CCXX testchart
14918 reference_new = CGATS(b"BEGIN_DATA\nEND_DATA")
14919 reference_new.DATA_FORMAT = reference_ti3.queryv1("DATA_FORMAT")
14920 colorimeter_new = CGATS(b"BEGIN_DATA\nEND_DATA")
14921 colorimeter_new.DATA_FORMAT = colorimeter_ti3.queryv1("DATA_FORMAT")
14922 data_reference = reference_ti3.queryv1("DATA")
14923 data_colorimeter = colorimeter_ti3.queryv1("DATA")
14924 required = ccxx.queryv(("RGB_R", "RGB_G", "RGB_B"))
14925 devicecombination2name = {
14926 "RGB_R=100 RGB_G=100 RGB_B=100": "white",
14927 "RGB_R=100 RGB_G=0 RGB_B=0": "red",
14928 "RGB_R=0 RGB_G=100 RGB_B=0": "green",
14929 "RGB_R=0 RGB_G=0 RGB_B=100": "blue",
14930 }
14931 for _i in required:
14932 values = required[_i]
14933 patch = {
14934 "RGB_R": values[0],
14935 "RGB_G": values[1],
14936 "RGB_B": values[2],
14937 }
14938 devicecombination = " ".join(
14939 ["=".join([key, f"{value:.0f}"]) for key, value in patch.items()]
14940 )
14941 name = devicecombination2name.get(devicecombination, devicecombination)
14942 item = data_reference.queryi1(patch)
14943 if item:
14944 reference_new.DATA.add_data(item)
14945 else:
14946 show_result_dialog(
14947 lang.getstr(
14948 "error.testchart.missing_fields",
14949 (
14950 os.path.basename(reference_ti3.filename),
14951 lang.getstr(name),
14952 ),
14953 )
14954 )
14955 return None
14956 item = data_colorimeter.queryi1(patch)
14957 if item:
14958 colorimeter_new.DATA.add_data(item)
14959 else:
14960 show_result_dialog(
14961 lang.getstr(
14962 "error.testchart.missing_fields",
14963 (
14964 os.path.basename(colorimeter_ti3.filename),
14965 lang.getstr(name),
14966 ),
14967 )
14968 )
14969 return None
14970 reference_ti3.queryi1("DATA").DATA = reference_new.DATA
14971 colorimeter_ti3.queryi1("DATA").DATA = colorimeter_new.DATA
14972 # If the reference comes from EDID, normalize luminance
14973 if reference_ti3.queryv1("DATA_SOURCE") == b"EDID":
14974 white = colorimeter_ti3.queryi1("DATA").queryi1(
14975 {"RGB_R": 100, "RGB_G": 100, "RGB_B": 100}
14976 )
14977 scale = luminance / 100.0 if luminance else 1.0
14978 white = " ".join(
14979 [
14980 str(v)
14981 for v in (
14982 white["XYZ_X"] * scale,
14983 white["XYZ_Y"] * scale,
14984 white["XYZ_Z"] * scale,
14985 )
14986 ]
14987 )
14988 colorimeter_ti3.queryi1("DATA").LUMINANCE_XYZ_CDM2 = white
14989 # Add display base ID if missing
14990 self.worker.check_add_display_type_base_id(colorimeter_ti3, cfgname)
14991 elif not spectral:
14992 # If 1 file, check if it contains spectral values (CCSS creation)
14993 InfoDialog(
14994 self,
14995 title=lang.getstr("colorimeter_correction.create"),
14996 msg=lang.getstr("error.measurement.missing_spectral"),
14997 ok=lang.getstr("ok"),
14998 bitmap=get_icon(32, "dialog-error"),
14999 )
15000 return None
15001 # Add display type
15002 for cgats in cgats_list:
15003 if not cgats.queryv1("DISPLAY_TYPE_REFRESH"):
15004 cgats[0].add_keyword(
15005 "DISPLAY_TYPE_REFRESH",
15006 {"c": b"YES", "l": b"NO"}.get(getcfg(cfgname), b"NO"),
15007 )
15008 print(
15009 "Added DISPLAY_TYPE_REFRESH {!r}".format(
15010 cgats[0].DISPLAY_TYPE_REFRESH.decode("utf-8")
15011 )
15012 )
15013 options_dispcal, options_colprof = get_options_from_ti3(reference_ti3)
15014 display = None
15015 manufacturer = None
15016 manufacturer_display = None
15017 for option in options_colprof:
15018 if option.startswith("M"):
15019 display = option[1:].strip(' "')
15020 elif option.startswith("A"):
15021 manufacturer = option[1:].strip(' "')
15022 if manufacturer:
15023 quirk_manufacturer = colord.quirk_manufacturer(manufacturer)
15024 if (
15025 manufacturer
15026 and display
15027 and quirk_manufacturer.lower() not in display.lower()
15028 ):
15029 manufacturer_display = f"{quirk_manufacturer} {display}"
15030 elif display:
15031 manufacturer_display = display
15032
15033 if isinstance(manufacturer_display, bytes):
15034 manufacturer_display = manufacturer_display.decode("utf-8")
15035
15036 if len(cgats_list) == 2:
15037 instrument = colorimeter_ti3.queryv1("TARGET_INSTRUMENT")
15038 if instrument:
15039 instrument = get_canonical_instrument_name(instrument)
15040 if isinstance(instrument, bytes):
15041 instrument = instrument.decode("utf-8")
15042 observer = getcfg("colorimeter_correction.observer.reference")
15043 if observer == "1931_2":
15044 description = "{} & {}".format( # noqa: UP032
15045 instrument or self.worker.get_instrument_name(),
15046 manufacturer_display or self.worker.get_display_name(True, True),
15047 )
15048 else:
15049 description = "{} ({} {}) & {}".format(
15050 instrument or self.worker.get_instrument_name(),
15051 lang.getstr(f"observer.{observer}"),
15052 lang.getstr("observer"),
15053 manufacturer_display or self.worker.get_display_name(True, True),
15054 )
15055 else:
15056 description = manufacturer_display or self.worker.get_display_name(
15057 True, True
15058 )
15059 if sys.platform == "darwin":
15060 # In case of internal screen, get 'nice' description
15061 model_id = display or util_mac.get_model_id()
15062 if model_id and re.match(
15063 r"iBook|iMac|MacBook|PowerBook", model_id, flags=re.I
15064 ):
15065 attrs = util_mac.get_machine_attributes(model_id) or {}
15066 description = description.replace(
15067 model_id, attrs.get("marketingModel", model_id)
15068 )
15069 target_instrument = reference_ti3.queryv1("TARGET_INSTRUMENT")
15070 if target_instrument:
15071 target_instrument = get_canonical_instrument_name(target_instrument)
15072 if isinstance(target_instrument, bytes):
15073 target_instrument = target_instrument.decode("utf-8")
15074 description = f"{description} ({target_instrument})"
15075 args = []
15076 tech = {b"YES": "Unknown"}.get(
15077 reference_ti3.queryv1("DISPLAY_TYPE_REFRESH"), b"LCD"
15078 )
15079 technology_strings = self.worker.get_technology_strings()
15080 debug_print(
15081 "reference_ti3.queryv1('DISPLAY_TYPE_REFRESH'): "
15082 f"{reference_ti3.queryv1('DISPLAY_TYPE_REFRESH')}"
15083 )
15084 debug_print(f"tech: {tech}")
15085 debug_print(f"technology_string: {technology_strings}")
15086 if event:
15087 # Allow user to alter description, display and instrument
15088 dlg = ConfirmDialog(
15089 parent,
15090 title=lang.getstr("colorimeter_correction.create"),
15091 msg=lang.getstr("colorimeter_correction.create.details"),
15092 ok=lang.getstr("ok"),
15093 cancel=lang.getstr("cancel"),
15094 bitmap=get_icon(32, "dialog-information"),
15095 )
15096 boxsizer = wx.StaticBoxSizer(
15097 wx.StaticBox(dlg, -1, lang.getstr("description")), wx.VERTICAL
15098 )
15099 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
15100 if sys.platform not in ("darwin", "win32"):
15101 boxsizer.Add((1, 8))
15102 dlg.description_txt_ctrl = wx.TextCtrl(dlg, -1, description, size=(400, -1))
15103 boxsizer.Add(
15104 dlg.description_txt_ctrl,
15105 1,
15106 flag=wx.ALL | wx.ALIGN_LEFT | wx.EXPAND,
15107 border=4,
15108 )
15109 boxsizer = wx.StaticBoxSizer(
15110 wx.StaticBox(dlg, -1, lang.getstr("display")), wx.VERTICAL
15111 )
15112 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
15113 if sys.platform not in ("darwin", "win32"):
15114 boxsizer.Add((1, 8))
15115 if not display:
15116 # protects from an improperly formatted display name in the ref.ti3
15117 display = self.worker.get_display_name(False, True, False)
15118 dlg.display_txt_ctrl = wx.TextCtrl(dlg, -1, display, size=(400, -1))
15119 boxsizer.Add(
15120 dlg.display_txt_ctrl,
15121 1,
15122 flag=wx.ALL | wx.ALIGN_LEFT | wx.EXPAND,
15123 border=4,
15124 )
15125 use_manufacturer_txt_ctrl = not manufacturer
15126 if use_manufacturer_txt_ctrl:
15127 boxsizer = wx.StaticBoxSizer(
15128 wx.StaticBox(dlg, -1, lang.getstr("display.manufacturer")),
15129 wx.VERTICAL,
15130 )
15131 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
15132 if sys.platform not in ("darwin", "win32"):
15133 boxsizer.Add((1, 8))
15134 if not PNP_ID_CACHE:
15135 # Populate pnpidcache
15136 get_manufacturer_name("???")
15137 dlg.manufacturer_txt_ctrl = wx.Choice(
15138 dlg,
15139 -1,
15140 choices=natsort(list(PNP_ID_CACHE.values())),
15141 size=(400, -1),
15142 )
15143 manufacturer_selection = self.worker.get_display_edid().get(
15144 "manufacturer", ""
15145 )
15146 if len(manufacturer_selection) < 1:
15147 manufacturer_selection = "Unknown"
15148 dlg.manufacturer_txt_ctrl.SetStringSelection(manufacturer_selection)
15149 boxsizer.Add(
15150 dlg.manufacturer_txt_ctrl,
15151 1,
15152 flag=wx.ALL | wx.ALIGN_LEFT | wx.EXPAND,
15153 border=4,
15154 )
15155 # Display technology
15156 boxsizer = wx.StaticBoxSizer(
15157 wx.StaticBox(dlg, -1, lang.getstr("display.tech")), wx.VERTICAL
15158 )
15159 dlg.sizer3.Add(boxsizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
15160 if sys.platform not in ("darwin", "win32"):
15161 boxsizer.Add((1, 8))
15162 loctech = {}
15163 techloc = {}
15164 for technology_string in list(technology_strings.values()):
15165 loc = lang.getstr(
15166 f"display.tech.{technology_string}", default=technology_string
15167 )
15168 loctech[loc] = technology_string
15169 techloc[technology_string] = loc
15170 dlg.display_tech_ctrl = wx.Choice(dlg, -1, choices=list(loctech.keys()))
15171 dlg.display_tech_ctrl.SetStringSelection(techloc.get(tech, ""))
15172 boxsizer.Add(
15173 dlg.display_tech_ctrl, flag=wx.ALL | wx.ALIGN_LEFT | wx.EXPAND, border=4
15174 )
15175 btn = PlateButton(
15176 dlg, -1, lang.getstr("info.display_tech.show"), get_icon(16, "info")
15177 )
15178 set_platebutton_bitmaps(btn, "info")
15179 btn.Bind(wx.EVT_BUTTON, self.display_tech_info_show_handler)
15180 boxsizer.Add(btn, flag=wx.ALL | wx.ALIGN_LEFT, border=4)
15181 dlg.description_txt_ctrl.SetFocus()
15182 dlg.sizer0.SetSizeHints(dlg)
15183 dlg.sizer0.Layout()
15184 dlg.Center()
15185 result = dlg.ShowWindowModalBlocking()
15186 description = safe_str(dlg.description_txt_ctrl.GetValue().strip(), "UTF-8")
15187 display = dlg.display_txt_ctrl.GetValue()
15188 if (
15189 dlg.display_tech_ctrl.IsEnabled()
15190 and dlg.display_tech_ctrl.GetStringSelection()
15191 ):
15192 tech = loctech[dlg.display_tech_ctrl.GetStringSelection()]
15193 if use_manufacturer_txt_ctrl:
15194 manufacturer = dlg.manufacturer_txt_ctrl.GetStringSelection()
15195 dlg.Destroy()
15196 if result != wx.ID_OK:
15197 return None
15198 else:
15199 description += " AUTO"
15200 args.extend(["-E", description])
15201 if display:
15202 args.extend(["-I", safe_str(display.strip(), "UTF-8")])
15203 ccxxmake_version = get_argyll_version("ccxxmake")
15204 if reference_ti3 and (not colorimeter_ti3 or ccxxmake_version >= [1, 7]):
15205 if ccxxmake_version >= [1, 7]:
15206 args.extend(
15207 [
15208 "-t",
15209 {v: k for k, v in technology_strings.items()}.get(tech, "u"),
15210 ]
15211 )
15212 else:
15213 args.extend(["-T", safe_str(tech, "UTF-8")])
15214 # Prepare our files
15215 cwd = self.worker.create_tempdir()
15216 ti3_tmp_names = []
15217 if reference_ti3:
15218 reference_ti3.write(os.path.join(cwd, "reference.ti3"))
15219 ti3_tmp_names.append("reference.ti3")
15220 result = True
15221 if colorimeter_ti3:
15222 # Create CCMX
15223 colorimeter_ti3.write(os.path.join(cwd, "colorimeter.ti3"))
15224 ti3_tmp_names.append("colorimeter.ti3")
15225 name = "correction"
15226 ext = ".ccmx"
15227 # CCSS-capable instruments enable creating a CCMX that maps from
15228 # non-standard observer A used for the colorimeter measurements
15229 # to non-standard observer B used for the reference measurements.
15230 # To get correct readings (= matching reference observer B) when
15231 # using such a CCMX, observer A needs to be used, not observer B.
15232 observer = colorimeter_ti3.queryv1("OBSERVER")
15233 reference_observer = getcfg("colorimeter_correction.observer.reference")
15234 if spectral and reference_observer != reference_ti3.queryv1(
15235 "OBSERVER"
15236 ).decode("utf-8"):
15237 # We can override the observer if we have spectral data
15238 # Need to use spec2cie to convert spectral data to
15239 # CIE XYZ with given observer, because we later use the XYZ
15240 spec2cie = get_argyll_util("spec2cie")
15241 if not spec2cie:
15242 show_result_dialog(
15243 Error(lang.getstr("argyll.util.not_found", "spec2cie"))
15244 )
15245 self.worker.wrapup(False)
15246 return None
15247 os.rename(
15248 os.path.join(cwd, "reference.ti3"),
15249 os.path.join(cwd, "reference_orig.ti3"),
15250 )
15251 result = self.worker.exec_cmd(
15252 spec2cie,
15253 [
15254 "-o",
15255 reference_observer,
15256 os.path.join(cwd, "reference_orig.ti3"),
15257 os.path.join(cwd, "reference.ti3"),
15258 ],
15259 capture_output=True,
15260 skip_scripts=True,
15261 silent=False,
15262 working_dir=cwd,
15263 )
15264 if not isinstance(result, Exception) and result:
15265 ref_ti3_fn_orig = reference_ti3.filename
15266 reference_ti3 = CGATS(os.path.join(cwd, "reference.ti3"))
15267 reference_ti3.filename = ref_ti3_fn_orig
15268 # spec2cie doesn't update "LUMINANCE_XYZ_CDM2", and doesn't
15269 # normalize measurement data to Y=100
15270 XYZ_CDM2 = reference_ti3.queryv1("LUMINANCE_XYZ_CDM2") # noqa: N806
15271 white = reference_ti3.queryi1(
15272 {"RGB_R": 100, "RGB_G": 100, "RGB_B": 100}
15273 )
15274 scale = white["XYZ_Y"] / 100.0
15275 if XYZ_CDM2:
15276 # Fix LUMINANCE_XYZ_CDM2
15277 # Note that for oberservers other than 1931 2 degree,
15278 # Y is not in cd/m2, but we try and keep the same
15279 # relationship
15280 XYZ_CDM2 = [float(v) for v in XYZ_CDM2.split()] # noqa: N806
15281 XYZ_CDM2 = [ # noqa: N806
15282 f"{v * XYZ_CDM2[1] / 100.0:.6f}"
15283 for v in list(
15284 white.queryv1(("XYZ_X", "XYZ_Y", "XYZ_Z")).values()
15285 )
15286 ]
15287 reference_ti3[0].LUMINANCE_XYZ_CDM2 = " ".join(XYZ_CDM2)
15288 data_format = reference_ti3.queryv1("DATA_FORMAT")
15289 # Remove L*a*b*. Do not use iter, as we change the
15290 # dictionary in-place
15291 for i, column in list(data_format.items()):
15292 if column.startswith("LAB_"):
15293 del data_format[i]
15294 # Normalize to Y=100
15295 data = reference_ti3.queryv1("DATA")
15296 for _i in data:
15297 sample = data[_i]
15298 for column in data_format.values():
15299 if column.startswith(("XYZ_", "SPEC_")):
15300 sample[column] /= scale
15301 reference_ti3.write()
15302 # The -o observer argument for ccxxmake isn't really needed
15303 # when we used spec2cie. Add it regardless for good measure
15304 args.append("-o")
15305 args.append(reference_observer)
15306 else:
15307 reference_observer = reference_ti3.queryv1("OBSERVER").decode("utf-8")
15308 else:
15309 # Create CCSS
15310 args.append("-S")
15311 name = "calibration"
15312 ext = ".ccss"
15313 observer = None
15314 reference_observer = None
15315 args.append("-f")
15316 args.append(",".join(ti3_tmp_names))
15317 args.append(name + ext)
15318 if not isinstance(result, Exception) and result:
15319 result = self.worker.create_ccxx(args, cwd)
15320 source = os.path.join(self.worker.tempdir, name + ext)
15321 if isinstance(result, Exception):
15322 show_result_dialog(result, self)
15323 elif result and os.path.isfile(source):
15324 if colorimeter_ti3:
15325 white_abs = []
15326 for _j, meas in enumerate((reference_ti3, colorimeter_ti3)):
15327 # Get absolute whitepoint
15328 _lum = meas.queryv1("LUMINANCE_XYZ_CDM2")
15329 white = (
15330 _lum.decode("utf-8") if _lum is not None else None
15331 ) or meas.queryi1({"RGB_R": 100, "RGB_G": 100, "RGB_B": 100})
15332 if isinstance(white, str):
15333 white = [float(v) for v in white.split()]
15334 elif isinstance(white, CGATS):
15335 white = white["XYZ_X"], white["XYZ_Y"], white["XYZ_Z"]
15336 else:
15337 # This shouldn't happen
15338 white = colormath.get_whitepoint("D65", scale=100)
15339 print(
15340 APPNAME + ": Warning - could not find white - "
15341 "dE calculation will be inaccurate"
15342 )
15343 white_abs.append(white)
15344 if DEBUG or VERBOSE > 1:
15345 print("ref white {:.6f} {:.6f} {:.6f}".format(*white_abs[0]))
15346 white_ref = [v / white_abs[0][1] for v in white_abs[0]]
15347 if getcfg("ccmx.use_four_color_matrix_method"):
15348 print(f"{APPNAME}: Creating matrix using four-color method")
15349 XYZ = [] # noqa: N806
15350 for j, meas in enumerate((reference_ti3, colorimeter_ti3)):
15351 for R, G, B in [ # noqa: N806
15352 (100, 0, 0),
15353 (0, 100, 0),
15354 (0, 0, 100),
15355 (100, 100, 100),
15356 ]:
15357 item = meas.queryi1("DATA").queryi1(
15358 {"RGB_R": R, "RGB_G": G, "RGB_B": B}
15359 )
15360 X, Y, Z = item["XYZ_X"], item["XYZ_Y"], item["XYZ_Z"] # noqa: N806
15361 X, Y, Z = (v * white_abs[j][1] / 100.0 for v in (X, Y, Z)) # noqa: N806
15362 XYZ.extend((X, Y, Z))
15363 R = colormath.four_color_matrix(*XYZ) # noqa: N806
15364 print(f"{APPNAME}: Correction matrix is:")
15365 ccmx = CGATS(source)
15366 for i in range(3):
15367 print(" {:.6f} {:.6f} {:.6f}".format(*R[i]))
15368 for j, component in enumerate("XYZ"):
15369 ccmx[0].DATA[i][f"XYZ_{component}"] = R[i][j]
15370 ccmx.write()
15371 # Important: Do not use parsed CGATS, order of keywords may be
15372 # different than raw data so MD5 will be different
15373 try:
15374 with open(source, "rb") as cgatsfile:
15375 cgats = universal_newlines(cgatsfile.read())
15376 except Exception as exception:
15377 traceback.print_exc()
15378 show_result_dialog(exception, self)
15379 self.worker.wrapup(False)
15380 return None
15381 if reference_ti3[0].get("TARGET_INSTRUMENT") and not re.search(
15382 rb'\nREFERENCE\s+".+?"\n', cgats
15383 ):
15384 # By default, CCSS files don't contain reference instrument
15385 cgats = re.sub(
15386 rb'(\nDISPLAY\s+"[^"]*"\n)',
15387 b'\nREFERENCE "%s"\\1'
15388 % reference_ti3[0].get("TARGET_INSTRUMENT").replace(b"\\", b"\\\\"),
15389 cgats,
15390 )
15391 if not re.search(rb'\nTECHNOLOGY\s+".+?"\n', cgats) and tech:
15392 # By default, CCMX files don't contain technology string
15393 cgats = re.sub(
15394 rb'(\nDISPLAY\s+"[^"]*"\n)',
15395 b'\nTECHNOLOGY "%s"\\1' % tech,
15396 cgats,
15397 )
15398 manufacturer_id = None
15399 if manufacturer:
15400 if not PNP_ID_CACHE:
15401 # Populate pnpidcache
15402 get_manufacturer_name("???")
15403 manufacturers = dict([name, id_] for id_, name in PNP_ID_CACHE.items())
15404 manufacturer_id = manufacturers.get(manufacturer)
15405 debug_print(f"manufacturer_id: {manufacturer_id}")
15406 debug_print(f"manufacturer : {manufacturer}")
15407 if manufacturer_id and not re.search(
15408 rb'\nMANUFACTURER_ID\s+".+?"\n', cgats
15409 ):
15410 # By default, CCMX/CCSS files don't contain manufacturer ID
15411 cgats = re.sub(
15412 rb'(\nDISPLAY\s+"[^"]*"\n)',
15413 b'\nMANUFACTURER_ID "%s"\\1'
15414 % manufacturer_id.replace("\\", "\\\\").encode("utf-8"),
15415 cgats,
15416 )
15417 if manufacturer and not re.search(rb'\nMANUFACTURER\s+".+?"\n', cgats):
15418 # By default, CCMX/CCSS files don't contain manufacturer
15419 cgats = re.sub(
15420 rb'(\nDISPLAY\s+"[^"]*"\n)',
15421 b'\nMANUFACTURER "%s"\\1'
15422 % manufacturer.replace("\\", "\\\\").encode("utf-8"),
15423 cgats,
15424 )
15425 if observer and not re.search(rb'\nOBSERVER\s+".+?"\n', cgats):
15426 # By default, CCMX/CCSS files don't contain observer
15427 cgats = re.sub(
15428 rb'(\nDISPLAY\s+"[^"]*"\n)',
15429 b'\nOBSERVER "%s"\\1' % observer.replace(b"\\", b"\\\\"),
15430 cgats,
15431 )
15432 if reference_observer and not re.search(
15433 rb'\nREFERENCE_OBSERVER\s+".+?"\n', cgats
15434 ):
15435 # By default, CCMX/CCSS files don't contain observer
15436 cgats = re.sub(
15437 rb'(\nDISPLAY\s+"[^"]*"\n)',
15438 b'\nREFERENCE_OBSERVER "%s"\\1'
15439 % reference_observer.encode("UTF-8").replace(b"\\", b"\\\\"),
15440 cgats,
15441 )
15442 result = check_create_dir(config.get_argyll_data_dir())
15443 if isinstance(result, Exception):
15444 show_result_dialog(result, self)
15445 self.worker.wrapup(False)
15446 return None
15447 if colorimeter_ti3:
15448 # CCMX
15449 # Show reference vs corrected colorimeter values along with
15450 # delta E
15451 matrix = colormath.Matrix3x3()
15452 ccmx = CGATS(cgats)
15453 for i, sample in ccmx.queryv1("DATA").items():
15454 matrix.append([])
15455 for component in "XYZ":
15456 matrix[i].append(sample[f"XYZ_{component}"])
15457 dlg = ConfirmDialog(
15458 parent,
15459 msg=lang.getstr("colorimeter_correction.create.success"),
15460 ok=lang.getstr("save"),
15461 cancel=lang.getstr("testchart.discard"),
15462 bitmap=get_icon(32, "dialog-information"),
15463 )
15464 sizer = wx.BoxSizer(wx.HORIZONTAL)
15465 dlg.sizer3.Add(sizer, 1, flag=wx.TOP | wx.EXPAND, border=12)
15466 labels = (
15467 "{} ({})".format(
15468 get_canonical_instrument_name(
15469 reference_ti3.queryv1("TARGET_INSTRUMENT")
15470 or lang.getstr("instrument")
15471 ).decode("utf-8"),
15472 lang.getstr("reference"),
15473 ),
15474 "{} ({})".format(
15475 get_canonical_instrument_name(
15476 ccmx.queryv1("INSTRUMENT") or lang.getstr("instrument")
15477 ).decode("utf-8"),
15478 lang.getstr("corrected"),
15479 ),
15480 )
15481 scale = getcfg("app.dpi") / config.get_default_dpi()
15482 scale = max(scale, 1)
15483 for i, label in enumerate(labels):
15484 txt = wx.StaticText(
15485 dlg,
15486 -1,
15487 label,
15488 size=(80 * scale * (3 + i), -1),
15489 style=wx.ALIGN_CENTER_HORIZONTAL,
15490 )
15491 font = txt.Font
15492 font.SetWeight(wx.FONTWEIGHT_BOLD)
15493 txt.Font = font
15494 sizer.Add(txt, flag=wx.LEFT, border=40)
15495 if "gtk3" in wx.PlatformInfo:
15496 style = wx.BORDER_SIMPLE
15497 else:
15498 style = wx.BORDER_THEME
15499 grid = CustomGrid(
15500 dlg,
15501 -1,
15502 size=(
15503 640 * scale + wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X),
15504 -1,
15505 ),
15506 style=style,
15507 )
15508 grid.Size = grid.Size[0], grid.GetDefaultRowSize() * 4
15509 dlg.sizer3.Add(grid, flag=wx.TOP | wx.ALIGN_LEFT, border=4)
15510 grid.DisableDragColSize()
15511 grid.DisableDragRowSize()
15512 grid.SetCellHighlightPenWidth(0)
15513 grid.SetCellHighlightROPenWidth(0)
15514 grid.SetColLabelSize(grid.GetDefaultRowSize())
15515 grid.SetDefaultCellAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
15516 grid.SetMargins(0, 0)
15517 grid.SetRowLabelAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
15518 grid.SetRowLabelSize(40)
15519 grid.SetScrollRate(0, 5)
15520 grid.draw_horizontal_grid_lines = False
15521 grid.draw_vertical_grid_lines = False
15522 grid.EnableEditing(False)
15523 grid.EnableGridLines(False)
15524 grid.CreateGrid(0, 9)
15525 for i, label in enumerate(
15526 ["x", "y", "Y", "", "", "x", "y", "Y", "ΔE*00"]
15527 ):
15528 # Rectangular (width = height)
15529 size = grid.GetDefaultRowSize() if i in (3, 4) else 80 * scale
15530 grid.SetColSize(i, int(size))
15531 grid.SetColLabelValue(i, label)
15532 grid.BeginBatch()
15533 ref_data = reference_ti3.queryv1("DATA")
15534 tgt_data = colorimeter_ti3.queryv1("DATA")
15535 deltaE_94 = [] # noqa: N806
15536 deltaE_00 = [] # noqa: N806
15537 print("")
15538 print(
15539 " Reference xyY |"
15540 " Corrected xyY |"
15541 " DE94 | DE00 "
15542 )
15543 print("-" * 80)
15544 for i in ref_data:
15545 ref = ref_data[i]
15546 tgt = tgt_data[i]
15547 grid.AppendRows(1)
15548 row = grid.GetNumberRows() - 1
15549 grid.SetRowLabelValue(row, f"{ref.SAMPLE_ID:.0f}")
15550 XYZ = [] # noqa: N806
15551 XYZabs = [] # noqa: N806
15552 xyYabs = [] # noqa: N806
15553 for j, sample in enumerate((ref, tgt)):
15554 # Get samples
15555 XYZ.append([])
15556 for component in "XYZ":
15557 XYZ[j].append(sample[f"XYZ_{component}"])
15558 # Scale to absolute brightness
15559 XYZabs.append(list(XYZ[j]))
15560 for k, value in enumerate(XYZabs[j]):
15561 XYZabs[j][k] = value * white_abs[j][1] / 100.0
15562 if j == 1:
15563 # Apply matrix to colorimeter measurements
15564 XYZabs[j] = matrix * XYZabs[j]
15565 xyYabs.append(colormath.XYZ2xyY(*XYZabs[j]))
15566 # Set cell values
15567 for k, value in enumerate(xyYabs[j]):
15568 grid.SetCellValue(row, j * 5 + k, f"{value:.4f}")
15569 # Show sRGB approximation of measured patch
15570 X, Y, Z = [ # noqa: N806
15571 v / max(white_abs[0][1], (matrix * white_abs[1])[1])
15572 for v in XYZabs[j]
15573 ]
15574 # Adapt from reference white to D65
15575 X, Y, Z = colormath.adapt(X, Y, Z, white_ref, "D65") # noqa: N806
15576 # Convert XYZ to sRGB
15577 RGB = [round(v) for v in colormath.XYZ2RGB(X, Y, Z, scale=255)] # noqa: N806
15578 grid.SetCellBackgroundColour(row, 3 + j, wx.Colour(*RGB))
15579 if DEBUG or VERBOSE > 1:
15580 print(
15581 "ref {:.6f} {:.6f} {:.6f}, ".format(*XYZabs[0]),
15582 "col {:.6f} {:.6f} {:.6f}".format(*XYZabs[1]),
15583 )
15584 Lab_ref = colormath.XYZ2Lab(*XYZabs[0] + [white_abs[0]]) # noqa: N806
15585 Lab_tgt = colormath.XYZ2Lab(*XYZabs[1] + [white_abs[0]]) # noqa: N806
15586 if DEBUG or VERBOSE > 1:
15587 print(
15588 "ref Lab {:.6f} {:.6f} {:.6f}, ".format(*Lab_ref),
15589 "col Lab {:.6f} {:.6f} {:.6f}".format(*Lab_tgt),
15590 )
15591 # For comparison to Argyll DE94 values
15592 deltaE = colormath.delta(*Lab_ref + Lab_tgt + ("94",))["E"] # noqa: N806
15593 deltaE_94.append(deltaE)
15594 deltaE = colormath.delta(*Lab_ref + Lab_tgt + ("00",))["E"] # noqa: N806
15595 deltaE_00.append(deltaE)
15596 print(
15597 (
15598 " {:.6f} {:.6f} {:8.4f} | "
15599 "{:.6f} {:.6f} {:8.4f} | {:.6f} | {:.6f} "
15600 ).format(
15601 *(
15602 tuple(xyYabs[0])
15603 + tuple(xyYabs[1])
15604 + (deltaE_94[-1], deltaE_00[-1])
15605 )
15606 )
15607 )
15608 grid.SetCellValue(row, 8, f"{deltaE:.4f}")
15609 print("")
15610 print(
15611 f"{APPNAME}: Fit error is max {max(deltaE_94):.6f}, "
15612 f"avg {sum(deltaE_94) / len(deltaE_94):.6f} DE94"
15613 )
15614 print(
15615 f"{APPNAME}: Fit error is max {max(deltaE_00):.6f}, "
15616 f"avg {sum(deltaE_00) / len(deltaE_00):.6f} DE00"
15617 )
15618 grid.DefaultCellBackgroundColour = grid.LabelBackgroundColour
15619 grid.EndBatch()
15620 dlg.sizer0.SetSizeHints(dlg)
15621 dlg.sizer0.Layout()
15622 result = dlg.ShowWindowModalBlocking() if event else wx.ID_OK
15623 dlg.Destroy()
15624 if result != wx.ID_OK:
15625 self.worker.wrapup(False)
15626 return None
15627 # Add dE fit error to CGATS as meta
15628 for label, fit_error in (
15629 ("MAX_DE94", max(deltaE_94)),
15630 ("AVG_DE94", sum(deltaE_94) / len(deltaE_94)),
15631 ("MAX_DE00", max(deltaE_00)),
15632 ("AVG_DE00", sum(deltaE_00) / len(deltaE_00)),
15633 ):
15634 cgats = re.sub(
15635 rb'(\nREFERENCE\s+"[^"]*"\n)',
15636 (f'\\1FIT_{label} "{fit_error:.6f}"\n').encode("utf-8"), # noqa: UP012
15637 cgats,
15638 )
15639 metadata = []
15640 # Add measurement file names and checksum to CCXX
15641 for label, meas in (
15642 ("REFERENCE", reference_ti3),
15643 ("TARGET", colorimeter_ti3),
15644 ):
15645 if meas and meas.filename:
15646 metadata.append(
15647 '{}_FILENAME "{}"'.format(
15648 label, safe_str(meas.filename, "UTF-8")
15649 )
15650 )
15651 metadata.append(
15652 '{}_HASH "md5:{}"'.format( # noqa: UP032
15653 label,
15654 md5(bytes(meas).strip()).hexdigest(), # noqa: S324
15655 )
15656 )
15657 if DEBUG or TEST:
15658 # Add original measurement data to CGATS as meta
15659 ccmx_data_format = [
15660 "RGB_R",
15661 "RGB_G",
15662 "RGB_B",
15663 "XYZ_X",
15664 "XYZ_Y",
15665 "XYZ_Z",
15666 ]
15667 for label, meas in (
15668 ("REFERENCE", reference_ti3),
15669 ("TARGET", colorimeter_ti3),
15670 ):
15671 XYZ_CDM2 = meas.queryv1("LUMINANCE_XYZ_CDM2") # noqa: N806
15672 if XYZ_CDM2:
15673 metadata.append(
15674 '{}_LUMINANCE_XYZ_CDM2 "{}"'.format(
15675 label, XYZ_CDM2.decode("utf-8")
15676 )
15677 )
15678 if not colorimeter_ti3:
15679 break
15680 metadata.append(
15681 '{}_DATA_FORMAT "{}"'.format(label, " ".join(ccmx_data_format))
15682 )
15683 data_format = meas.queryv1("DATA_FORMAT")
15684 data = meas.queryv1("DATA")
15685 for i in data:
15686 sample = data[i]
15687 RGB_XYZ = [str(sample[column]) for column in ccmx_data_format] # noqa: N806
15688 metadata.append(
15689 '{}_DATA_{:.0f} "{}"'.format(
15690 label, i + 1, " ".join(RGB_XYZ)
15691 )
15692 )
15693 # Line length limit for CGATS keywords 1024 chars, add
15694 # spectral data as individual keywords
15695 for column in data_format.values():
15696 column = column.decode("utf-8")
15697 if column not in ccmx_data_format and column != "SAMPLE_ID":
15698 metadata.append(
15699 f"{label}_DATA_{i + 1:.0f}_{column} "
15700 f'"{sample[column]}"'
15701 )
15702 if colorimeter_ti3 and getcfg("ccmx.use_four_color_matrix_method"):
15703 cgats = re.sub(
15704 rb'(\nORIGINATOR\s+)"Argyll[^"]+"',
15705 (rf'\1"{APPNAME} {VERSION_STRING}"').encode("utf-8"), # noqa: UP012
15706 cgats,
15707 )
15708 metadata.append('FIT_METHOD "xy"')
15709 else:
15710 metadata.append('FIT_METHOD "ΔE*94"')
15711 if metadata:
15712 debug_print(f"medatadata: {metadata}")
15713 cgats = re.sub(
15714 rb'(\nREFERENCE\s+"[^"]*"\n)',
15715 (
15716 "\\1{}\n".format("\n".join(metadata).replace("\\", "\\\\"))
15717 ).encode("utf-8"),
15718 cgats,
15719 )
15720 if event:
15721 if colorimeter_correction_check_overwrite(
15722 self, cgats, bool(colorimeter_ti3)
15723 ):
15724 self.upload_colorimeter_correction(cgats)
15725 else:
15726 path = get_cgats_path(cgats)
15727 with open(path, "wb") as cgatsfile:
15728 cgatsfile.write(cgats)
15729 setcfg("colorimeter_correction_matrix_file", ":" + path)
15730 elif result is not None:
15731 InfoDialog(
15732 self,
15733 title=lang.getstr("colorimeter_correction.create"),
15734 msg=lang.getstr("colorimeter_correction.create.failure")
15735 + "\n"
15736 + "".join(self.worker.errors),
15737 ok=lang.getstr("cancel"),
15738 bitmap=get_icon(32, "dialog-error"),
15739 log=False,
15740 )
15741 self.worker.wrapup(False)
15742 return True
15743
15744 def upload_colorimeter_correction(
15745 self, cgats: None | str | bytes | list | Path | io.IOBase | ICCProfileTag
15746 ) -> None:
15747 """Prompt user to upload colorimeter correction to the online database.
15748
15749 Args:
15750 cgats (None | str | bytes | list | Path | io.IOBase | ICCProfileTag): The
15751 CGATS data to upload.
15752 """
15753 dlg = ConfirmDialog(
15754 self,
15755 msg=lang.getstr("colorimeter_correction.upload.confirm"),
15756 ok=lang.getstr("ok"),
15757 cancel=lang.getstr("cancel"),
15758 bitmap=get_icon(32, "dialog-information"),
15759 )
15760 dlg.info = PlateButton(
15761 dlg.buttonpanel,
15762 -1,
15763 lang.getstr("colorimeter_correction.info"),
15764 get_icon(16, "info"),
15765 )
15766 set_platebutton_bitmaps(dlg.info, "info")
15767
15768 def show_ccxx_info(event: wx.Event) -> None:
15769 """Show information about the colorimeter correction.
15770
15771 Args:
15772 event (wx.Event): The event that triggered this handler.
15773 """
15774 self.colorimeter_correction_info_handler(event, cgats)
15775
15776 dlg.info.Bind(wx.EVT_BUTTON, show_ccxx_info)
15777 dlg.sizer2.Insert(
15778 0, dlg.info, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=12
15779 )
15780 dlg.sizer2.Insert(0, (32 + 7, 1))
15781 result = dlg.ShowWindowModalBlocking()
15782 dlg.Destroy()
15783 if result != wx.ID_OK:
15784 return
15785 if isinstance(cgats, str):
15786 # upload_colorimeter_correction_handler() passes a str (decoded
15787 # from the file), but the regex below requires bytes; normalize
15788 # so it doesn't raise TypeError.
15789 cgats = cgats.encode("utf-8")
15790 ccxx = CGATS(cgats)
15791 # Remove platform-specific/potentially sensitive information
15792 cgats = re.sub(rb'\n(?:REFERENCE|TARGET)_FILENAME\s+"[^"]+"\n', b"\n", cgats)
15793 params = {"cgats": cgats}
15794 # Also upload reference and target CGATS (if available)
15795 for label in ("REFERENCE", "TARGET"):
15796 filename = (ccxx.queryv1(f"{label}_FILENAME") or b"").decode("utf-8")
15797 algo_hash = ((ccxx.queryv1(f"{label}_HASH") or b"").decode("utf-8")).split(
15798 ":", 1
15799 )
15800 if filename and os.path.isfile(filename) and algo_hash[0] in globals():
15801 meas = bytes(CGATS(filename)).strip()
15802 # Check hash
15803 if globals()[algo_hash[0]](meas).hexdigest() == algo_hash[-1]:
15804 params[label.lower() + "_cgats"] = meas
15805 if DEBUG or TEST:
15806 print(list(params.keys()))
15807 # Upload correction
15808 self.worker.interactive = False
15809 self.worker.start(
15810 lambda result: result,
15811 upload_colorimeter_correction,
15812 wargs=(self, params),
15813 progress_msg=lang.getstr("colorimeter_correction.upload"),
15814 stop_timers=False,
15815 cancelable=False,
15816 show_remaining_time=False,
15817 fancy=False,
15818 )
15819
15820 def upload_colorimeter_correction_handler(self, event: wx.Event) -> None:
15821 """Let user choose a ccss/ccmx file to upload.
15822
15823 Args:
15824 event (wx.Event): The event that triggered this handler.
15825 """
15826 path = None
15827 default_dir, default_file = get_verified_path("last_filedialog_path")
15828 dlg = wx.FileDialog(
15829 self,
15830 lang.getstr("colorimeter_correction_matrix_file.choose"),
15831 defaultDir=default_dir,
15832 defaultFile=default_file,
15833 wildcard=lang.getstr("filetype.ccmx") + "|*.ccmx;*.ccss",
15834 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
15835 )
15836 dlg.Center(wx.BOTH)
15837 if dlg.ShowModal() == wx.ID_OK:
15838 path = dlg.GetPath()
15839 dlg.Destroy()
15840 if not path:
15841 return
15842 setcfg("last_filedialog_path", path)
15843 # Important: Do not use parsed CGATS, order of keywords may be
15844 # different than raw data so MD5 will be different
15845 with open(path, "rb") as cgatsfile:
15846 cgats = cgatsfile.read().decode()
15847 originator = re.search(r'\nORIGINATOR\s+"Argyll', cgats)
15848 if not originator:
15849 originator = re.search(r'\nORIGINATOR\s+"' + APPNAME, cgats)
15850 if not originator:
15851 InfoDialog(
15852 self,
15853 msg=lang.getstr("colorimeter_correction.upload.deny"),
15854 ok=lang.getstr("cancel"),
15855 bitmap=get_icon(32, "dialog-error"),
15856 )
15857 else:
15858 self.upload_colorimeter_correction(cgats)
15859
15860 def comport_ctrl_handler(
15861 self, event: None | wx.Event = None, force: bool = False
15862 ) -> None:
15863 """Handle the COM port selection control.
15864
15865 Updates the configuration based on the selected COM port
15866 and enables/disables menu items related to colorimeter calibration
15867 and colorimeter correction.
15868
15869 Args:
15870 event (None | wx.Event, optional): The event that triggered this
15871 handler.
15872 force (bool, optional): If True, forces the update of the
15873 colorimeter correction matrix control items.
15874 """
15875 if DEBUG and event:
15876 print(
15877 "[D] comport_ctrl_handler called for ID "
15878 f"{event.GetId()} {getevtobjname(event, self)} event type "
15879 f"{event.GetEventType()} {getevttype(event)}"
15880 )
15881 if self.comport_ctrl.GetSelection() > -1:
15882 setcfg("comport.number", self.comport_ctrl.GetSelection() + 1)
15883 self.menuitem_calibrate_instrument.Enable(
15884 bool(self.worker.get_instrument_features().get("sensor_cal"))
15885 )
15886 self.update_measurement_modes()
15887 enable_ccxx = (
15888 self.worker.instrument_can_use_ccxx(False)
15889 and not is_ccxx_testchart()
15890 and getcfg("measurement_mode") != "auto"
15891 )
15892 self.menuitem_choose_colorimeter_correction.Enable(enable_ccxx)
15893 self.menuitem_colorimeter_correction_web.Enable(enable_ccxx)
15894 self.update_colorimeter_correction_matrix_ctrl()
15895 self.update_colorimeter_correction_matrix_ctrl_items(force)
15896
15897 def import_colorimeter_corrections_handler(
15898 self,
15899 event: wx.Event,
15900 paths: None | list[str] = None,
15901 callafter: None | Callable = None,
15902 callafter_args: tuple = (),
15903 ) -> None | bool:
15904 """Import colorimeter corrections from other profiling software.
15905
15906 Currently supported: iColor Display (native import to CCMX),
15907 i1 Profiler (import to CCSS via Argyll CMS >= 1.3.4)
15908 Spyder4/5 (import to spyd4cal.bin via Argyll CMS >= 1.3.6)
15909
15910 Args:
15911 event (wx.Event): The event that triggered this handler.
15912 paths (None | list, optional): List of paths to files to import. If
15913 None, the user will be prompted to select files.
15914 callafter (callable, optional): Function to call after the import
15915 is done.
15916 callafter_args (tuple, optional): Arguments to pass to the
15917 callafter function.
15918
15919 Returns:
15920 bool: True if the import was successful, False otherwise.
15921 """
15922 msg = " ".join(
15923 [
15924 lang.getstr("oem.import.auto"),
15925 lang.getstr("oem.import.auto.download_selection"),
15926 ]
15927 )
15928 if sys.platform == "win32":
15929 msg = " ".join([lang.getstr("oem.import.auto_windows"), msg])
15930 result = None
15931 i1d3 = None
15932 i1d3ccss = None
15933 spyd4 = None
15934 spyd4en = None
15935 icd = None
15936 oeminst = get_argyll_util("oeminst")
15937 importers = {}
15938 if not oeminst:
15939 i1d3ccss = get_argyll_util("i1d3ccss")
15940 spyd4en = get_argyll_util("spyd4en")
15941 dlg = ConfirmDialog(
15942 self,
15943 title=lang.getstr("colorimeter_correction.import"),
15944 msg=msg,
15945 ok=lang.getstr("auto"),
15946 cancel=lang.getstr("cancel"),
15947 bitmap=get_icon(32, "dialog-information"),
15948 alt=lang.getstr("file.select"),
15949 )
15950 dlg.sizer3.Add((1, 8))
15951
15952 def check_importers(event: wx.Event) -> None:
15953 """Check if at least one importer is selected.
15954
15955 Args:
15956 event (wx.Event): The event that triggered this check.
15957 """
15958 result = False
15959 for name in ("i1d3", "icd", "spyd4"):
15960 if hasattr(dlg, name) and getattr(dlg, name).IsChecked():
15961 result = True
15962 break
15963 dlg.ok.Enable(result)
15964
15965 for name, desc, instruments_, importer in [
15966 (
15967 "i1d3",
15968 "i1 Profiler",
15969 ("i1 DisplayPro, ColorMunki Display", "Spyder4", "Spyder5"),
15970 i1d3ccss or oeminst,
15971 ),
15972 (
15973 "icd",
15974 "iColor Display",
15975 ("DTP94", "i1 Display 2", "Spyder2", "Spyder3"),
15976 True,
15977 ),
15978 ("spyd4", "Spyder4/5", ("Spyder4", "Spyder5"), spyd4en or oeminst),
15979 ]:
15980 if not importer:
15981 continue
15982 for instrument in instruments_:
15983 if instrument not in desc:
15984 desc += " ({})".format(", ".join(instruments_))
15985 break
15986 setattr(dlg, name, wx.CheckBox(dlg, -1, desc))
15987 for instrument in instruments_:
15988 check = self.worker.spyder4_cal_exists() if name == "spyd4" else False
15989 if instrument in self.worker.instruments and not check:
15990 getattr(dlg, name).SetValue(True)
15991 break
15992 dlg.sizer3.Add(getattr(dlg, name), flag=wx.TOP | wx.ALIGN_LEFT, border=8)
15993 getattr(dlg, name).Bind(wx.EVT_CHECKBOX, check_importers)
15994 dlg.install_user = wx.RadioButton(
15995 dlg, -1, lang.getstr("install_user"), style=wx.RB_GROUP
15996 )
15997 dlg.install_user.SetValue(True)
15998 dlg.sizer3.Add(dlg.install_user, flag=wx.TOP | wx.ALIGN_LEFT, border=16)
15999 dlg.install_systemwide = wx.RadioButton(
16000 dlg, -1, lang.getstr("install_local_system")
16001 )
16002 dlg.install_user.Bind(wx.EVT_RADIOBUTTON, install_scope_handler)
16003 dlg.install_systemwide.Bind(wx.EVT_RADIOBUTTON, install_scope_handler)
16004 install_scope_handler(dlg=dlg)
16005 check_importers(None)
16006 dlg.sizer3.Add(dlg.install_systemwide, flag=wx.TOP | wx.ALIGN_LEFT, border=4)
16007 dlg.sizer0.SetSizeHints(dlg)
16008 dlg.sizer0.Layout()
16009 if event:
16010 choice = dlg.ShowModal()
16011 elif paths:
16012 choice = wx.ID_ANY
16013 else:
16014 choice = wx.ID_OK
16015 importer_configurations = [
16016 ("i1d3", i1d3ccss or oeminst),
16017 ("spyd4", spyd4en or oeminst),
16018 ("icd", True),
16019 ]
16020 importers = {
16021 name: importer
16022 for name, importer in importer_configurations
16023 if importer and getattr(dlg, name).GetValue()
16024 }
16025 asroot = dlg.install_systemwide.GetValue()
16026 dlg.Destroy()
16027 if choice == wx.ID_CANCEL:
16028 return None
16029 if choice != wx.ID_OK and not paths:
16030 dlg = wx.FileDialog(
16031 self,
16032 lang.getstr("colorimeter_correction.import.choose"),
16033 wildcard=lang.getstr("filetype.any") + "|*",
16034 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE,
16035 )
16036 dlg.Center(wx.BOTH)
16037 choice2 = dlg.ShowModal()
16038 paths = dlg.GetPaths()
16039 dlg.Destroy()
16040 if choice2 != wx.ID_OK:
16041 return None
16042 elif not paths:
16043 paths = []
16044 if asroot:
16045 result = self.worker.authenticate(
16046 oeminst or i1d3ccss or spyd4en,
16047 lang.getstr("colorimeter_correction.import"),
16048 self,
16049 )
16050 if result not in (True, None):
16051 if isinstance(result, Exception):
16052 show_result_dialog(result, self)
16053 return None
16054 self.worker.interactive = False
16055 self.worker.start(
16056 self.import_colorimeter_corrections_consumer,
16057 self.import_colorimeter_corrections_producer,
16058 cargs=(callafter, callafter_args),
16059 wargs=(
16060 result,
16061 i1d3,
16062 i1d3ccss,
16063 spyd4,
16064 spyd4en,
16065 icd,
16066 oeminst,
16067 paths,
16068 choice == wx.ID_OK,
16069 asroot,
16070 importers,
16071 ),
16072 progress_msg=lang.getstr("colorimeter_correction.import"),
16073 fancy=False,
16074 )
16075 return (event and None) or True # This always returns True
16076
16077 def import_colorimeter_correction(
16078 self,
16079 result: bool | Exception,
16080 i1d3: bool,
16081 i1d3ccss: bool,
16082 spyd4: bool,
16083 spyd4en: bool,
16084 icd: bool,
16085 oeminst: bool,
16086 path: str | list,
16087 asroot: bool,
16088 ) -> tuple[bool | Exception, bool, bool, bool]:
16089 """Import colorimeter correction(s) from path.
16090
16091 Args:
16092 result (bool | Exception): Result of the import operation.
16093 i1d3 (bool): Whether to import i1D3 corrections.
16094 i1d3ccss (bool): Whether to import i1D3 corrections in CCSS format.
16095 spyd4 (bool): Whether to import Spyder4 corrections.
16096 spyd4en (bool): Whether to import Spyder4 corrections in
16097 spyd4cal.bin format.
16098 icd (bool): Whether to import iColor Display corrections.
16099 oeminst (bool): Whether to use OEM installer.
16100 path (str | list): Path(s) to the correction files.
16101 asroot (bool): Whether to install as root (system-wide).
16102
16103 Returns:
16104 tuple: Result of the import operation, and flags indicating whether
16105 i1D3, Spyder4, and iColor Display corrections were imported.
16106 """
16107 debug_print("import_colorimeter_correction <-")
16108 debug_print(" result:", result)
16109 debug_print(" i1d3:", i1d3)
16110 debug_print(" i1d3ccss:", i1d3ccss)
16111 debug_print(" spyd4:", spyd4)
16112 debug_print(" spyd4en:", spyd4en)
16113 debug_print(" icd:", icd)
16114 debug_print(" oeminst:", oeminst)
16115 debug_print(" path(s):", path)
16116 debug_print(" asroot:", asroot)
16117 kind = None
16118 if isinstance(path, list):
16119 kind = "xrite"
16120 elif path and os.path.exists(path):
16121 filename, ext = os.path.splitext(path)
16122 kind = "unknown"
16123 if ext.lower() == ".txt":
16124 kind = "icd"
16125 result = True
16126 else:
16127 icolordisplay = "icolordisplay" in os.path.basename(path).lower()
16128 if ext.lower() == ".dmg":
16129 if icolordisplay:
16130 kind = "icd"
16131 result = self.worker.exec_cmd(
16132 which("hdiutil"),
16133 ["attach", path],
16134 capture_output=True,
16135 skip_scripts=True,
16136 )
16137 if result and not isinstance(result, Exception):
16138 for _path in safe_glob(
16139 os.path.join(
16140 os.path.sep,
16141 "Volumes",
16142 "iColorDisplay*",
16143 "iColorDisplay*.app",
16144 "Contents",
16145 "Resources",
16146 "DeviceCorrections.txt",
16147 )
16148 ):
16149 break
16150 else:
16151 result = Error(
16152 lang.getstr("file.missing", "DeviceCorrections.txt")
16153 )
16154 elif i1d3ccss and ext.lower() == ".edr":
16155 kind = "xrite"
16156 elif ext.lower() in (".cab", ".exe"):
16157 if icolordisplay:
16158 kind = "icd"
16159 sevenzip = get_program_file("7z", "7-zip")
16160 if sevenzip:
16161 if not getcfg("dry_run"):
16162 # Extract from NSIS installer
16163 temp = self.worker.create_tempdir()
16164 if isinstance(temp, Exception):
16165 result = temp
16166 else:
16167 result = self.worker.exec_cmd(
16168 sevenzip,
16169 ["e", "-y", path, "DeviceCorrections.txt"],
16170 capture_output=True,
16171 skip_scripts=True,
16172 working_dir=temp,
16173 )
16174 if result and not isinstance(result, Exception):
16175 path = os.path.join(
16176 temp, "DeviceCorrections.txt"
16177 )
16178 else:
16179 self.worker.wrapup(False)
16180 else:
16181 result = Error(lang.getstr("file.missing", "7z" + EXE_EXT))
16182 elif i1d3ccss and (
16183 "colormunki" in os.path.basename(path).lower()
16184 or "i1profiler" in os.path.basename(path).lower()
16185 or os.path.basename(path).lower() == "i1d3"
16186 ):
16187 # Assume X-Rite installer
16188 kind = "xrite"
16189 elif spyd4en and (
16190 "spyder4" in os.path.basename(path).lower()
16191 or os.path.basename(path).lower() == "spyd4"
16192 ):
16193 # Assume Spyder4/5
16194 kind = "spyder4"
16195 if kind:
16196 if kind == "icd":
16197 if (
16198 not getcfg("dry_run")
16199 and result
16200 and not isinstance(result, Exception)
16201 ):
16202 # Assume iColorDisplay DeviceCorrections.txt
16203 ccmx_dir = config.get_argyll_data_dir()
16204 if not os.path.exists(ccmx_dir):
16205 result = check_create_dir(ccmx_dir)
16206 if isinstance(result, Exception):
16207 return result, i1d3, spyd4, icd
16208 print(lang.getstr("colorimeter_correction.import"))
16209 print(path)
16210 try:
16211 imported, skipped = ccmx.convert_devicecorrections_to_ccmx(
16212 path, ccmx_dir
16213 )
16214 if imported == 0:
16215 raise Info
16216 except ValueError as exception:
16217 result = Error(
16218 lang.getstr("file.invalid") + "\n" + str(exception)
16219 )
16220 except Info:
16221 result = False
16222 except Exception as exception:
16223 result = exception
16224 else:
16225 result = icd = True
16226 if skipped > 0:
16227 result = Warn(
16228 lang.getstr(
16229 "colorimeter_correction.import.partial_warning",
16230 ("iColor Display", skipped, imported + skipped),
16231 )
16232 )
16233 self.worker.wrapup(False)
16234 elif kind == "xrite":
16235 # Import .edr
16236 if asroot and sys.platform == "win32":
16237 ccss = self.get_argyll_data_files("l", "*.ccss", True)
16238 args = path if isinstance(path, list) else [path]
16239 result = i1d3 = self.worker.import_edr(args, asroot=asroot)
16240 if asroot and sys.platform == "win32":
16241 # Hacky but the only way to know if we were successful
16242 result = i1d3 = (
16243 self.get_argyll_data_files("l", "*.ccss", True) != ccss
16244 )
16245 elif kind == "spyder4":
16246 # Import spyd4cal.bin
16247 result = spyd4 = self.worker.import_spyd4cal([path], asroot=asroot)
16248 if asroot and sys.platform == "win32":
16249 result = spyd4 = self.get_argyll_data_files("l", "spyd4cal.bin")
16250 elif oeminst and not icolordisplay:
16251 if asroot and sys.platform == "win32":
16252 ccss = self.get_argyll_data_files("l", "*.ccss", True)
16253 result = self.worker.import_colorimeter_corrections(
16254 oeminst, [path], asroot
16255 )
16256 if ".ccss" in "".join(self.worker.output) or (
16257 asroot
16258 and sys.platform == "win32"
16259 and self.get_argyll_data_files("l", "*.ccss", True) != ccss
16260 ):
16261 i1d3 = result
16262 if "spyd4cal.bin" in "".join(self.worker.output) or (
16263 asroot
16264 and sys.platform == "win32"
16265 and self.get_argyll_data_files("l", "spyd4cal.bin")
16266 ):
16267 spyd4 = result
16268 else:
16269 result = Error(lang.getstr("error.file_type_unsupported") + "\n" + path)
16270
16271 debug_print("import_colorimeter_correction ->")
16272 debug_print(" result:", result)
16273 debug_print(" i1d3:", i1d3)
16274 debug_print(" i1d3ccss:", i1d3ccss)
16275 debug_print(" spyd4:", spyd4)
16276 debug_print(" spyd4en:", spyd4en)
16277 debug_print(" icd:", icd)
16278 debug_print(" oeminst:", oeminst)
16279 debug_print(" path(s):", path)
16280 debug_print(" asroot:", asroot)
16281 return result, i1d3, spyd4, icd
16282
16283 def import_colorimeter_corrections_producer(
16284 self,
16285 result: str,
16286 i1d3: bool,
16287 i1d3ccss: bool,
16288 spyd4: bool,
16289 spyd4en: bool,
16290 icd: bool,
16291 oeminst: str,
16292 paths: list,
16293 auto: bool,
16294 asroot: bool,
16295 importers: dict,
16296 ) -> tuple[bool | Exception, bool, bool, bool]:
16297 """Import colorimetercorrections from paths.
16298
16299 Args:
16300 result (str): Initial result message.
16301 i1d3 (bool): Whether i1D3 corrections were imported.
16302 i1d3ccss (bool): Whether i1D3 CCSS corrections were imported.
16303 spyd4 (bool): Whether Spyder4/5 corrections were imported.
16304 spyd4en (bool): Whether Spyder4/5 EN corrections were imported.
16305 icd (bool): Whether iColorDisplay corrections were imported.
16306 oeminst (str): Path to the OEMINST utility.
16307 paths (list): List of paths to import from.
16308 auto (bool): Whether this is an automatic import.
16309 asroot (bool): Whether to install corrections system-wide.
16310 importers (dict): Dictionary of importers to use.
16311
16312 Returns:
16313 tuple[bool | Exception, bool, bool, bool]: A tuple containing the
16314 result of the import operation which is either a bool or an
16315 Exception, and flags indicating whether i1D3, Spyder4, and
16316 iColor Display corrections were imported.
16317 """
16318 if auto and not paths:
16319 paths = []
16320 if importers.get("icd"):
16321 # Look for iColorDisplay
16322 if sys.platform == "win32":
16323 icdfn = safe_glob(
16324 os.path.join(
16325 getenvu("PROGRAMFILES", ""),
16326 "Quato",
16327 "iColorDisplay",
16328 "DeviceCorrections.txt",
16329 )
16330 )
16331 elif sys.platform == "darwin":
16332 icdfn = safe_glob(
16333 os.path.join(
16334 os.path.sep,
16335 "Applications",
16336 "iColorDisplay*.app",
16337 "DeviceCorrections.txt",
16338 )
16339 )
16340 if not icdfn:
16341 icdfn = safe_glob(
16342 os.path.join(
16343 os.path.sep,
16344 "Volumes",
16345 "iColorDisplay*",
16346 "iColorDisplay*.app",
16347 "DeviceCorrections.txt",
16348 )
16349 )
16350 else:
16351 icdfn = None
16352 if icdfn:
16353 paths.extend(icdfn)
16354 if importers.get("i1d3") and (oeminst or i1d3ccss) and not i1d3:
16355 # Look for *.edr files
16356 if sys.platform == "win32":
16357 i1d3fn = safe_glob(
16358 os.path.join(
16359 getenvu("PROGRAMFILES", ""),
16360 "X-Rite",
16361 "Devices",
16362 "i1d3",
16363 "Calibrations",
16364 "*.edr",
16365 )
16366 )
16367 elif sys.platform == "darwin":
16368 i1d3fn = safe_glob(
16369 os.path.join(
16370 os.path.sep,
16371 "Library",
16372 "Application Support",
16373 "X-Rite",
16374 "Devices",
16375 "i1d3xrdevice",
16376 "Contents",
16377 "Resources",
16378 "Calibrations",
16379 "*.edr",
16380 )
16381 )
16382 if not i1d3fn:
16383 i1d3fn = safe_glob(
16384 os.path.join(
16385 os.path.sep, "Volumes", "i1Profiler", "*Setup.exe"
16386 )
16387 )
16388 if not i1d3fn:
16389 i1d3fn = safe_glob(
16390 os.path.join(
16391 os.path.sep,
16392 "Volumes",
16393 "ColorMunki Display",
16394 "*Setup.exe",
16395 )
16396 )
16397 else:
16398 i1d3fn = []
16399 if len(i1d3fn) > 1:
16400 # Multiple EDR files
16401 paths.append(i1d3fn)
16402 else:
16403 paths.extend(i1d3fn)
16404 if importers.get("spyd4") and (oeminst or spyd4en) and not spyd4:
16405 # Look for dccmtr.dll
16406 if sys.platform == "win32":
16407 spydfn = safe_glob(
16408 os.path.join(
16409 getenvu("PROGRAMFILES", ""),
16410 "Datacolor",
16411 "Spyder5*",
16412 "dccmtr.dll",
16413 )
16414 )
16415 if not spydfn:
16416 spydfn = safe_glob(
16417 os.path.join(
16418 getenvu("PROGRAMFILES", ""),
16419 "Datacolor",
16420 "Spyder4*",
16421 "dccmtr.dll",
16422 )
16423 )
16424 elif sys.platform == "darwin":
16425 # Look for setup.exe on CD-ROM
16426 spydfn = safe_glob(
16427 os.path.join(
16428 os.path.sep, "Volumes", "Datacolor", "Data", "Setup.exe"
16429 )
16430 )
16431 if not spydfn:
16432 spydfn = safe_glob(
16433 os.path.join(
16434 os.path.sep,
16435 "Volumes",
16436 "Datacolor_ISO",
16437 "Data",
16438 "Setup.exe",
16439 )
16440 )
16441 else:
16442 spydfn = None
16443 if spydfn:
16444 paths.extend(spydfn)
16445 for path in paths:
16446 (result, i1d3, spyd4, icd) = self.import_colorimeter_correction(
16447 result, i1d3, i1d3ccss, spyd4, spyd4en, icd, oeminst, path, asroot
16448 )
16449 paths = []
16450 for name in importers:
16451 _importer = importers[name]
16452 imported = locals().get(name, False)
16453 if (imported and name != "i1d3") or not auto:
16454 continue
16455 # Automatic download
16456 if name == "icd" and sys.platform == "darwin":
16457 name += ".dmg"
16458 self.worker.recent.clear()
16459 self.worker.lastmsg.clear()
16460 # We always (re-)download the i1D3 package because it may contain
16461 # additional corrections not present in i1Profiler
16462 result = self.worker.download(
16463 f"https://{DOMAIN}/{name}", force=name == "i1d3"
16464 )
16465 if isinstance(result, Exception):
16466 break
16467 if result:
16468 if os.path.basename(result).lower() == "i1d3.zip":
16469 # Extract contained CCSS files
16470 result = self.worker.extract_archive(result)
16471 if isinstance(result, Exception):
16472 break
16473 result = [path for path in result if not os.path.isdir(path)]
16474 paths.append(result)
16475 else:
16476 # Cancelled
16477 result = None
16478 break
16479 if not isinstance(result, Exception) and result:
16480 for path in paths:
16481 (result, i1d3, spyd4, icd) = self.import_colorimeter_correction(
16482 result, i1d3, i1d3ccss, spyd4, spyd4en, icd, oeminst, path, asroot
16483 )
16484 return result, i1d3, spyd4, icd
16485
16486 def import_colorimeter_corrections_consumer(
16487 self,
16488 results: tuple,
16489 callafter: None | Callable = None,
16490 callafter_args: tuple = (),
16491 ) -> None:
16492 """Consumer for importing colorimeter corrections.
16493
16494 Args:
16495 results (tuple): A tuple containing the results of the import
16496 operation, which may include the result of the import,
16497 i1d3, spyd4, and icd.
16498 callafter (None | Callable, optional): A callable to be called after the
16499 import operation is complete.
16500 callafter_args (tuple, optional): Arguments to be passed to the
16501 callable specified in callafter.
16502 """
16503 print("results:", results)
16504 result, i1d3, spyd4, icd = results
16505 if isinstance(result, Exception):
16506 show_result_dialog(result, self)
16507 imported = []
16508 failures = []
16509 mapping = {
16510 "i1 Profiler/ColorMunki Display": i1d3,
16511 "Spyder4/5": spyd4,
16512 "iColor Display": icd,
16513 }
16514 for name in mapping:
16515 subresult = mapping[name]
16516 if subresult and not isinstance(subresult, Exception):
16517 imported.append(name)
16518 elif subresult is not None:
16519 failures.append(name)
16520 if imported:
16521 self.update_measurement_modes()
16522 self.update_colorimeter_correction_matrix_ctrl_items(True)
16523 InfoDialog(
16524 self,
16525 msg=lang.getstr(
16526 "colorimeter_correction.import.success", "\n".join(imported)
16527 ),
16528 ok=lang.getstr("ok"),
16529 bitmap=get_icon(32, "dialog-information"),
16530 )
16531 if failures or (not imported and result is not None):
16532 error = "".join(self.worker.errors) or lang.getstr(
16533 "colorimeter_correction.import.failure"
16534 ) + "\n\n" + "\n".join(failures)
16535 show_result_dialog(UnloggedError(error), self)
16536 if callafter:
16537 wx.CallAfter(callafter, *callafter_args)
16538
16539 def import_session_archive(self, path: str) -> None:
16540 """Import compressed session archive.
16541
16542 Args:
16543 path (str): The path to the session archive file.
16544 """
16545 filename, ext = os.path.splitext(path)
16546 basename = os.path.basename(filename) # Without extension
16547 if not self.check_overwrite(filename=basename):
16548 return
16549 self.worker.start(
16550 self.import_session_archive_consumer,
16551 self.import_session_archive_producer,
16552 cargs=(basename,),
16553 wargs=(path, basename, ext),
16554 progress_msg=lang.getstr("archive.import"),
16555 fancy=False,
16556 )
16557
16558 def import_session_archive_producer(
16559 self,
16560 path: str,
16561 basename: str,
16562 ext: str,
16563 ) -> str | Exception:
16564 """Producer for importing session archive.
16565
16566 Args:
16567 path (str): The path to the session archive file.
16568 basename (str): The base name of the session archive without
16569 extension, used for saving the profile.
16570 ext (str): The file extension of the session archive.
16571
16572 Returns:
16573 str | Exception: The path to the extracted session archive or an
16574 exception if an error occurred.
16575 """
16576 temp = self.worker.create_tempdir()
16577 if isinstance(temp, Exception):
16578 return temp
16579 if ext.lower() == ".7z":
16580 if not (sevenzip := get_program_file("7z", "7-zip")):
16581 return Error(lang.getstr("file.missing", f"7z{EXE_EXT}"))
16582 # Extract from 7z archive (flat hierarchy, not using dirnames)
16583 result = self.worker.exec_cmd(
16584 sevenzip,
16585 ["e", "-y", path],
16586 capture_output=True,
16587 log_output=False,
16588 skip_scripts=True,
16589 working_dir=temp,
16590 )
16591 if not result or isinstance(result, Exception):
16592 return result
16593 # Check if a session archive
16594 found_ext = None
16595 for ext_ in (".icc", ".icm", ".cal"):
16596 if os.path.isfile(os.path.join(temp, f"{basename}{ext_}")):
16597 found_ext = ext_
16598 break
16599 if not found_ext:
16600 # Doesn't seem to be a session archive
16601 return Error(
16602 lang.getstr("error.not_a_session_archive", os.path.basename(path))
16603 )
16604 if os.path.isdir(os.path.join(temp, basename)):
16605 # Remove empty directory
16606 shutil.rmtree(os.path.join(temp, basename))
16607
16608 else:
16609 if path.lower().endswith(".tgz") or path.lower().endswith(".tar.gz"):
16610 # Gzipped TAR archive
16611 archive = TarFileProper.open(path, "r", encoding="UTF-8")
16612 getinfo = archive.getmember
16613 getnames = archive.getnames
16614 else:
16615 # ZIP
16616 archive = zipfile.ZipFile(path, "r")
16617 getinfo = archive.getinfo
16618 getnames = archive.namelist
16619 try:
16620 with archive:
16621 # Check if a session archive
16622 info = None
16623 for ext_ in (".icc", ".icm", ".cal"):
16624 for name in (
16625 f"{basename}/{basename}{ext_}",
16626 f"{basename}{ext_}",
16627 ):
16628 if isinstance(archive, zipfile.ZipFile):
16629 # If the ZIP file was created with Unicode
16630 # names stored in the file, 'name' will already
16631 # be Unicode. Otherwise, it'll either be 7-bit
16632 # ASCII or (legacy) cp437 encoding
16633 names = (name, safe_str(name, "cp437"))
16634 else:
16635 # Gzipped TAR archive, assume UTF-8
16636 names = (safe_str(name, "UTF-8"),)
16637 for name in names:
16638 try:
16639 info = getinfo(name)
16640 except KeyError:
16641 continue
16642 break
16643 if info:
16644 break
16645 if info:
16646 break
16647 if not info:
16648 # Doesn't seem to be a session archive
16649 return Error(
16650 lang.getstr(
16651 "error.not_a_session_archive", os.path.basename(path)
16652 )
16653 )
16654 found_ext = ext_
16655 # Extract from archive (flat hierarchy, not using dirnames)
16656 for name in getnames():
16657 if not isinstance(archive, zipfile.ZipFile):
16658 # Gzipped TAR
16659 archive.extract(name, temp, False)
16660 continue
16661 # If the ZIP file was created with Unicode names stored
16662 # in the file, 'name' will already be Unicode.
16663 # Otherwise, it'll either be 7-bit ASCII or (legacy)
16664 # cp437 encoding
16665 outname = str(name)
16666 with open(
16667 os.path.join(temp, os.path.basename(outname)), "wb"
16668 ) as outfile:
16669 outfile.write(archive.read(name))
16670 except Exception as exception:
16671 print(traceback.format_exc())
16672 return exception
16673 # NOTE: use the extracted file's own extension (.cal/.icc/.icm), not
16674 # the archive's (.7z/.tgz/.zip) -- the latter was a latent bug: the
16675 # returned path would point at a nonexistent "<basename>.zip" inside
16676 # the storage folder (the extracted+moved file is really
16677 # "<basename>.cal"/etc.), so ``load_cal_handler`` silently treated the
16678 # import as if the calibration had gone missing.
16679 return os.path.join(
16680 getcfg("profile.save_path"), basename, basename + found_ext
16681 )
16682
16683 def import_session_archive_consumer(
16684 self, result: str | Exception, basename: str
16685 ) -> None:
16686 """Consumer for importing session archive.
16687
16688 Args:
16689 result (str | Exception): The result of the import operation,
16690 which can be a file path or an exception.
16691 basename (str): The base name of the session archive without
16692 extension, used for saving the profile.
16693 """
16694 if result and not isinstance(result, Exception):
16695 # Copy to storage folder
16696 self.worker.wrapup(
16697 dst_path=os.path.join(
16698 getcfg("profile.save_path"), basename, basename + ".ext"
16699 )
16700 )
16701 # Load settings from profile
16702 self.load_cal_handler(None, result)
16703 else:
16704 show_result_dialog(result)
16705 self.worker.wrapup(False)
16706
16707 def display_ctrl_handler(
16708 self,
16709 event: wx.Event,
16710 load_lut: bool = True,
16711 update_ccmx_items: bool = True,
16712 ) -> None:
16713 """Handle display control events.
16714
16715 Args:
16716 event (wx.Event): The event triggered by the control.
16717 load_lut (bool, optional): Whether to load the LUT after changing
16718 the display.
16719 update_ccmx_items (bool, optional): Whether to update colorimeter
16720 correction matrix items.
16721 """
16722 debug_print(
16723 "[D] display_ctrl_handler called for ID "
16724 f"{event.GetId()} {getevtobjname(event, self)} event type "
16725 f"{event.GetEventType()} {getevttype(event)}"
16726 )
16727 display_no = self.display_ctrl.GetSelection()
16728 profile = None
16729 if display_no > -1:
16730 setcfg("display.number", display_no + 1)
16731 if load_lut:
16732 profile = get_display_profile(display_no)
16733 if not getcfg("calibration.file", False):
16734 # Current
16735 self.profile_info_btn.Enable(bool(profile))
16736 if self.display_lut_link_ctrl.IsShown():
16737 self.display_lut_link_ctrl_handler(
16738 CustomEvent(wx.EVT_BUTTON.evtType[0], self.display_lut_link_ctrl),
16739 bool(int(getcfg("display_lut.link"))),
16740 )
16741 if load_lut:
16742 debug_print(
16743 "[D] display_ctrl_handler -> lut_viewer_load_lut",
16744 profile.getDescription() if profile else None,
16745 )
16746 self.lut_viewer_load_lut(profile=profile)
16747 debug_print("[D] display_ctrl_handler -> lut_viewer_load_lut END")
16748 self.update_use_video_lut()
16749 # Enable 3D LUT tab for virtual displays & eeColor
16750 enable_3dlut_tab = (
16751 config.is_virtual_display() or config.get_display_name() == "SII REPEATER"
16752 )
16753 setcfg_cond(
16754 enable_3dlut_tab, "3dlut.tab.enable", 1, True, not getcfg("3dlut.create")
16755 )
16756 self.update_drift_compensation_ctrls()
16757 self.show_display_delay_ctrls()
16758 self.show_ffp_ctrls()
16759 self.show_output_levels_ctrls()
16760 self.update_output_levels_ctrl()
16761 # Check if display is calibratable at all. Unset calibration update
16762 # checkbox if this is not the case.
16763 if config.is_uncalibratable_display():
16764 setcfg("calibration.update", False)
16765 self.calibration_update_cb.SetValue(False)
16766 if self.IsShownOnScreen():
16767 self.update_menus()
16768 if (
16769 update_ccmx_items
16770 and getcfg("colorimeter_correction_matrix_file").split(":")[0] == "AUTO"
16771 ):
16772 self.update_colorimeter_correction_matrix_ctrl_items()
16773 else:
16774 self.update_estimated_measurement_times()
16775 self.update_main_controls()
16776 if getattr(self, "reportframe", None):
16777 self.reportframe.update_controls()
16778 if getattr(self, "lut3dframe", None):
16779 self.lut3dframe.update_controls()
16780 # if (event and not isinstance(event, CustomEvent) and
16781 # not getcfg("calibration.file", False)):
16782 # # Set measurement report dest profile to current
16783 # setcfg("measurement_report.output_profile",
16784 # get_current_profile_path())
16785 if isinstance(event, CustomEvent):
16786 return
16787 if config.get_display_name().startswith("Chromecast "):
16788 # Show a warning re Chromecast limitation
16789 show_result_dialog(
16790 UnloggedWarning(lang.getstr("chromecast_limitations_warning")),
16791 parent=self,
16792 )
16793 if (
16794 config.get_display_name() == "Untethered"
16795 and getcfg("testchart.file") == "auto"
16796 ):
16797 # Untethered does not support auto-optimization
16798 self.set_testchart()
16799
16800 def update_output_levels_ctrl(self) -> None:
16801 """Update output levels controls based on configuration."""
16802 if getcfg("patterngenerator.detect_video_levels"):
16803 self.output_levels_auto.SetValue(True)
16804 else:
16805 use_video_levels = bool(getcfg("patterngenerator.use_video_levels"))
16806 self.output_levels_full_range.SetValue(not use_video_levels)
16807 self.output_levels_limited_range.SetValue(use_video_levels)
16808
16809 def display_delay_handler(self, event: wx.Event) -> None:
16810 """Handle display delay control events.
16811
16812 Args:
16813 event (wx.Event): The event triggered by the control.
16814 """
16815 mapping = {
16816 self.override_min_display_update_delay_ms.GetId(): (
16817 "measure.override_min_display_update_delay_ms"
16818 ),
16819 self.min_display_update_delay_ms.GetId(): (
16820 "measure.min_display_update_delay_ms"
16821 ),
16822 self.override_display_settle_time_mult.GetId(): (
16823 "measure.override_display_settle_time_mult"
16824 ),
16825 self.display_settle_time_mult.GetId(): "measure.display_settle_time_mult",
16826 }
16827 pref = mapping.get(event.GetId())
16828 if pref:
16829 ctrl = self.FindWindowById(event.GetId())
16830 value = ctrl.GetValue()
16831 if ctrl.Name.startswith("override_"):
16832 self.update_display_delay_ctrl(ctrl.Name[9:], value)
16833 value = int(value)
16834 setcfg(pref, value)
16835 self.update_estimated_measurement_times()
16836
16837 def update_display_delay_ctrl(self, name: str, enable: bool) -> None:
16838 """Update display delay control state and value.
16839
16840 Args:
16841 name (str): The name of the control to update.
16842 enable (bool): Whether to enable or disable the control.
16843 """
16844 spinctrl = getattr(self, name)
16845 spinctrl.Enable(enable)
16846 if name == "min_display_update_delay_ms":
16847 self.min_display_update_delay_ms_label.Enable(enable)
16848 spinvalue = getcfg(f"measure.{name}")
16849 if not enable:
16850 # Restore previous environment variable value
16851 backup = os.getenv(f"ARGYLL_{name.upper()}_BACKUP")
16852 current = os.getenv(f"ARGYLL_{name.upper()}")
16853 if backup or current:
16854 valuetype = type(DEFAULTS[f"measure.{name}"])
16855 with contextlib.suppress(TypeError, ValueError):
16856 spinvalue = valuetype(backup or current)
16857 spinctrl.SetValue(spinvalue)
16858
16859 def display_lut_ctrl_handler(self, event: wx.Event) -> None:
16860 """Handle display LUT selection changes.
16861
16862 Args:
16863 event (wx.Event): The event triggered by the control.
16864 """
16865 debug_print(
16866 "[D] display_lut_ctrl_handler called for ID "
16867 f"{event.GetId()} {getevtobjname(event, self)} event type "
16868 f"{event.GetEventType()} {getevttype(event)}"
16869 )
16870 try:
16871 i = self.displays.index(self.display_lut_ctrl.GetStringSelection())
16872 except ValueError:
16873 i = min(0, self.display_ctrl.GetSelection())
16874 setcfg("display_lut.number", i + 1)
16875
16876 def display_lut_link_ctrl_handler(
16877 self, event: wx.Event, link: None | bool = None
16878 ) -> None:
16879 """Handle the display LUT link control event.
16880
16881 Args:
16882 event (wx.Event): The event triggered by the control.
16883 link (bool, optional): The current link state. If None, it will
16884 be determined from the configuration.
16885 """
16886 debug_print(
16887 "[D] display_lut_link_ctrl_handler called for ID "
16888 f"{event.GetId()} {getevtobjname(event, self)} event type "
16889 f"{event.GetEventType()} {getevttype(event)}"
16890 )
16891 bitmap_link = get_icon(16, "stock_lock")
16892 bitmap_unlink = get_icon(16, "stock_lock-open")
16893 if link is None:
16894 link = not bool(int(getcfg("display_lut.link")))
16895 link = not len(self.worker.displays) or (
16896 link
16897 and self.worker.lut_access[
16898 max(min(len(self.worker.displays), getcfg("display.number")), 0) - 1
16899 ]
16900 )
16901 lut_no = -1
16902 if link:
16903 self.display_lut_link_ctrl.SetBitmapLabel(bitmap_link)
16904 with contextlib.suppress(ValueError):
16905 lut_no = self.display_lut_ctrl.Items.index(
16906 self.display_ctrl.GetStringSelection()
16907 )
16908 else:
16909 self.display_lut_link_ctrl.SetBitmapLabel(bitmap_unlink)
16910 set_bitmap_labels(self.display_lut_link_ctrl)
16911 if lut_no < 0:
16912 try:
16913 lut_no = self.display_lut_ctrl.Items.index(
16914 self.display_ctrl.Items[getcfg("display_lut.number") - 1]
16915 )
16916 except (IndexError, ValueError):
16917 lut_no = min(0, self.display_ctrl.GetSelection())
16918 self.display_lut_ctrl.SetSelection(lut_no)
16919 self.display_lut_ctrl.Enable(not link and self.display_lut_ctrl.GetCount() > 0)
16920 setcfg("display_lut.link", int(link))
16921 try:
16922 i = self.displays.index(self.display_lut_ctrl.Items[lut_no])
16923 except (IndexError, ValueError):
16924 i = min(0, self.display_ctrl.GetSelection())
16925 setcfg("display_lut.number", i + 1)
16926
16927 def display_tech_info_show_handler(self, event: wx.Event) -> None:
16928 """Show display technology information tooltip window.
16929
16930 Args:
16931 event (wx.Event): The event triggered by the control.
16932 """
16933 if hasattr(self, "display_tech_info_tooltip_window"):
16934 # Hmm. Somehow initial scroll position isn't at (0, 0)
16935 wx.CallAfter(self.display_tech_info_tooltip_window.panel.Scroll, 0, 0)
16936 self.display_tech_info_tooltip_window.Show()
16937 self.display_tech_info_tooltip_window.Raise()
16938 return
16939
16940 # Create tooltip window with display technology information
16941 id_str = "info.display_tech"
16942 lcode = lang.getcode()
16943 if lcode in ("ko", "zh_cn", "zh_hk") and lang.LDICT.get(lcode, {}).get(id_str):
16944 wrap = 66
16945 else:
16946 wrap = 112
16947 self.display_tech_info_tooltip_window = TooltipWindow(
16948 self,
16949 msg=lang.getstr(id_str),
16950 cols=1,
16951 title=lang.getstr("display.tech"),
16952 bitmap=get_icon(32, "dialog-information"),
16953 wrap=wrap,
16954 use_header=False,
16955 show=False,
16956 scrolled=True,
16957 )
16958 w = self.display_tech_info_tooltip_window
16959 w.sizer0.Add((0, 2))
16960 # link1 = HyperLinkCtrl(w.panel, -1,
16961 # label=lang.getstr(
16962 # "info.display_tech.linklabel.displayspecifications.com"
16963 # ),
16964 # URL="https://www.displayspecifications.com/")
16965 # link1.BackgroundColour = w.panel.BackgroundColour
16966 link1 = PlateButton(
16967 w.panel,
16968 -1,
16969 lang.getstr("info.display_tech.linklabel.displayspecifications.com"),
16970 get_icon(16, "web"),
16971 )
16972 link1.SetMaxFontSize(11)
16973 set_platebutton_bitmaps(link1, "web")
16974 if sys.platform == "darwin":
16975 # Prevent initial highlited state
16976 link1.Unbind(wx.EVT_SET_FOCUS)
16977 link1.Bind(
16978 wx.EVT_BUTTON,
16979 lambda e: webbrowser_open("https://www.displayspecifications.com/"),
16980 )
16981 w.sizer0.Add(link1, flag=wx.LEFT, border=12 + 32 + 7)
16982 w.sizer0.Add((0, 9))
16983 # link2 = HyperLinkCtrl(w.panel, -1,
16984 # label=lang.getstr("info.display_tech.linklabel.everymac.com"),
16985 # URL="https://everymac.com/")
16986 # link2.BackgroundColour = w.panel.BackgroundColour
16987 link2 = PlateButton(
16988 w.panel,
16989 -1,
16990 lang.getstr("info.display_tech.linklabel.everymac.com"),
16991 get_icon(16, "web"),
16992 )
16993 link2.SetMaxFontSize(11)
16994 set_platebutton_bitmaps(link2, "web")
16995 if sys.platform == "darwin":
16996 # Prevent initial highlited state
16997 link2.Unbind(wx.EVT_SET_FOCUS)
16998 link2.Bind(wx.EVT_BUTTON, lambda e: webbrowser_open("https://everymac.com/"))
16999 w.sizer0.Add(link2, flag=wx.LEFT, border=12 + 32 + 7)
17000 w.sizer0.Add((0, 12))
17001 w.sizer0.SetSizeHints(w)
17002 sw = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
17003 w.Size = w.MinSize = w.MinSize[0] + sw, w.MinSize[1]
17004 w.sizer0.Layout()
17005 # Hmm. Somehow initial scroll position isn't at (0, 0)
17006 wx.CallAfter(self.display_tech_info_tooltip_window.panel.Scroll, 0, 0)
17007 self.display_tech_info_tooltip_window.Show()
17008 self.display_tech_info_tooltip_window.Raise()
17009
17010 def measurement_mode_ctrl_handler(self, event: wx.Event = None) -> None:
17011 """Handle changes to the measurement mode control.
17012
17013 Args:
17014 event (wx.Event, optional): The event triggered by the control.
17015 """
17016 if event is not None:
17017 debug_print(
17018 "[D] measurement_mode_ctrl_handler called for ID "
17019 f"{event.GetId()} {getevtobjname(event, self)} event type "
17020 f"{event.GetEventType()} {getevttype(event)}"
17021 )
17022 v = self.get_measurement_mode()
17023 if v and "p" in v and self.worker.argyll_version < [1, 1, 0]:
17024 self.measurement_mode_ctrl.SetSelection(
17025 self.measurement_modes_ba[self.get_instrument_type()].get(
17026 DEFAULTS["measurement_mode"], 1
17027 )
17028 )
17029 v = None
17030 InfoDialog(
17031 self,
17032 msg=lang.getstr("projector_mode_unavailable"),
17033 ok=lang.getstr("ok"),
17034 bitmap=get_icon(32, "dialog-information"),
17035 )
17036 if (v and "V" in v and self.worker.argyll_version < [1, 1, 0]) or (
17037 self.worker.argyll_version[0:3] == [1, 1, 0]
17038 and (
17039 "Beta" in self.worker.argyll_version_string
17040 or "RC1" in self.worker.argyll_version_string
17041 or "RC2" in self.worker.argyll_version_string
17042 )
17043 ):
17044 # adaptive emissive mode was added in RC3
17045 self.measurement_mode_ctrl.SetSelection(
17046 self.measurement_modes_ba[self.get_instrument_type()].get(
17047 DEFAULTS["measurement_mode"], 1
17048 )
17049 )
17050 v = None
17051 InfoDialog(
17052 self,
17053 msg=lang.getstr("adaptive_mode_unavailable"),
17054 ok=lang.getstr("ok"),
17055 bitmap=get_icon(32, "dialog-information"),
17056 )
17057 cal_changed = (
17058 v != getcfg("measurement_mode")
17059 and getcfg("calibration.file", False) not in self.presets[1:]
17060 )
17061 setcfg(
17062 "measurement_mode", (strtr(v, {"V": "", "H": ""}) if v else None) or None
17063 )
17064 instrument_features = self.worker.get_instrument_features()
17065 if instrument_features.get("adaptive_mode"):
17066 setcfg("measurement_mode.adaptive", 1 if v and "V" in v else 0)
17067 if instrument_features.get("highres_mode"):
17068 setcfg("measurement_mode.highres", 1 if v and "H" in v else 0)
17069 if (
17070 v
17071 and self.worker.get_instrument_name() in ("ColorHug", "ColorHug2")
17072 and "p" in v
17073 ):
17074 # ColorHug projector mode is just a correction matrix
17075 # Avoid setting ColorMunki projector mode
17076 v = v.replace("p", "")
17077 # ColorMunki projector mode is an actual special sensor dial position
17078 setcfg("measurement_mode.projector", 1 if v and "p" in v else None)
17079 self.update_colorimeter_correction_matrix_ctrl()
17080 self.update_colorimeter_correction_matrix_ctrl_items(
17081 update_measurement_mode=False
17082 )
17083 if (
17084 v
17085 and self.get_trc()
17086 and ("c" not in v or "p" in v)
17087 and float(self.get_black_point_correction()) > 0
17088 and getcfg("calibration.black_point_correction_choice.show")
17089 and not getcfg("calibration.black_point_correction.auto")
17090 ):
17091 ok = lang.getstr("turn_on") if "c" in v else lang.getstr("turn_off")
17092 title = "calibration.black_point_correction"
17093 msg = "calibration.black_point_correction_choice"
17094 cancel = "setting.keep_current"
17095 dlg = ConfirmDialog(
17096 self,
17097 title=lang.getstr(title),
17098 msg=lang.getstr(msg),
17099 ok=ok,
17100 cancel=lang.getstr(cancel),
17101 bitmap=get_icon(32, "dialog-question"),
17102 )
17103 chk = wx.CheckBox(dlg, -1, lang.getstr("dialog.do_not_show_again"))
17104 dlg.Bind(
17105 wx.EVT_CHECKBOX,
17106 self.black_point_correction_choice_dialog_handler,
17107 id=chk.GetId(),
17108 )
17109 dlg.sizer3.Add(chk, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
17110 dlg.sizer0.SetSizeHints(dlg)
17111 dlg.sizer0.Layout()
17112 result = dlg.ShowModal()
17113 dlg.Destroy()
17114 if result == wx.ID_OK:
17115 bkpt_corr = 1.0 if "c" in v else 0.0
17116 if not cal_changed and bkpt_corr != getcfg(
17117 "calibration.black_point_correction"
17118 ):
17119 self.cal_changed()
17120 setcfg("calibration.black_point_correction", bkpt_corr)
17121 self.update_controls(update_profile_name=False)
17122 self.update_profile_name()
17123 if v == "auto":
17124 wx.CallAfter(
17125 show_result_dialog,
17126 UnloggedInfo(lang.getstr("display.reset.info")),
17127 self,
17128 )
17129
17130 def black_point_correction_choice_dialog_handler(self, event: wx.Event) -> None:
17131 """Handle the checkbox in the black point correction choice dialog.
17132
17133 Args:
17134 event (wx.Event): The event triggered by the checkbox.
17135 """
17136 setcfg(
17137 "calibration.black_point_correction_choice.show",
17138 int(not event.GetEventObject().GetValue()),
17139 )
17140
17141 def profile_type_ctrl_handler(self, event: wx.Event) -> None:
17142 """Handle changes to the profile type control.
17143
17144 Args:
17145 event (wx.Event): The event triggered by the control.
17146 """
17147 if DEBUG and event:
17148 print(
17149 "[D] profile_type_ctrl_handler called for ID "
17150 f"{event.GetId()} {getevtobjname(event, self)} event type "
17151 f"{event.GetEventType()} {getevttype(event)}"
17152 )
17153 v = self.get_profile_type()
17154 lut_type = v in ("l", "x", "X")
17155 self.gamap_btn.Enable(lut_type)
17156
17157 proftype_changed = False
17158 if v in ("l", "x", "X"):
17159 # XYZ LUT type
17160 if getcfg("profile.type") not in ("l", "x", "X"):
17161 # Disable black point compensation for LUT profiles
17162 setcfg("profile.black_point_compensation", 0)
17163 proftype_changed = True
17164 elif v in ("s", "S"):
17165 # Shaper + matrix type
17166 if getcfg("profile.type") not in ("s", "S"):
17167 # Enable black point compensation for shaper profiles
17168 setcfg("profile.black_point_compensation", 1)
17169 else:
17170 setcfg("profile.black_point_compensation", 0)
17171 if v in ("s", "S", "g", "G") and getcfg("profile.type") not in (
17172 "s",
17173 "S",
17174 "g",
17175 "G",
17176 ):
17177 proftype_changed = True
17178 self.update_bpc()
17179 self.profile_quality_ctrl.Enable(v not in ("g", "G"))
17180 if v in ("g", "G"):
17181 self.profile_quality_ctrl.SetValue(3)
17182 self.profile_quality_info.SetLabel(lang.getstr("calibration.quality.high"))
17183 if v != getcfg("profile.type"):
17184 self.profile_settings_changed()
17185 setcfg("profile.type", v)
17186 if hasattr(self, "gamapframe"):
17187 self.gamapframe.update_controls()
17188 self.set_default_testchart(force=proftype_changed)
17189 self.update_profile_name()
17190 if event:
17191 self.check_testchart_patches_amount()
17192
17193 def check_testchart_patches_amount(self) -> None:
17194 """Check if the selected testchart has at least the recommended amount of patches.
17195
17196 Give user the choice to use the recommended amount if patch count is lower.
17197 """ # noqa: E501
17198 recommended = {
17199 "G": 6,
17200 "g": 6,
17201 "l": 125,
17202 "lh": 125,
17203 "S": 12,
17204 "s": 12,
17205 "X": 73,
17206 "Xh": 73,
17207 "x": 73,
17208 "xh": 73,
17209 }
17210 # lower quality actually needs *higher* patchcount while high quality
17211 # can get away with fewer patches and still improved result
17212 recommended = recommended.get(
17213 self.get_profile_type() + self.get_profile_quality(),
17214 recommended[self.get_profile_type()],
17215 )
17216 patches = int(self.testchart_patches_amount.GetLabel())
17217 if recommended <= patches or is_ccxx_testchart():
17218 return
17219
17220 self.profile_quality_ctrl.Disable()
17221 dlg = ConfirmDialog(
17222 self,
17223 msg=lang.getstr("profile.testchart_recommendation"),
17224 ok=lang.getstr("OK"),
17225 cancel=lang.getstr("cancel"),
17226 bitmap=get_icon(32, "dialog-question"),
17227 )
17228 result = dlg.ShowModal()
17229 self.profile_quality_ctrl.Enable(
17230 not getcfg("profile.update") and self.get_profile_type() not in ("g", "G")
17231 )
17232 dlg.Destroy()
17233 if result != wx.ID_OK:
17234 return
17235 setcfg(
17236 "testchart.auto_optimize",
17237 max(
17238 config.VALID_VALUES["testchart.auto_optimize"][1],
17239 round(colormath.cbrt(recommended)),
17240 ),
17241 )
17242 self.set_testchart("auto")
17243
17244 def measurement_file_check_auto_handler(self, event: wx.Event) -> None:
17245 """Handle the automatic measurement file check menu item.
17246
17247 Args:
17248 event (wx.Event): The event triggered by the menu item.
17249 """
17250 if not getcfg("ti3.check_sanity.auto"):
17251 dlg = ConfirmDialog(
17252 self,
17253 msg=lang.getstr("measurement_file.check_sanity.auto.warning"),
17254 ok=lang.getstr("ok"),
17255 cancel=lang.getstr("cancel"),
17256 bitmap=get_icon(32, "dialog-warning"),
17257 log=False,
17258 )
17259 result = dlg.ShowModal()
17260 dlg.Destroy()
17261 if result != wx.ID_OK:
17262 self.menuitem_measurement_file_check_auto.Check(False)
17263 return
17264 setcfg(
17265 "ti3.check_sanity.auto",
17266 int(self.menuitem_measurement_file_check_auto.IsChecked()),
17267 )
17268
17269 def measurement_file_check_handler(self, event: wx.Event) -> None:
17270 """Handle the measurement file check menu item.
17271
17272 Args:
17273 event (wx.Event): The event triggered by the menu item.
17274 """
17275 # select measurement data (ti3 or profile)
17276 path = None
17277 default_dir, default_file = get_verified_path("last_ti3_path")
17278 dlg = wx.FileDialog(
17279 self,
17280 lang.getstr("measurement_file.choose"),
17281 defaultDir=default_dir,
17282 defaultFile=default_file,
17283 wildcard=lang.getstr("filetype.icc_ti3") + "|*.icc;*.icm;*.ti3",
17284 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
17285 )
17286 dlg.Center(wx.BOTH)
17287 result = dlg.ShowModal()
17288 if result == wx.ID_OK:
17289 path = dlg.GetPath()
17290 dlg.Destroy()
17291 if not path:
17292 return
17293 if not os.path.exists(path):
17294 show_result_dialog(Error(lang.getstr("file.missing", path)), self)
17295 return
17296 # Get filename and extension of file
17297 filename, ext = os.path.splitext(path)
17298 if ext.lower() != ".ti3":
17299 try:
17300 profile = ICCProfile(path)
17301 except (OSError, ICCProfileInvalidError):
17302 show_result_dialog(
17303 Error(lang.getstr("profile.invalid") + "\n" + path), self
17304 )
17305 return
17306 if (profile.tags.get("CIED", b"") or profile.tags.get("targ", b""))[
17307 0:4
17308 ] != b"CTI3":
17309 show_result_dialog(
17310 Error(lang.getstr("profile.no_embedded_ti3") + "\n" + path),
17311 self,
17312 )
17313 return
17314 ti3 = BytesIO(
17315 profile.tags.get("CIED", b"") or profile.tags.get("targ", b"")
17316 )
17317 else:
17318 profile = None
17319 try:
17320 ti3 = open(path, "rb") # noqa: SIM115
17321 except Exception:
17322 show_result_dialog(Error(lang.getstr("error.file.open", path)), self)
17323 return
17324 setcfg("last_ti3_path", path)
17325 ti3 = CGATS(ti3)
17326 if not self.measurement_file_check_confirm(ti3, True):
17327 return
17328 if not ti3.modified:
17329 show_result_dialog(UnloggedInfo(lang.getstr("errors.none_found")), self)
17330 return
17331
17332 if profile:
17333 # Regenerate the profile?
17334 dlg = ConfirmDialog(
17335 self,
17336 msg=lang.getstr("profile.confirm_regeneration"),
17337 ok=lang.getstr("ok"),
17338 cancel=lang.getstr("cancel"),
17339 bitmap=get_icon(32, "dialog-information"),
17340 )
17341 dlg.Center()
17342 result = dlg.ShowModal()
17343 if result == wx.ID_OK:
17344 self.worker.wrapup(False)
17345 tmp_working_dir = self.worker.create_tempdir()
17346 if isinstance(tmp_working_dir, Exception):
17347 show_result_dialog(tmp_working_dir, self)
17348 return
17349 profile.tags.targ = TextType(
17350 b"text\0\0\0\0" + bytes(ti3) + b"\0", b"targ"
17351 )
17352 profile.tags.DevD = profile.tags.CIED = profile.tags.targ
17353 tmp_path = os.path.join(tmp_working_dir, os.path.basename(path))
17354 profile.write(tmp_path)
17355 self.create_profile_handler(None, tmp_path, True)
17356 return
17357
17358 # No profile, just save the TI3
17359 dlg = wx.FileDialog(
17360 self,
17361 lang.getstr("save_as"),
17362 os.path.dirname(path),
17363 os.path.basename(path),
17364 wildcard=lang.getstr("filetype.ti3") + "|*.ti3",
17365 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
17366 )
17367 dlg.Center(wx.BOTH)
17368 result = dlg.ShowModal()
17369 path = dlg.GetPath()
17370 dlg.Destroy()
17371 if result != wx.ID_OK:
17372 return
17373 if not waccess(path, os.W_OK):
17374 show_result_dialog(
17375 Error(lang.getstr("error.access_denied.write", path)),
17376 self,
17377 )
17378 return
17379 try:
17380 ti3.write(path)
17381 except OSError as exception:
17382 show_result_dialog(exception, self)
17383
17384 def measurement_file_check_confirm(
17385 self,
17386 ti3: None | CGATS = None,
17387 force: bool = False,
17388 parent: None | wx.Window = None,
17389 ) -> bool | tuple[CGATS, list[int]]:
17390 """Check the sanity of a measurement file (TI3).
17391
17392 Args:
17393 ti3 (None | CGATS, optional): The CGATS object representing the TI3
17394 file.
17395 force (bool, optional): If True, skip the sanity check dialog.
17396 Defaults to False.
17397 parent (None | wx.Window, optional): The parent window for the
17398 dialog. Defaults to None.
17399
17400 Returns:
17401 bool: True if the TI3 file is valid or if the user confirms the
17402 changes, False if the user cancels the dialog. A tuple of
17403 (CGATS, list[int]) is returned if the TI3 file was modified
17404 and saved successfully.
17405 """
17406 if not getcfg("ti3.check_sanity.auto") and not force:
17407 return True
17408 if not ti3:
17409 profile_save_path = self.worker.tempdir
17410 if profile_save_path and os.path.isdir(profile_save_path):
17411 profile_name = getcfg("profile.name.expanded")
17412 ti3 = os.path.join(
17413 profile_save_path,
17414 f"{make_argyll_compatible_path(profile_name, is_name=True)}.ti3",
17415 )
17416 if not os.path.isfile(ti3):
17417 ti3 = None
17418 if not ti3:
17419 # Let the caller handle missing files
17420 return True
17421 try:
17422 if not isinstance(ti3, CGATS):
17423 ti3 = CGATS(ti3)
17424 ti3_1 = verify_ti1_rgb_xyz(ti3)
17425 except (OSError, CGATSError) as exception:
17426 show_result_dialog(exception, self)
17427 return False
17428 suspicious = check_ti3(ti3_1)
17429 if not suspicious:
17430 return True
17431 self.Show(start_timers=False)
17432 dlg = MeasurementFileCheckSanityDialog(parent or self, ti3_1, suspicious, force)
17433 result = dlg.ShowModal()
17434 if result == wx.ID_OK:
17435 indexes = []
17436 for index in range(dlg.grid.GetNumberRows()):
17437 if dlg.grid.GetCellValue(index, 0) == "":
17438 indexes.insert(0, index)
17439 data = ti3_1.queryv1("DATA")
17440 removed = []
17441 for index in indexes:
17442 removed.insert(0, data.pop(dlg.suspicious_items[index]))
17443 for item in removed:
17444 print(f"Removed patch #{item.key:.0f} from TI3: {item}")
17445 for index in dlg.mods:
17446 fields = dlg.mods[index]
17447 if index not in indexes:
17448 item = dlg.suspicious_items[index]
17449 for field in fields:
17450 value = fields[field]
17451 old = item[field]
17452 if old != value:
17453 item[field] = value
17454 print(
17455 f"Updated patch #{item.SAMPLE_ID} in TI3: "
17456 f"{field} {old:.4f} \u2192 {value:.4f}"
17457 )
17458 dlg.Destroy()
17459 if result == wx.ID_CANCEL:
17460 return False
17461 if result == wx.ID_OK and ti3.modified:
17462 if ti3.filename and os.path.exists(ti3.filename) and not force:
17463 try:
17464 ti3.write()
17465 except OSError as exception:
17466 show_result_dialog(exception, self)
17467 return False
17468 print("Written updated TI3 to", ti3.filename)
17469 return removed, ti3
17470 return True
17471
17472 def profile_name_ctrl_handler(self, event: wx.Event) -> None:
17473 """Handle changes to the profile name text control.
17474
17475 Args:
17476 event (wx.Event): The event that triggered this handler.
17477 """
17478 debug_print(
17479 "[D] profile_name_ctrl_handler called for ID "
17480 f"{event.GetId()} {getevtobjname(event, self)} event type "
17481 f"{event.GetEventType()} {getevttype(event)}"
17482 )
17483 oldval = self.profile_name_textctrl.GetValue()
17484 if not self.check_profile_name() or len(oldval) > 80:
17485 wx.Bell()
17486 x = self.profile_name_textctrl.GetInsertionPoint()
17487 if oldval == "":
17488 newval = DEFAULTS.get("profile.name", "")
17489 else:
17490 newval = re.sub(r"[\\/:;*?\"<>|]+", "", oldval).lstrip("-")[:80]
17491 # Windows silently strips any combination of trailing spaces and dots
17492 newval = newval.rstrip(" .")
17493 self.profile_name_textctrl.ChangeValue(newval)
17494 self.profile_name_textctrl.SetInsertionPoint(
17495 x - (len(oldval) - len(newval))
17496 )
17497 self.update_profile_name()
17498
17499 def create_profile_name_btn_handler(self, event: wx.Event) -> None:
17500 """Create profile name from display and measurement settings.
17501
17502 Args:
17503 event (wx.Event): The event that triggered this handler.
17504 """
17505 self.update_profile_name()
17506
17507 def create_session_archive_handler(self, event: wx.Event) -> None:
17508 """Create 7z or ZIP archive of the currently selected profile folder.
17509
17510 Args:
17511 event (wx.Event): The event that triggered this handler.
17512 """
17513 filename = getcfg("calibration.file", False)
17514 if not filename:
17515 return
17516 path_name, ext = os.path.splitext(filename)
17517 # Check for 7-Zip
17518 sevenzip = get_program_file("7z", "7-zip")
17519 file_format = "7z" if sevenzip else "zip"
17520 wildcard = "{}|*.{}".format(lang.getstr(f"filetype.{file_format}"), file_format)
17521 if file_format == "7z":
17522 wildcard = "{}|{}|*.zip".format(wildcard, lang.getstr("filetype.zip"))
17523 wildcard = "{}|{}|*.tgz".format(wildcard, lang.getstr("filetype.tgz"))
17524 # Ask where to save archive
17525 default_dir, default_file = get_verified_path("last_archive_save_path")
17526 dlg = wx.FileDialog(
17527 self,
17528 lang.getstr("archive.create"),
17529 default_dir,
17530 f"{os.path.basename(path_name)}.{file_format}",
17531 wildcard=wildcard,
17532 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
17533 )
17534 dlg.Center(wx.BOTH)
17535 result = dlg.ShowModal()
17536 archive_path = dlg.GetPath()
17537 if sevenzip and dlg.GetFilterIndex():
17538 # ZIP or TGZ
17539 sevenzip = None
17540 dlg.Destroy()
17541 if result != wx.ID_OK:
17542 return
17543 setcfg("last_archive_save_path", archive_path)
17544 dirname = os.path.dirname(filename)
17545 dirfilenames = [
17546 os.path.join(dirname, filename) for filename in os.listdir(dirname)
17547 ]
17548 dirfilenames.sort()
17549 # Select filenames
17550 filenames = (
17551 safe_glob(path_name + "*")
17552 + safe_glob(os.path.join(dirname, "*.ccmx"))
17553 + safe_glob(os.path.join(dirname, "*.ccss"))
17554 + safe_glob(os.path.join(dirname, "0_16.ti1"))
17555 + safe_glob(os.path.join(dirname, "0_16.ti3"))
17556 + safe_glob(os.path.join(dirname, "0_16.log"))
17557 )
17558 # Remove duplicates & sort
17559 filenames = sorted(set(filenames))
17560 lut3d_ext = [
17561 "." + strtr(lut3d_format, {"eeColor": "txt", "madVR": "3dlut"})
17562 for lut3d_format in [
17563 f
17564 for f in config.VALID_VALUES["3dlut.format"]
17565 if f not in ("icc", "icm", "png")
17566 ]
17567 ]
17568 has_3dlut = False
17569 for filename in filenames:
17570 if os.path.splitext(filename)[1].lower() in lut3d_ext:
17571 has_3dlut = True
17572 break
17573 if has_3dlut:
17574 # Should 3D LUT files be included?
17575 dlg = ConfirmDialog(
17576 self,
17577 msg=lang.getstr("archive.include_3dluts"),
17578 ok=lang.getstr("no"),
17579 alt=lang.getstr("yes"),
17580 cancel=lang.getstr("cancel"),
17581 bitmap=get_icon(32, "dialog-question"),
17582 )
17583 result = dlg.ShowModal()
17584 if result == wx.ID_CANCEL:
17585 return
17586 if result != wx.ID_OK:
17587 # Include 3D LUTs
17588 lut3d_ext = None
17589 self.worker.interactive = False
17590 self.worker.start(
17591 self.create_session_archive_consumer,
17592 self.create_session_archive_producer,
17593 wargs=(
17594 dirname,
17595 dirfilenames,
17596 filenames,
17597 archive_path,
17598 lut3d_ext if has_3dlut else None,
17599 sevenzip,
17600 ),
17601 progress_msg=lang.getstr("archive.create"),
17602 stop_timers=False,
17603 cancelable=bool(sevenzip),
17604 fancy=False,
17605 )
17606
17607 def create_session_archive_producer(
17608 self,
17609 dirname: str,
17610 dirfilenames: list[str],
17611 filenames: list[str],
17612 archive_path: str,
17613 exclude_ext: None | list,
17614 sevenzip: None | str,
17615 ) -> bool | Exception:
17616 """Create session archive.
17617
17618 Args:
17619 dirname (str): The directory name where the files are located.
17620 dirfilenames (list): List of all filenames in the directory.
17621 filenames (list): List of filenames to include in the archive.
17622 archive_path (str): The path where the archive will be saved.
17623 exclude_ext (None | list): List of file extensions to exclude from
17624 the archive.
17625 sevenzip (None | str): Path to the 7-Zip executable, or None to
17626 create a ZIP archive.
17627
17628 Returns:
17629 bool | Exception: True if the archive was created successfully, or
17630 an Exception if an error occurred.
17631 """
17632 if sevenzip:
17633 # Create 7z archive
17634 if filenames == dirfilenames:
17635 # Add whole folder to archive, so that the 7z archive
17636 # has one folder in it containing all files
17637 filenames = [dirname]
17638 if os.path.isfile(archive_path):
17639 os.remove(archive_path)
17640 args = ["a", "-y"]
17641 if exclude_ext:
17642 args.extend(f"-xr!*{ext}" for ext in exclude_ext)
17643 return self.worker.exec_cmd(
17644 sevenzip, [*args, archive_path, *filenames], capture_output=True
17645 )
17646 # Create gzipped TAR or ZIP archive
17647 dirbasename = ""
17648 if filenames == dirfilenames:
17649 # Add whole folder to archive, so that the ZIP archive
17650 # has one folder in it containing all files
17651 dirbasename = os.path.basename(dirname)
17652 if archive_path.lower().endswith(".tgz") or archive_path.lower().endswith(
17653 ".tar.gz"
17654 ):
17655 # Create gzipped tar archive
17656 archive = TarFileProper.open(archive_path, "w:gz", encoding="UTF-8")
17657 writefile = archive.add
17658 else:
17659 archive = zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED)
17660 writefile = archive.write
17661 try:
17662 with archive:
17663 for filename in filenames:
17664 if (
17665 exclude_ext
17666 and os.path.splitext(filename)[1].lower() in exclude_ext
17667 ):
17668 continue
17669 writefile(
17670 filename,
17671 os.path.join(dirbasename, os.path.basename(filename)),
17672 )
17673 except Exception as exception:
17674 return exception
17675 else:
17676 return True
17677
17678 def create_session_archive_consumer(self, result: bool | Exception) -> None:
17679 """Handle the result of the session archive creation.
17680
17681 Args:
17682 result (bool | Exception): The result of the archive creation.
17683 """
17684 if not result:
17685 result = UnloggedError("".join(self.worker.errors))
17686 if isinstance(result, Exception):
17687 show_result_dialog(result, parent=self)
17688
17689 def profile_save_path_btn_handler(self, event: wx.Event) -> None:
17690 """Handle the profile save path button.
17691
17692 Args:
17693 event (wx.Event): The event that triggered this handler.
17694 """
17695 default_path = os.path.join(*get_verified_path("profile.save_path"))
17696 profile_name = getcfg("profile.name.expanded")
17697 dlg = wx.DirDialog(
17698 self,
17699 lang.getstr("dialog.set_profile_save_path", profile_name),
17700 defaultPath=default_path,
17701 )
17702 dlg.Center(wx.BOTH)
17703 if dlg.ShowModal() != wx.ID_OK:
17704 dlg.Destroy()
17705 return
17706
17707 path = dlg.GetPath()
17708 profile_save_dir = os.path.join(path, profile_name)
17709 if not os.path.isdir(profile_save_dir):
17710 os.makedirs(profile_save_dir, exist_ok=True)
17711 if not waccess(os.path.join(profile_save_dir, profile_name), os.W_OK):
17712 show_result_dialog(
17713 Error(lang.getstr("error.access_denied.write", path)), self
17714 )
17715 return
17716 with contextlib.suppress(Exception):
17717 os.rmdir(profile_save_dir)
17718 setcfg("profile.save_path", path)
17719 self.update_profile_name()
17720 dlg.Destroy()
17721
17722 def profile_name_info_btn_handler(self, event: wx.Event) -> None:
17723 """Show a tooltip window with profile name placeholders and their meanings."""
17724 if not hasattr(self, "profile_name_tooltip_window"):
17725 self.profile_name_tooltip_window = TooltipWindow(
17726 self,
17727 msg=self.profile_name_info(),
17728 cols=2,
17729 title=lang.getstr("profile.name"),
17730 bitmap=get_icon(32, "dialog-information"),
17731 )
17732 else:
17733 self.profile_name_tooltip_window.Show()
17734 self.profile_name_tooltip_window.Raise()
17735
17736 def profile_name_info(self) -> str:
17737 """Return a string with profile name placeholders and their meanings.
17738
17739 Returns:
17740 str: A formatted string with profile name placeholders and their
17741 meanings.
17742 """
17743 info = [
17744 f"%nn\t{lang.getstr('computer.name')}",
17745 f"%dn\t{lang.getstr('display')}",
17746 f"%dns\t{lang.getstr('display_short')}",
17747 f"%dnw\t{lang.getstr('display')} ({lang.getstr('windows_only')})",
17748 f"%dnws\t{lang.getstr('display_short')} ({lang.getstr('windows_only')})",
17749 f"%out\t{lang.getstr('display.output')}",
17750 f"%ds\t{lang.getstr('edid.serial')} ({lang.getstr('if_available')})",
17751 f"%crc32\t{lang.getstr('edid.crc32')} ({lang.getstr('if_available')})",
17752 f"%in\t{lang.getstr('instrument')}",
17753 f"%im\t{lang.getstr('measurement_mode')}",
17754 f"%wp\t{lang.getstr('whitepoint')}",
17755 f"%cb\t{lang.getstr('calibration.luminance')}",
17756 f"%cB\t{lang.getstr('calibration.black_luminance')}",
17757 f"%cg\t{lang.getstr('trc')}",
17758 f"%ca\t{lang.getstr('calibration.ambient_viewcond_adjust')}",
17759 f"%cf\t{lang.getstr('calibration.black_output_offset')}",
17760 f"%ck\t{lang.getstr('calibration.black_point_correction')}",
17761 ]
17762 if DEFAULTS["calibration.black_point_rate.enabled"]:
17763 info.append(f"%cA\t{lang.getstr('calibration.black_point_rate')}")
17764 info.extend(
17765 [
17766 f"%cq\t{lang.getstr('calibration.speed')}",
17767 f"%pq\t{lang.getstr('profile.quality')}",
17768 f"%pt\t{lang.getstr('profile.type')}",
17769 f"%tpa\t{lang.getstr('testchart.info')}",
17770 ]
17771 )
17772 return "{}\n{}".format(
17773 lang.getstr("profile.name.placeholders"), "\n".join(info)
17774 )
17775
17776 def check_profile_b2a_hires(self, profile: ICCProfile) -> bool:
17777 """Check if profile is a LUT-type.
17778
17779 If yes, if LUT is of high enough resolution when created by ArgyllCMS
17780 (we assume anything >= 17 to be ok) and give choice to generate hires
17781 tables if not.
17782
17783 Args:
17784 profile (ICCProfile): The ICC profile to check.
17785
17786 Returns:
17787 bool: True if hires B2A or no B2A, False otherwise.
17788 """
17789 if (
17790 "B2A0" in profile.tags
17791 and isinstance(profile.tags.B2A0, LUT16Type)
17792 and profile.tags.B2A0.clut_grid_steps < 17
17793 and profile.creator == b"argl"
17794 ):
17795 # Nope. Not allowing to install. Offer to re-generate B2A
17796 # tables.
17797 dlg = ConfirmDialog(
17798 self,
17799 msg=lang.getstr("profile.b2a.lowres.warning"),
17800 bitmap=get_icon(32, "dialog-warning"),
17801 )
17802 choice = dlg.ShowModal()
17803 if choice == wx.ID_OK:
17804 self.profile_hires_b2a_handler(None, profile)
17805 return False
17806 return True
17807
17808 def profile_hires_b2a_handler(
17809 self, event: wx.Event, profile: None | ICCProfile = None
17810 ) -> None:
17811 """Handle the profile B2A highres generation.
17812
17813 Args:
17814 event (wx.Event): Event that triggered this handler.
17815 profile (None | ICCProfile, optional): The profile for which B2A
17816 tables should be generated. If None, a profile selection dialog
17817 will be shown to select a profile.
17818 """
17819 if not profile:
17820 profile = self.select_profile(
17821 title=lang.getstr("profile.b2a.hires"), ignore_current_profile=True
17822 )
17823 if not profile:
17824 return
17825 if not ("A2B0" in profile.tags or "A2B1" in profile.tags):
17826 result = Error(
17827 lang.getstr(
17828 "profile.required_tags_missing",
17829 f"A2B0 {lang.getstr('or')} A2B1",
17830 )
17831 )
17832 elif (
17833 "A2B0" in profile.tags and not isinstance(profile.tags.A2B0, LUT16Type)
17834 ) or ("A2B1" in profile.tags and not isinstance(profile.tags.A2B1, LUT16Type)):
17835 result = Error(lang.getstr("profile.required_tags_missing", "LUT16Type"))
17836 elif profile.connectionColorSpace not in (b"XYZ", b"Lab"):
17837 connection_color_space = profile.connectionColorSpace.decode("utf-8")
17838 result = Error(
17839 lang.getstr(
17840 "profile.unsupported",
17841 (connection_color_space, connection_color_space),
17842 )
17843 )
17844 else:
17845 result = None
17846 if result:
17847 show_result_dialog(result, self)
17848 else:
17849 self.interactive = False
17850 # self.profile_hires_b2a_consumer(
17851 # self.worker.update_profile_B2A(profile),
17852 # profile
17853 # )
17854 self.worker.start(
17855 self.profile_hires_b2a_consumer,
17856 self.worker.update_profile_B2A,
17857 cargs=(profile,),
17858 wargs=(profile,),
17859 wkwargs={"clutres": getcfg("profile.b2a.hires.size")},
17860 )
17861
17862 def profile_hires_b2a_consumer(
17863 self, result: str | Exception, profile: ICCProfile
17864 ) -> None:
17865 """Consumer for profile B2A highres generation.
17866
17867 Args:
17868 result (str | Exception): Result of the B2A generation.
17869 profile (ICCProfile): The profile for which B2A tables were
17870 generated.
17871 """
17872 self.start_timers()
17873 if isinstance(result, Exception):
17874 show_result_dialog(result, self)
17875 elif result:
17876 if not profile.filename or not os.path.isfile(profile.filename):
17877 # Let the user choose a location for the profile
17878 default_dir, default_file = os.path.split(profile.filename)
17879 dlg = wx.FileDialog(
17880 self,
17881 lang.getstr("save_as"),
17882 default_dir,
17883 default_file,
17884 wildcard=lang.getstr("filetype.icc") + "|*" + PROFILE_EXT,
17885 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
17886 )
17887 dlg.Center(wx.BOTH)
17888 result = dlg.ShowModal()
17889 profile_save_path = dlg.GetPath()
17890 dlg.Destroy()
17891 if result != wx.ID_OK:
17892 return
17893 filename, ext = os.path.splitext(profile_save_path)
17894 if ext.lower() not in (".icc", ".icm"):
17895 profile_save_path += PROFILE_EXT
17896 profile.setDescription(os.path.basename(filename))
17897 else:
17898 result = wx.ID_OK
17899 profile_save_path = profile.filename
17900 if result == wx.ID_OK:
17901 if not waccess(profile_save_path, os.W_OK):
17902 show_result_dialog(
17903 Error(
17904 lang.getstr("error.access_denied.write", profile_save_path)
17905 ),
17906 self,
17907 )
17908 return
17909 profile.calculate_id()
17910 profile.write(profile_save_path)
17911 if profile_save_path == get_current_profile_path():
17912 self.lut3d_update_b2a_controls()
17913 self.install_profile_handler(
17914 None, profile_save_path, install_3dlut=False
17915 )
17916 else:
17917 show_result_dialog(lang.getstr("error.profile.file_not_created"), self)
17918
17919 def create_profile_handler(
17920 self, event: wx.Event, path: None | str = None, skip_ti3_check: bool = False
17921 ) -> None:
17922 """Create profile from existing measurements.
17923
17924 Args:
17925 event (wx.Event): Event that triggered this handler.
17926 path (None | str, optional): Path to the measurement file. If None,
17927 a file dialog will be shown to select the measurement file.
17928 skip_ti3_check (bool): If True, skip the sanity check for the TI3
17929 file.
17930 """
17931 if not check_set_argyll_bin():
17932 return
17933 if self.check_show_macos_bugs_warning(cal=False) is False:
17934 return
17935 if path is None:
17936 selectedpaths = []
17937 # select measurement data (ti3 or profile)
17938 default_dir, default_file = get_verified_path("last_ti3_path")
17939 dlg = wx.FileDialog(
17940 self,
17941 lang.getstr("create_profile"),
17942 defaultDir=default_dir,
17943 defaultFile=default_file,
17944 wildcard=lang.getstr("filetype.icc_ti3") + "|*.icc;*.icm;*.ti3",
17945 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE,
17946 )
17947 dlg.Center(wx.BOTH)
17948 result = dlg.ShowModal()
17949 if result == wx.ID_OK:
17950 selectedpaths = dlg.GetPaths()
17951 dlg.Destroy()
17952 elif path:
17953 selectedpaths = [path]
17954 collected_ti3s = []
17955 for path_ in selectedpaths:
17956 if not os.path.exists(path_):
17957 InfoDialog(
17958 self,
17959 msg=lang.getstr("file.missing", path_),
17960 ok=lang.getstr("ok"),
17961 bitmap=get_icon(32, "dialog-error"),
17962 )
17963 return
17964 tags = {}
17965 ti3_lines = []
17966 # Get filename and extension of source file
17967 source_filename, source_ext = os.path.splitext(path_)
17968 if source_ext.lower() != ".ti3":
17969 try:
17970 profile = ICCProfile(path_)
17971 except (OSError, ICCProfileInvalidError):
17972 InfoDialog(
17973 self,
17974 msg=f"{lang.getstr('profile.invalid')}\n{path_}",
17975 ok=lang.getstr("ok"),
17976 bitmap=get_icon(32, "dialog-error"),
17977 )
17978 return
17979 if (profile.tags.get("CIED", b"") or profile.tags.get("targ", b""))[
17980 0:4
17981 ] != b"CTI3":
17982 InfoDialog(
17983 self,
17984 msg=f"{lang.getstr('profile.no_embedded_ti3')}\n{path_}",
17985 ok=lang.getstr("ok"),
17986 bitmap=get_icon(32, "dialog-error"),
17987 )
17988 return
17989 with BytesIO(
17990 profile.tags.get("CIED", b"") or profile.tags.get("targ", b"")
17991 ) as ti3:
17992 ti3_lines = [line.strip() for line in ti3]
17993 # Preserve custom tags
17994 for tagname in ("mmod", "meta"):
17995 if tagname in profile.tags:
17996 tags[tagname] = profile.tags[tagname]
17997 else:
17998 try:
17999 with open(path_, "rb") as ti3:
18000 ti3_lines = [line.strip() for line in ti3]
18001 except Exception:
18002 InfoDialog(
18003 self,
18004 msg=lang.getstr("error.file.open", path_),
18005 ok=lang.getstr("ok"),
18006 bitmap=get_icon(32, "dialog-error"),
18007 )
18008 return
18009 if b"CAL" not in ti3_lines:
18010 dlg = ConfirmDialog(
18011 self,
18012 msg=lang.getstr("dialog.ti3_no_cal_info"),
18013 ok=lang.getstr("continue"),
18014 cancel=lang.getstr("cancel"),
18015 bitmap=get_icon(32, "dialog-warning"),
18016 )
18017 result = dlg.ShowModal()
18018 dlg.Destroy()
18019 if result != wx.ID_OK:
18020 return
18021 collected_ti3s.append((path_, ti3_lines))
18022 if not collected_ti3s:
18023 return
18024 if len(collected_ti3s) > 1:
18025 source_filename = os.path.splitext(DEFAULTS["last_ti3_path"])[0]
18026 source_ext = ".ti3"
18027 path = collected_ti3s[0][0]
18028 is_tmp = False
18029 tmp_working_dir = self.worker.tempdir
18030 if tmp_working_dir:
18031 if sys.platform == "win32":
18032 if path.lower().startswith(tmp_working_dir.lower()):
18033 is_tmp = True
18034 elif path.startswith(tmp_working_dir):
18035 is_tmp = True
18036 if is_tmp:
18037 default_dir, default_file = get_verified_path("last_ti3_path")
18038 else:
18039 default_dir, default_file = os.path.split(path)
18040 setcfg("last_ti3_path", path)
18041 # let the user choose a location for the profile
18042 dlg = wx.FileDialog(
18043 self,
18044 lang.getstr("save_as"),
18045 default_dir,
18046 os.path.basename(source_filename) + PROFILE_EXT,
18047 wildcard=lang.getstr("filetype.icc") + "|*" + PROFILE_EXT,
18048 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
18049 )
18050 dlg.Center(wx.BOTH)
18051 result = dlg.ShowModal()
18052 profile_save_path = os.path.split(dlg.GetPath())
18053 profile_save_path = os.path.join(
18054 profile_save_path[0],
18055 make_argyll_compatible_path(profile_save_path[1], is_name=True),
18056 )
18057 dlg.Destroy()
18058 if result != wx.ID_OK:
18059 return
18060
18061 if not waccess(profile_save_path, os.W_OK):
18062 show_result_dialog(
18063 Error(lang.getstr("error.access_denied.write", profile_save_path)),
18064 self,
18065 )
18066 return
18067 filename, ext = os.path.splitext(profile_save_path)
18068 if ext.lower() not in (".icc", ".icm"):
18069 profile_save_path += PROFILE_EXT
18070 if os.path.exists(profile_save_path):
18071 dlg = ConfirmDialog(
18072 self,
18073 msg=lang.getstr("dialog.confirm_overwrite", (profile_save_path)),
18074 ok=lang.getstr("overwrite"),
18075 cancel=lang.getstr("cancel"),
18076 bitmap=get_icon(32, "dialog-warning"),
18077 )
18078 result = dlg.ShowModal()
18079 dlg.Destroy()
18080 if result != wx.ID_OK:
18081 return
18082 setcfg("last_cal_or_icc_path", profile_save_path)
18083 setcfg("last_icc_path", profile_save_path)
18084 # get filename and extension of target file
18085 profile_name = os.path.basename(os.path.splitext(profile_save_path)[0])
18086 # create temporary working dir
18087 tmp_working_dir = self.worker.create_tempdir()
18088 if isinstance(tmp_working_dir, Exception):
18089 self.worker.wrapup(False)
18090 show_result_dialog(tmp_working_dir, self)
18091 return
18092 # Copy ti3 to temp dir
18093 ti3_tmp_path = os.path.join(
18094 tmp_working_dir,
18095 make_argyll_compatible_path(f"{profile_name}.ti3", is_name=True),
18096 )
18097 if len(collected_ti3s) > 1:
18098 # Collect files for averaging
18099 collected_paths = []
18100 for ti3_path, ti3_lines in collected_ti3s:
18101 collected_path = os.path.join(
18102 tmp_working_dir, os.path.basename(ti3_path)
18103 )
18104 with open(collected_path, "wb") as ti3_file:
18105 ti3_file.write(b"\n".join(ti3_lines))
18106 collected_paths.append(collected_path)
18107 # Average the TI3 files
18108 args = ["-v", *collected_paths, ti3_tmp_path]
18109 cmd = get_argyll_util("average")
18110 result = self.worker.exec_cmd(
18111 cmd, args, capture_output=True, skip_scripts=True
18112 )
18113 for collected_path in collected_paths:
18114 os.remove(collected_path)
18115 if isinstance(result, Exception) or not result:
18116 self.worker.wrapup(False)
18117 show_result_dialog(result or Error("\n".join(self.worker.errors)), self)
18118 return
18119 path = ti3_tmp_path
18120 self.worker.options_dispcal = []
18121 self.worker.options_targen = []
18122 display_name = None
18123 display_manufacturer = None
18124 try:
18125 if source_ext.lower() == ".ti3":
18126 if path != ti3_tmp_path:
18127 shutil.copyfile(path, ti3_tmp_path)
18128 # Get dispcal options if present
18129 (options_dispcal, options_colprof) = get_options_from_ti3(path)
18130 self.worker.options_dispcal = ["-" + arg for arg in options_dispcal]
18131 arg = get_arg("M", options_colprof)
18132 if arg:
18133 display_name = arg[1][2:].strip('"')
18134 arg = get_arg("A", options_colprof)
18135 if arg:
18136 display_manufacturer = arg[1][2:].strip('"')
18137 else:
18138 # Binary mode because we want to avoid automatic
18139 # newlines conversion
18140 with open(ti3_tmp_path, "wb") as ti3:
18141 ti3.write(
18142 profile.tags.get("CIED", b"") or profile.tags.get("targ", b"")
18143 )
18144 # Get dispcal options if present
18145 self.worker.options_dispcal = [
18146 "-" + arg for arg in get_options_from_profile(profile)[0]
18147 ]
18148 if "dmdd" in profile.tags:
18149 display_name = profile.getDeviceModelDescription()
18150 if "dmnd" in profile.tags:
18151 display_manufacturer = profile.getDeviceManufacturerDescription()
18152 if is_tmp and path != ti3_tmp_path:
18153 profile.close()
18154 os.remove(path)
18155 ti3 = CGATS(ti3_tmp_path)
18156 if ti3.queryv1("COLOR_REP") and ti3.queryv1("COLOR_REP")[:3] == b"RGB":
18157 self.worker.options_targen = ["-d3"]
18158 except Exception as exception:
18159 handle_error(
18160 Error(
18161 "Error - temporary .ti3 file could not "
18162 "be created: " + str(exception)
18163 ),
18164 parent=self,
18165 )
18166 self.worker.wrapup(False)
18167 return
18168 setcfg("calibration.file.previous", None)
18169 print("-" * 80)
18170 if not skip_ti3_check and not self.measurement_file_check_confirm(ti3):
18171 self.worker.wrapup(False)
18172 return
18173 # Run colprof
18174 self.worker.interactive = False
18175 self.worker.start(
18176 self.profile_finish,
18177 self.worker.create_profile,
18178 ckwargs={
18179 "profile_path": profile_save_path,
18180 "failure_msg": lang.getstr("error.profile.file_not_created"),
18181 "install_3dlut": getcfg("3dlut.create"),
18182 },
18183 wkwargs={
18184 "dst_path": profile_save_path,
18185 "display_name": display_name,
18186 "display_manufacturer": display_manufacturer,
18187 "tags": tags,
18188 },
18189 progress_msg=lang.getstr("create_profile"),
18190 )
18191
18192 def create_profile_from_edid(self, event: wx.Event) -> None:
18193 """Create profile from EDID.
18194
18195 Args:
18196 event (wx.Event): A wx.Event object triggering this method.
18197 """
18198 edid = self.worker.get_display_edid()
18199 default_file = (
18200 edid.get("monitor_name", edid.get("ascii", str(edid["product_id"])))
18201 + PROFILE_EXT
18202 )
18203 default_dir = get_verified_path(
18204 None, os.path.join(getcfg("profile.save_path"), default_file)
18205 )[0]
18206 # let the user choose a location for the profile
18207 dlg = wx.FileDialog(
18208 self,
18209 lang.getstr("save_as"),
18210 default_dir,
18211 default_file,
18212 wildcard=lang.getstr("filetype.icc") + "|*" + PROFILE_EXT,
18213 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
18214 )
18215 dlg.Center(wx.BOTH)
18216 result = dlg.ShowModal()
18217 profile_save_path = os.path.split(dlg.GetPath())
18218 profile_save_path = os.path.join(
18219 profile_save_path[0],
18220 make_argyll_compatible_path(profile_save_path[1], is_name=True),
18221 )
18222 dlg.Destroy()
18223 if result != wx.ID_OK:
18224 return
18225
18226 if not waccess(profile_save_path, os.W_OK):
18227 show_result_dialog(
18228 Error(lang.getstr("error.access_denied.write", profile_save_path)),
18229 self,
18230 )
18231 return
18232 profile = ICCProfile.from_edid(edid)
18233 try:
18234 profile.write(profile_save_path)
18235 except Exception as exception:
18236 InfoDialog(
18237 self,
18238 msg=str(exception),
18239 ok=lang.getstr("ok"),
18240 bitmap=get_icon(32, "dialog-error"),
18241 )
18242 else:
18243 if getcfg("profile.create_gamut_views"):
18244 print("-" * 80)
18245 print(lang.getstr("gamut.view.create"))
18246 self.worker.interactive = False
18247 self.worker.start(
18248 self.create_profile_from_edid_finish,
18249 self.worker.calculate_gamut,
18250 cargs=(profile,),
18251 wargs=(profile_save_path,),
18252 progress_msg=lang.getstr("gamut.view.create"),
18253 resume=False,
18254 )
18255 else:
18256 self.create_profile_from_edid_finish(True, profile)
18257
18258 def create_profile_from_edid_finish(
18259 self,
18260 result: bool | Exception,
18261 profile: ICCProfile,
18262 ) -> None:
18263 """Finish creating profile from EDID.
18264
18265 Args:
18266 result (bool | Exception): Result of the gamut calculation.
18267 profile (ICCProfile): The created ICC profile.
18268 """
18269 if isinstance(result, Exception):
18270 show_result_dialog(result, self)
18271 elif result:
18272 if isinstance(result, tuple):
18273 profile.set_gamut_metadata(result[0], result[1])
18274 prefix = profile.tags.meta.getvalue("prefix", b"", None)
18275 if isinstance(prefix, bytes):
18276 prefix = prefix.decode("utf-8")
18277 prefixes = prefix.split(",")
18278 # Set license
18279 profile.tags.meta["License"] = getcfg("profile.license")
18280 # Set device ID
18281 device_id = self.worker.get_device_id(quirk=False)
18282 if device_id:
18283 profile.tags.meta["MAPPING_device_id"] = device_id
18284 prefixes.append("MAPPING_")
18285 profile.tags.meta["prefix"] = ",".join(prefixes)
18286 profile.calculate_id()
18287 print("-" * 80)
18288 try:
18289 profile.write()
18290 except Exception as exception:
18291 show_result_dialog(exception, self)
18292 return
18293 self.profile_finish(
18294 True, profile.filename, install_3dlut=getcfg("3dlut.create")
18295 )
18296
18297 def create_profile_name(self) -> str:
18298 """Replace placeholders in profile name with values from configuration.
18299
18300 Returns:
18301 str: The profile name with placeholders replaced by actual values.
18302 """
18303 profile_name = self.profile_name_textctrl.GetValue()
18304
18305 # Computername
18306 if "%nn" in profile_name:
18307 profile_name = profile_name.replace("%nn", str(platform.node()) or "\0")
18308
18309 # Windows display name (EnumDisplayDevices / DeviceString)
18310 if "%dnws" in profile_name:
18311 display_win32_short = self.worker.get_display_name_short(False, False)
18312 profile_name = profile_name.replace("%dnws", display_win32_short or "\0")
18313 if "%dnw" in profile_name:
18314 display_win32 = self.worker.get_display_name(True, False)
18315 profile_name = profile_name.replace("%dnw", display_win32 or "\0")
18316
18317 # EDID
18318 if "%ds" in profile_name or "%crc32" in profile_name:
18319 edid = self.worker.get_display_edid()
18320 # Serial
18321 if "%ds" in profile_name:
18322 serial = edid.get("serial_ascii", hex(edid.get("serial_32", 0))[2:])
18323 if serial and serial not in ("0", "1010101", "fffffff"):
18324 profile_name = profile_name.replace("%ds", serial)
18325 else:
18326 profile_name = profile_name.replace("%ds", "\0")
18327 # CRC32
18328 if "%crc32" in profile_name:
18329 raw_edid = edid.get("edid")
18330 if isinstance(raw_edid, str):
18331 raw_edid = raw_edid.encode("utf-8")
18332 if raw_edid:
18333 profile_name = profile_name.replace(
18334 "%crc32", "%X" % (crc32(raw_edid) & 0xFFFFFFFF)
18335 )
18336 else:
18337 profile_name = profile_name.replace("%crc32", "\0")
18338
18339 # Display name
18340 if "%dns" in profile_name:
18341 display_short = self.worker.get_display_name_short(False, True)
18342 profile_name = profile_name.replace("%dns", display_short or "\0")
18343 if "%dn" in profile_name:
18344 display = self.worker.get_display_name(True, True)
18345 profile_name = profile_name.replace("%dn", display or "\0")
18346
18347 # Output #
18348 if config.is_virtual_display():
18349 output = "\0"
18350 else:
18351 output = "#{}".format(getcfg("display.number"))
18352 profile_name = profile_name.replace("%out", output or "\0")
18353
18354 # Instrument name
18355 if "%in" in profile_name:
18356 instrument = self.comport_ctrl.GetStringSelection()
18357 profile_name = profile_name.replace("%in", instrument or "\0")
18358
18359 # Measurement mode
18360 if "%im" in profile_name:
18361 mode = ""
18362 measurement_mode = self.get_measurement_mode()
18363 if measurement_mode:
18364 if "c" in measurement_mode:
18365 mode += lang.getstr("measurement_mode.refresh")
18366 elif "l" in measurement_mode:
18367 mode += lang.getstr("measurement_mode.lcd")
18368 if "p" in measurement_mode:
18369 if mode:
18370 mode += "-"
18371 mode += lang.getstr("projector")
18372 if "V" in measurement_mode:
18373 if mode:
18374 mode += "-"
18375 mode += lang.getstr("measurement_mode.adaptive")
18376 if "H" in measurement_mode:
18377 if mode:
18378 mode += "-"
18379 mode += lang.getstr("measurement_mode.highres")
18380 else:
18381 mode += lang.getstr("default")
18382 profile_name = profile_name.replace("%im", mode)
18383
18384 trc = self.get_trc()
18385 do_cal = self.interactive_display_adjustment_cb.GetValue() or trc
18386
18387 # Whitepoint
18388 if "%wp" in profile_name:
18389 whitepoint = self.get_whitepoint()
18390 whitepoint_locus = self.get_whitepoint_locus()
18391 if isinstance(whitepoint, str):
18392 if whitepoint.find(",") < 0:
18393 if whitepoint_locus == "t":
18394 whitepoint = "D" + whitepoint
18395 else:
18396 whitepoint += "K"
18397 else:
18398 whitepoint = "x ".join(whitepoint.split(",")) + "y"
18399 profile_name = profile_name.replace("%wp", (do_cal and whitepoint) or "\0")
18400
18401 # Luminance
18402 if "%cb" in profile_name:
18403 luminance = self.get_luminance()
18404 profile_name = profile_name.replace(
18405 "%cb", "\0" if luminance is None or not do_cal else luminance + "cdm²"
18406 )
18407
18408 # Black luminance
18409 if "%cB" in profile_name:
18410 black_luminance = self.get_black_luminance()
18411 profile_name = profile_name.replace(
18412 "%cB",
18413 (
18414 "\0"
18415 if black_luminance is None or not do_cal
18416 else black_luminance + "cdm²"
18417 ),
18418 )
18419
18420 # TRC / black output offset
18421 if "%cg" in profile_name or "%cf" in profile_name:
18422 black_output_offset = self.get_black_output_offset()
18423
18424 # TRC
18425 if "%cg" in profile_name and trc:
18426 trc_type = self.get_trc_type()
18427 bt1886 = trc == "2.4" and trc_type == "G" and black_output_offset == "0"
18428 if bt1886:
18429 trc = "Rec. 1886"
18430 elif trc not in ("l", "709", "s", "240"):
18431 if trc_type == "G":
18432 trc = "{} ({})".format(
18433 trc, lang.getstr("trc.type.absolute").lower()
18434 )
18435 else:
18436 trc = strtr(
18437 trc, {"l": "L", "709": "Rec. 709", "s": "sRGB", "240": "SMPTE240M"}
18438 )
18439 profile_name = profile_name.replace("%cg", trc or "\0")
18440
18441 # Ambient adjustment
18442 if "%ca" in profile_name:
18443 ambient = self.get_ambient()
18444 profile_name = profile_name.replace(
18445 "%ca", "\0" if ambient is None or not trc else ambient + "lx"
18446 )
18447
18448 # Black output offset
18449 if "%cf" in profile_name:
18450 f = int(float(black_output_offset) * 100)
18451 profile_name = profile_name.replace("%cf", (f"{f:.0f}%") if trc else "\0")
18452
18453 # Black point correction / rate
18454 if "%ck" in profile_name or "%cA" in profile_name:
18455 black_point_correction = self.get_black_point_correction()
18456
18457 # Black point correction
18458 if "%ck" in profile_name:
18459 k = int(float(black_point_correction) * 100)
18460 auto = self.black_point_correction_auto_cb.GetValue()
18461 profile_name = profile_name.replace(
18462 "%ck",
18463 (
18464 (str(k) + "% " if 0 < k < 100 else "")
18465 + (lang.getstr("neutral") if k > 0 else "\0").lower()
18466 if trc and not auto
18467 else "\0"
18468 ),
18469 )
18470
18471 # Black point rate
18472 if "%cA" in profile_name:
18473 black_point_rate = self.get_black_point_rate()
18474 if black_point_rate and float(black_point_correction) < 1 and trc:
18475 profile_name = profile_name.replace("%cA", black_point_rate)
18476 else:
18477 profile_name = profile_name.replace("%cA", "\0")
18478
18479 # Calibration / profile quality
18480 if "%cq" in profile_name or "%pq" in profile_name:
18481 calibration_quality = self.get_calibration_quality()
18482 profile_quality = getcfg("profile.quality")
18483 aspects = {"c": calibration_quality if trc else "", "p": profile_quality}
18484 msgs = {"u": "VS", "h": "S", "m": "M", "l": "F", "v": "VF", "": "\0"}
18485 quality = {}
18486 if "%cq" in profile_name:
18487 quality["c"] = msgs[aspects["c"]]
18488 if "%pq" in profile_name:
18489 quality["p"] = msgs[aspects["p"]]
18490 if len(quality) == 2 and (
18491 quality["c"] == quality["p"] or quality["c"] == "\0"
18492 ):
18493 profile_name = re.sub(r"%cq\W*%pq", quality["p"], profile_name)
18494 for q in quality:
18495 profile_name = profile_name.replace(f"%{q}q", quality[q])
18496
18497 # Profile type
18498 if "%pt" in profile_name:
18499 profile_type = {
18500 "G": "1xGamma+MTX",
18501 "g": "3xGamma+MTX",
18502 "l": "LabLUT",
18503 "S": "1xCurve+MTX",
18504 "s": "3xCurve+MTX",
18505 "X": "XYZLUT+MTX",
18506 "x": "XYZLUT",
18507 }.get(self.get_profile_type())
18508 profile_name = profile_name.replace("%pt", profile_type or "\0")
18509
18510 # Amount of test patches
18511 if "%tpa" in profile_name:
18512 profile_name = profile_name.replace(
18513 "%tpa", self.testchart_patches_amount.GetLabel()
18514 )
18515
18516 # Date / time
18517 directives = (
18518 "a",
18519 "A",
18520 "b",
18521 "B",
18522 "d",
18523 "H",
18524 "I",
18525 "j",
18526 "m",
18527 "M",
18528 "p",
18529 "S",
18530 "U",
18531 "w",
18532 "W",
18533 "y",
18534 "Y",
18535 )
18536 for directive in directives:
18537 if f"%{directive}" in profile_name:
18538 with contextlib.suppress(UnicodeDecodeError):
18539 profile_name = profile_name.replace(
18540 f"%{directive}", strftime(f"%{directive}")
18541 )
18542
18543 # All whitespace to space
18544 profile_name = re.sub(r"\s", " ", profile_name)
18545
18546 # Get rid of inserted NULL bytes
18547 # Try to keep spacing intact
18548 if "\0" in profile_name:
18549 profile_name = re.sub(r"^(\0[_\- ]?)+|([_\- ]?\0)+$", "", profile_name)
18550 # Surrounded by underscores
18551 while "_\0" in profile_name or "\0_" in profile_name:
18552 while re.search(r"_\0+_", profile_name):
18553 profile_name = re.sub(r"_\0+_", "_", profile_name)
18554 profile_name = re.sub(r"_\0+", "_", profile_name)
18555 profile_name = re.sub(r"\0+_", "_", profile_name)
18556 # Surrounded by dashes
18557 while "-\0" in profile_name or "\0-" in profile_name:
18558 while re.search(r"-\0+-", profile_name):
18559 profile_name = re.sub(r"-\0+-", "-", profile_name)
18560 profile_name = re.sub(r"-\0+", "-", profile_name)
18561 profile_name = re.sub(r"\0+-", "-", profile_name)
18562 # Surrounded by whitespace
18563 while " \0" in profile_name or "\0 " in profile_name:
18564 while re.search(r" \0+ ", profile_name):
18565 profile_name = re.sub(r" \0+ ", " ", profile_name)
18566 profile_name = re.sub(r" \0+", " ", profile_name)
18567 profile_name = re.sub(r"\0+ ", " ", profile_name)
18568 profile_name = re.sub(r"\0+", "", profile_name)
18569
18570 # Windows silently strips any combination of trailing spaces and dots
18571 profile_name = profile_name.rstrip(" .")
18572
18573 # Get rid of characters considered invalid for filenames.
18574 # Also strip leading dashes which might trick Argyll tools into
18575 # mistaking parts of the profile name as an option parameter
18576 profile_name = re.sub(r"[\\/:;*?\"<>|]+", "_", profile_name).lstrip("-")
18577
18578 # Windows: MAX_PATH = 260, e.g. C:\256-char-path<NUL>
18579 # Subtracting NUL and the four-char extension (e.g. .icm) leaves us
18580 # with 255 characters, e.g.
18581 # C:\Users\<User>\AppData\Roaming\DisplayCAL\storage\<Name>\<Name>.icm
18582 # Mac OS X HFS+ has a 255-character limit.
18583 profile_save_path = getcfg("profile.save_path")
18584 maxpath = 255
18585 # Leave headroom of 31 chars
18586 maxpath -= 31
18587 if maxpath < len(profile_save_path):
18588 maxpath = len(profile_save_path) + 2
18589 profile_path = os.path.join(profile_save_path, profile_name, profile_name)
18590 while len(profile_path) > maxpath:
18591 profile_name = profile_name[:-1]
18592 profile_path = os.path.join(profile_save_path, profile_name, profile_name)
18593 return profile_name
18594
18595 def update_profile_name(self, event: None | wx.Event = None) -> None:
18596 """Update the profile name based on the current configuration.
18597
18598 This method generates a profile name by replacing placeholders in the
18599 profile name text control with values from the configuration. It checks
18600 if the generated profile name is valid, and if not, it attempts to
18601 create a valid profile name by using the default profile name or the
18602 last used profile name. If the profile name is still invalid, it sets
18603 the profile name text control to a default value.
18604
18605 Args:
18606 event (wx.Event, optional): The event that triggered this method.
18607 """
18608 profile_name = self.create_profile_name()
18609 if not self.check_profile_name(profile_name):
18610 self.profile_name_textctrl.ChangeValue(getcfg("profile.name"))
18611 profile_name = self.create_profile_name()
18612 if not self.check_profile_name(profile_name):
18613 self.profile_name_textctrl.ChangeValue(DEFAULTS.get("profile.name", ""))
18614 profile_name = self.create_profile_name()
18615 profile_name = make_argyll_compatible_path(profile_name, is_name=True)
18616 if profile_name != self.profile_name.GetLabel():
18617 setcfg("profile.name", self.profile_name_textctrl.GetValue())
18618 self.profile_name.SetToolTipString(profile_name)
18619 self.profile_name.SetLabel(profile_name.replace("&", "&&"))
18620 setcfg("profile.name.expanded", profile_name)
18621
18622 def check_profile_name(self, profile_name: None | str = None) -> bool:
18623 r"""Check if the profile name is valid.
18624
18625 A valid profile name must not contain any of the following characters:
18626 \ / : ; * ? " < > | and must not start with a dash (-).
18627 Additionally, it must not end with a combination of trailing spaces and
18628 dots, as Windows silently strips these characters.
18629
18630 Args:
18631 profile_name (None | str, optional): The profile name to check. If
18632 None, it uses the value from the profile name text control.
18633
18634 Returns:
18635 bool: True if the profile name is valid, False otherwise.
18636 """
18637 if profile_name is None:
18638 profile_name = self.profile_name_textctrl.GetValue()
18639 return (
18640 re.match(r"^[^\\/:;*?\"<>|]+$", profile_name)
18641 and not profile_name.startswith("-")
18642 # Windows silently strips any combination of trailing spaces and dots
18643 and profile_name == profile_name.rstrip(" .")
18644 )
18645
18646 def get_ambient(self) -> None | str:
18647 """Return the ambient light adjustment value as a string.
18648
18649 If the ambient light adjustment checkbox is checked, return the value
18650 from the ambient light adjustment text control, stripped of leading and
18651 trailing zeros. If the checkbox is not checked, it returns None.
18652
18653 Returns:
18654 None | str: The ambient light adjustment value as a string if the
18655 checkbox is checked, otherwise None.
18656 """
18657 if self.ambient_viewcond_adjust_cb.GetValue():
18658 return str(stripzeros(self.ambient_viewcond_adjust_textctrl.GetValue()))
18659 return None
18660
18661 def get_argyll_data_files(
18662 self,
18663 scope: str,
18664 wildcard: str,
18665 include_lastmod: bool = False,
18666 ) -> list[str | tuple[str, float]]:
18667 """Get paths of Argyll data files.
18668
18669 Args:
18670 scope (str): A string containing "l" for local system and/or "u"
18671 for user.
18672 wildcard (str): A wildcard pattern to match files.
18673 include_lastmod (bool): If True, include the last modification time
18674 of the files.
18675
18676 Returns:
18677 list[str | tuple[str, float]]: A list of file paths or tuples of
18678 (file path, last modification time).
18679 """
18680 data_files = []
18681 if sys.platform != "darwin":
18682 if "l" in scope:
18683 for commonappdata in config.COMMONAPPDATA:
18684 data_files += safe_glob(
18685 os.path.join(commonappdata, "color", wildcard)
18686 )
18687 data_files += safe_glob(
18688 os.path.join(commonappdata, "ArgyllCMS", wildcard)
18689 )
18690 if "u" in scope:
18691 data_files += safe_glob(os.path.join(config.APPDATA, "color", wildcard))
18692 else:
18693 if "l" in scope:
18694 data_files += safe_glob(os.path.join(config.LIBRARY, "color", wildcard))
18695 data_files += safe_glob(
18696 os.path.join(config.LIBRARY, "ArgyllCMS", wildcard)
18697 )
18698 if [1, 9] <= self.worker.argyll_version <= [1, 9, 1]:
18699 # Argyll CMS 1.9 and 1.9.1 use *nix locations due to a
18700 # configuration problem
18701 data_files += safe_glob(
18702 os.path.join("/usr/local/share", "ArgyllCMS", wildcard)
18703 )
18704 if "u" in scope:
18705 data_files += safe_glob(
18706 os.path.join(config.LIBRARY_HOME, "color", wildcard)
18707 )
18708 if [1, 9] <= self.worker.argyll_version <= [1, 9, 1]:
18709 # Argyll CMS 1.9 and 1.9.1 use *nix locations due to a
18710 # configuration problem
18711 data_files += safe_glob(
18712 os.path.join(
18713 config.HOME, ".local", "share", "ArgyllCMS", wildcard
18714 )
18715 )
18716 if "u" in scope:
18717 data_files += safe_glob(os.path.join(config.APPDATA, "ArgyllCMS", wildcard))
18718 filenames = list(data_files)
18719 data_files = []
18720 mapping = {}
18721 for filename in filenames:
18722 basename = os.path.basename(filename)
18723 if (
18724 basename not in mapping
18725 or os.path.basename(os.path.dirname(filename)) == "ArgyllCMS"
18726 ):
18727 # Prefer files with same basename in 'ArgyllCMS' folder over
18728 # 'color' folder
18729 mapping[basename] = filename
18730
18731 for filename in mapping.values():
18732 if include_lastmod:
18733 try:
18734 lastmod = os.stat(filename).st_mtime
18735 except OSError:
18736 lastmod = -1
18737 data_files.append((filename, lastmod))
18738 else:
18739 data_files.append(filename)
18740 return data_files
18741
18742 def get_instrument_type(self) -> str:
18743 """Return the instrument type as a string.
18744
18745 This method checks the instrument features to determine if it is a
18746 colorimeter or a spectrometer.
18747
18748 Returns:
18749 str: The instrument type, which can be either "color" for a
18750 colorimeter or "spect" for a spectrometer.
18751 """
18752 # Return the instrument type, "color" (colorimeter) or "spect"
18753 # (spectrometer)
18754 spect = self.worker.get_instrument_features().get("spectral", False)
18755 return "spect" if spect else "color"
18756
18757 def get_measurement_mode(self) -> str:
18758 """Return the measurement mode as string.
18759
18760 Examples:
18761 Argyll options -V -H (adaptive highres mode)
18762 Returned string 'VH'
18763
18764 Argyll option -yl
18765 Returned string 'l'
18766
18767 Argyll options -p -H (projector highres mode)
18768 Returned string 'pH'
18769
18770
18771 Returns:
18772 str: The measurement mode as a string, which can be one of the
18773 following:
18774 - "c" for refresh mode
18775 - "l" for LCD mode
18776 - "p" for projector mode
18777 - "V" for adaptive mode
18778 - "H" for high resolution mode
18779 """
18780 return self.measurement_modes_ab.get(self.get_instrument_type(), {}).get(
18781 self.measurement_mode_ctrl.GetSelection()
18782 )
18783
18784 def get_profile_type(self) -> str:
18785 """Return the profile type as a string.
18786
18787 Returns:
18788 str: The profile type as a string, which can be one of the following:
18789 - "G" for 1xGamma+MTX
18790 - "g" for 3xGamma+MTX
18791 - "l" for LabLUT
18792 - "S" for 1xCurve+MTX
18793 - "s" for 3xCurve+MTX
18794 - "X" for XYZLUT+MTX
18795 - "x" for XYZLUT
18796 """
18797 return self.profile_types_ab.get(
18798 self.profile_type_ctrl.GetSelection(), getcfg("profile.type")
18799 )
18800
18801 def get_whitepoint(self) -> None | str:
18802 """Return the whitepoint as a string.
18803
18804 Returns:
18805 None | str: The whitepoint as a string, which can be one of the
18806 following:
18807 - None for native whitepoint
18808 - A string representing the color temperature in kelvin
18809 - A string representing the xy coordinates in the format
18810 "x,y"
18811 """
18812 if self.whitepoint_ctrl.GetSelection() == 0:
18813 # Native
18814 return None
18815 if self.whitepoint_ctrl.GetSelection() == 1:
18816 # Color temperature in kelvin
18817 return str(
18818 stripzeros(
18819 self.whitepoint_colortemp_textctrl.GetValue().replace(",", ".")
18820 )
18821 )
18822 if self.whitepoint_ctrl.GetSelection() == 2:
18823 x = self.whitepoint_x_textctrl.GetValue()
18824 with contextlib.suppress(ValueError):
18825 x = round(x, 4)
18826 y = self.whitepoint_y_textctrl.GetValue()
18827 with contextlib.suppress(ValueError):
18828 y = round(y, 4)
18829 return str(stripzeros(x)) + "," + str(stripzeros(y))
18830 return None
18831
18832 def get_whitepoint_locus(self) -> str:
18833 """Return the whitepoint locus as a string.
18834
18835 Returns:
18836 str: The whitepoint locus as a string, which can be one of the
18837 following:
18838 - "t" for the whitepoint locus of the color temperature
18839 - "d" for the D series whitepoint locus
18840 - "p" for the P series whitepoint locus
18841 - "c" for the C series whitepoint locus
18842 """
18843 n = self.whitepoint_colortemp_locus_ctrl.GetSelection()
18844 if n not in self.whitepoint_colortemp_loci_ab:
18845 n = 0
18846 return str(self.whitepoint_colortemp_loci_ab[n])
18847
18848 def get_luminance(self) -> None | str:
18849 """Return the luminance as a string.
18850
18851 Returns:
18852 None | str: The luminance as a string, or None if the feature is
18853 not enabled in the configuration.
18854 """
18855 if self.luminance_ctrl.GetSelection() == 0:
18856 return None
18857 return str(stripzeros(self.luminance_textctrl.GetValue()))
18858
18859 def get_black_luminance(self) -> None | str:
18860 """Return the black luminance as a string.
18861
18862 Returns:
18863 None | str: The black luminance as a string, or None if the feature
18864 is not enabled in the configuration.
18865 """
18866 if self.black_luminance_ctrl.GetSelection() == 0:
18867 return None
18868 return str(stripzeros(self.black_luminance_textctrl.GetValue()))
18869
18870 def get_black_output_offset(self) -> str:
18871 """Return the black output offset as a string.
18872
18873 Returns:
18874 str: The black output offset as a string, or "0" if the feature
18875 is not enabled in the configuration.
18876 """
18877 return str(Decimal(self.black_output_offset_ctrl.GetValue()) / 100)
18878
18879 def get_black_point_correction(self) -> str:
18880 """Return the black point correction as a string.
18881
18882 Returns:
18883 str: The black point correction as a string, or "0" if the feature
18884 is not enabled in the configuration.
18885 """
18886 return str(Decimal(self.black_point_correction_ctrl.GetValue()) / 100)
18887
18888 def get_black_point_rate(self) -> None | str:
18889 """Return the black point rate as a string.
18890
18891 Returns:
18892 None | str: The black point rate as a string, or None if the
18893 feature is not enabled in the configuration.
18894 """
18895 if DEFAULTS["calibration.black_point_rate.enabled"]:
18896 return str(self.black_point_rate_floatctrl.GetValue())
18897 return None
18898
18899 def get_trc_type(self) -> str:
18900 """Return the TRC (Tone Response Curve) type as a string.
18901
18902 Returns:
18903 str: The TRC type, which can be either "G" (absolute) or "g"
18904 (relative).
18905 """
18906 if self.trc_type_ctrl.GetSelection() == 1:
18907 return "G"
18908 return "g"
18909
18910 def get_trc(self) -> str:
18911 """Return the TRC (Tone Response Curve) as a string.
18912
18913 Returns:
18914 str: The TRC value, which can be one of the following:
18915 - A string representing the TRC value (e.g., "2.4", "1.8")
18916 - "l" for linear
18917 - "709" for Rec. 709
18918 - "240" for SMPTE 240M
18919 - "s" for sRGB
18920 """
18921 if self.trc_ctrl.GetSelection() in (1, 4, 7):
18922 return str(stripzeros(self.trc_textctrl.GetValue().replace(",", ".")))
18923 if self.trc_ctrl.GetSelection() == 2:
18924 return "l"
18925 if self.trc_ctrl.GetSelection() == 3:
18926 return "709"
18927 if self.trc_ctrl.GetSelection() == 5:
18928 return "240"
18929 if self.trc_ctrl.GetSelection() == 6:
18930 return "s"
18931 return ""
18932
18933 def get_calibration_quality(self) -> str:
18934 """Return the calibration quality as a string.
18935
18936 Returns:
18937 str: The calibration quality, which can be one of the following:
18938 - "u" for Ultra
18939 - "h" for High
18940 - "m" for Medium
18941 - "l" for Low
18942 - "v" for Very Low
18943 """
18944 return self.quality_ab[self.calibration_quality_ctrl.GetValue()]
18945
18946 def get_profile_quality(self) -> str:
18947 """Return the profile quality as a string.
18948
18949 Returns:
18950 str: The profile quality, which can be one of the following:
18951
18952 - "u" for Ultra
18953 - "h" for High
18954 - "m" for Medium
18955 - "l" for Low
18956 - "v" for Very Low
18957 """
18958 return self.quality_ab[self.profile_quality_ctrl.GetValue() + 1]
18959
18960 def profile_settings_changed(self) -> None:
18961 """Mark the profile settings as changed.
18962
18963 This method is called when any profile setting is changed.
18964 """
18965 # cal = getcfg("calibration.file", False)
18966 # if cal:
18967 # filename, ext = os.path.splitext(cal)
18968 # if ext.lower() in (".icc", ".icm"):
18969 # if not os.path.exists(filename + ".cal") and \
18970 # not cal in self.presets:
18971 # self.cal_changed()
18972 # return
18973
18974 if self.updatingctrls:
18975 return
18976 setcfg("settings.changed", 1)
18977 if self.calibration_file_ctrl.GetStringSelection().startswith("*"):
18978 return
18979 sel = self.calibration_file_ctrl.GetSelection()
18980 if sel > 0:
18981 items = self.calibration_file_ctrl.GetItems()
18982 items[sel] = "* " + items[sel]
18983 self.calibration_file_ctrl.Freeze()
18984 self.calibration_file_ctrl.SetItems(items)
18985 self.calibration_file_ctrl.SetSelection(sel)
18986 self.calibration_file_ctrl.Thaw()
18987
18988 def testchart_ctrl_handler(self, event: wx.Event) -> None:
18989 """Handle changes to the testchart control.
18990
18991 Args:
18992 event (wx.Event): The event that triggered this method.
18993 """
18994 debug_print(
18995 "[D] testchart_ctrl_handler called for ID "
18996 f"{event.GetId()} {getevtobjname(event, self)} event type "
18997 f"{event.GetEventType()} {getevttype(event)}"
18998 )
18999 self.set_testchart(self.testcharts[self.testchart_ctrl.GetSelection()])
19000 wx.CallAfter(self.check_testchart_patches_amount)
19001
19002 def testchart_btn_handler(self, event: wx.Event, path: None | str = None) -> None:
19003 """Handle the testchart button click event.
19004
19005 Args:
19006 event (wx.Event): The event that triggered this method.
19007 path (None | str, optional): Path to the testchart file. If None,
19008 the default file dialog will be shown to select a testchart.
19009 """
19010 if path is None:
19011 default_dir, default_file = get_verified_path("testchart.file")
19012 dlg = wx.FileDialog(
19013 self,
19014 lang.getstr("dialog.set_testchart"),
19015 defaultDir=default_dir,
19016 defaultFile=default_file,
19017 wildcard=lang.getstr("filetype.icc_ti1_ti3")
19018 + "|*.icc;*.icm;*.ti1;*.ti3",
19019 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
19020 )
19021 dlg.Center(wx.BOTH)
19022 result = dlg.ShowModal()
19023 if result == wx.ID_OK:
19024 path = dlg.GetPath()
19025 dlg.Destroy()
19026 if not path:
19027 return
19028 if not os.path.exists(path):
19029 InfoDialog(
19030 self,
19031 msg=lang.getstr("file.missing", path),
19032 ok=lang.getstr("ok"),
19033 bitmap=get_icon(32, "dialog-error"),
19034 )
19035 return
19036 filename, ext = os.path.splitext(path)
19037 if ext.lower() in (".icc", ".icm"):
19038 try:
19039 profile = ICCProfile(path)
19040 except (OSError, ICCProfileInvalidError):
19041 InfoDialog(
19042 self,
19043 msg=lang.getstr("profile.invalid") + "\n" + path,
19044 ok=lang.getstr("ok"),
19045 bitmap=get_icon(32, "dialog-error"),
19046 )
19047 return
19048 ti3_lines = [
19049 line.strip()
19050 for line in BytesIO(
19051 profile.tags.get("CIED", b"") or profile.tags.get("targ", b"")
19052 )
19053 ]
19054 if "CTI3" not in ti3_lines:
19055 InfoDialog(
19056 self,
19057 msg=lang.getstr("profile.no_embedded_ti3") + "\n" + path,
19058 ok=lang.getstr("ok"),
19059 bitmap=get_icon(32, "dialog-error"),
19060 )
19061 return
19062 self.set_testchart(path)
19063 writecfg()
19064 self.profile_settings_changed()
19065
19066 def testchart_patches_amount_ctrl_handler(self, event: wx.Event) -> None:
19067 """Handle changes to the testchart patches amount control.
19068
19069 Args:
19070 event (wx.Event): The event that triggered this method.
19071 """
19072 auto = self.testchart_patches_amount_ctrl.GetValue()
19073 if event:
19074 setcfg("testchart.auto_optimize", auto)
19075 self.profile_settings_changed()
19076 proftype = getcfg("profile.type")
19077 if auto > 4:
19078 s = min(auto, 11) * 4 - 3
19079 g = s * 3 - 2
19080 patches_amount = get_total_patches(4, 4, s, g, auto, auto, 0) + 34
19081 patches_amount += 120
19082 if event and proftype not in ("l", "x", "X"):
19083 setcfg("profile.type", "x" if getcfg("3dlut.create") else "X")
19084 else:
19085 if auto == 1:
19086 patches_amount = 34
19087 elif auto == 2:
19088 patches_amount = 79
19089 elif auto == 3:
19090 patches_amount = 115
19091 else:
19092 patches_amount = 175
19093 if event:
19094 if auto > 1 and proftype not in ("x", "X"):
19095 setcfg("profile.type", "x" if getcfg("3dlut.create") else "X")
19096 elif auto < 2 and proftype not in ("g", "G", "s", "S"):
19097 setcfg("profile.type", "S" if getcfg("trc") else "s")
19098 if proftype != getcfg("profile.type"):
19099 self.update_profile_type_ctrl()
19100 # Reset profile type to previous value so the handler method will
19101 # recognize a change in profile type and update BPC accordingly
19102 setcfg("profile.type", proftype)
19103 self.profile_type_ctrl_handler(None)
19104 self.testchart_patches_amount.SetLabel(str(patches_amount))
19105 self.update_estimated_measurement_time("testchart")
19106 self.update_profile_name()
19107
19108 def testchart_patch_sequence_ctrl_handler(self, event: wx.Event) -> None:
19109 """Handle changes to the testchart patch sequence control.
19110
19111 Args:
19112 event (wx.Event): The event that triggered this method.
19113 """
19114 sel = self.testchart_patch_sequence_ctrl.Selection
19115 setcfg(
19116 "testchart.patch_sequence",
19117 config.VALID_VALUES["testchart.patch_sequence"][sel],
19118 )
19119 self.profile_settings_changed()
19120 self.update_estimated_measurement_time("testchart")
19121
19122 def create_testchart_btn_handler(self, event: wx.Event) -> None:
19123 """Create a new testchart based on the current settings.
19124
19125 Args:
19126 event (wx.Event): The event that triggered this method.
19127 """
19128 if not hasattr(self, "tcframe"):
19129 self.init_tcframe()
19130 elif not hasattr(self.tcframe, "ti1") or getcfg("testchart.file") not in (
19131 self.tcframe.ti1.filename,
19132 "auto",
19133 ):
19134 self.tcframe.tc_load_cfg_from_ti1(
19135 cfg="testchart.file", parent_set_chart_methodname="set_testchart"
19136 )
19137 setcfg("tc.show", 1)
19138 self.tcframe.Show()
19139 self.tcframe.Raise()
19140
19141 def init_tcframe(self, path: None | str = None) -> None:
19142 """Initialize the testchart editor frame.
19143
19144 Args:
19145 path (None | str, optional): Path to the testchart file. If None,
19146 the default.
19147 """
19148 self.tcframe = TestchartEditor(self, path=path)
19149
19150 def set_default_test_chart(self) -> None:
19151 """Set the default testchart based on the current profile type and quality."""
19152 # print "set_default_testchart", path
19153 if getcfg("profile.type") in ("x", "X"):
19154 # XYZ cLUT
19155 if getcfg("testchart.auto_optimize") < 2:
19156 setcfg("testchart.auto_optimize", 3)
19157 elif getcfg("profile.type") == "l":
19158 # L*a*b* cLUT
19159 if getcfg("testchart.auto_optimize") < 5:
19160 setcfg("testchart.auto_optimize", 5)
19161 elif getcfg("testchart.auto_optimize") > 2:
19162 # Gamma or shaper + matrix
19163 setcfg("testchart.auto_optimize", 1)
19164
19165 def set_default_testchart(self, alert: bool = True, force: bool = False) -> bool:
19166 """Set the default testchart based on the current profile type and quality.
19167
19168 Args:
19169 alert (bool): Whether to show an alert dialog if the testchart is
19170 missing.
19171 force (bool): Whether to force setting the default testchart even
19172 if it is already set.
19173
19174 Returns:
19175 None | bool: True if the testchart was set successfully, False
19176 otherwise. None if the testchart is already set and no
19177 changes were made.
19178 """
19179 path = getcfg("testchart.file")
19180 self.set_default_test_chart()
19181 if path == "auto":
19182 self.set_testchart(path)
19183 return None
19184 if os.path.basename(path) in self.dist_testchart_names:
19185 path = self.dist_testcharts[
19186 self.dist_testchart_names.index(os.path.basename(path))
19187 ]
19188 debug_print("[D] set_default_testchart testchart.file:", path)
19189 setcfg("testchart.file", path)
19190 if (
19191 not force
19192 and (
19193 lang.getstr(os.path.basename(path))
19194 in ["", *self.default_testchart_names]
19195 )
19196 and os.path.isfile(path)
19197 ):
19198 return None
19199 if not force and lang.getstr(os.path.basename(path)) in [
19200 "",
19201 *self.default_testchart_names,
19202 ]:
19203 ti1 = os.path.basename(path)
19204 else:
19205 ti1 = self.testchart_defaults[self.get_profile_type()].get(
19206 self.get_profile_quality(),
19207 self.testchart_defaults[self.get_profile_type()][None],
19208 )
19209 if ti1 == "auto":
19210 path = ti1
19211 else:
19212 path = get_data_path(os.path.join("ti1", ti1))
19213 if not path or not os.path.isfile(path):
19214 if alert:
19215 InfoDialog(
19216 self,
19217 msg=lang.getstr("error.testchart.missing", ti1),
19218 ok=lang.getstr("ok"),
19219 bitmap=get_icon(32, "dialog-error"),
19220 )
19221 elif VERBOSE >= 1:
19222 print(lang.getstr("error.testchart.missing", ti1))
19223 return False
19224 self.set_testchart(path)
19225 return True
19226
19227 def set_testcharts(self, path: None | str = None) -> None:
19228 """Set the testchart control items from the given path or use default.
19229
19230 Args:
19231 path (None | str, optional): Path to the testchart file. If None,
19232 the default testchart will be used.
19233 """
19234 idx = self.testchart_ctrl.GetSelection()
19235 self.testchart_ctrl.Freeze()
19236 self.testchart_ctrl.SetItems(self.get_testchart_names(path))
19237 self.testchart_ctrl.SetSelection(idx)
19238 self.testchart_ctrl.Thaw()
19239
19240 def set_testchart(
19241 self, path: None | str = None, update_profile_name: bool = True
19242 ) -> None:
19243 """Set the testchart to a given path or the default testchart.
19244
19245 Args:
19246 path (str): Path to the testchart file. If None, the default
19247 testchart will be used.
19248 update_profile_name (bool): Whether to update the profile name
19249 after setting the testchart.
19250 """
19251 if path is None:
19252 path = getcfg("testchart.file")
19253 filename, ext = os.path.splitext(path)
19254 ti1_path = f"{filename}.ti1"
19255 if (
19256 ext.lower() in (".icc", ".icm")
19257 and getcfg("testchart.patch_sequence") != "optimize_display_response_delay"
19258 and os.path.isfile(ti1_path)
19259 ):
19260 # Use actual testchart file so choosing the default patch
19261 # sequence of optimizing response delay will actually work
19262 # (because the ti1 is guaranteed to be in that sequence if created
19263 # via targen by DisplayCAL)
19264 path = ti1_path
19265 # print "set_testchart", path
19266 if path == "auto" and config.get_display_name() == "Untethered":
19267 self._current_testchart_path = path
19268 if self.IsShown():
19269 wx.CallAfter(
19270 show_result_dialog,
19271 UnloggedInfo(
19272 lang.getstr("testchart.auto_optimize.untethered.unsupported")
19273 ),
19274 self,
19275 )
19276 path = getcfg("calibration.file", False)
19277 if not path or path.lower().endswith(".cal"):
19278 path = DEFAULTS["testchart.file"]
19279 self.create_testchart_btn.Enable(
19280 path != "auto" and not getcfg("profile.update")
19281 )
19282 self.menuitem_testchart_edit.Enable(self.create_testchart_btn.Enabled)
19283 self.testchart_patches_amount_label.Show(path == "auto")
19284 self.testchart_patches_amount_ctrl.Show(path == "auto")
19285 if path == "auto":
19286 if path != getcfg("testchart.file"):
19287 self.profile_settings_changed()
19288 setcfg("testchart.file", path)
19289 if path not in self.testcharts:
19290 self.set_testcharts(path)
19291 self.testchart_ctrl.SetSelection(0)
19292 self.testchart_ctrl.SetToolTipString("")
19293 self.worker.options_targen = ["-d3"]
19294 auto = getcfg("testchart.auto_optimize") or 7
19295 self.testchart_patches_amount_ctrl.SetValue(auto)
19296 self.testchart_patches_amount_ctrl_handler(None)
19297 self._current_testchart_path = path
19298 else:
19299 self.set_testchart_from_path(path)
19300 self.check_testchart()
19301 if update_profile_name:
19302 self.update_profile_name()
19303
19304 def set_testchart_from_path(self, path: str) -> None:
19305 """Set the testchart from a given path.
19306
19307 Args:
19308 path (str): Path to the testchart file.
19309 """
19310 result = check_file_isfile(path)
19311 if isinstance(result, Exception):
19312 show_result_dialog(result, self)
19313 self.set_default_testchart(force=True)
19314 return
19315 if getattr(self, "_current_testchart_path", None) == path:
19316 # Nothing to do
19317 return
19318 try:
19319 self.load_testchart_from_file(path)
19320 except Exception as exception:
19321 error = traceback.format_exc() if DEBUG else exception
19322 InfoDialog(
19323 self,
19324 msg=lang.getstr("error.testchart.read", path) + "\n\n" + str(error),
19325 ok=lang.getstr("ok"),
19326 bitmap=get_icon(32, "dialog-error"),
19327 )
19328 self.set_default_testchart(force=True)
19329 else:
19330 self.update_estimated_measurement_time("testchart")
19331 if (
19332 hasattr(self, "tcframe")
19333 and self.tcframe.IsShownOnScreen()
19334 and (
19335 not hasattr(self.tcframe, "ti1")
19336 or getcfg("testchart.file") != self.tcframe.ti1.filename
19337 )
19338 ):
19339 self.tcframe.tc_load_cfg_from_ti1(
19340 cfg="testchart.file", parent_set_chart_methodname="set_testchart"
19341 )
19342
19343 def load_testchart_from_file(self, path: str) -> None:
19344 """Load the testchart from a file and verify its contents.
19345
19346 Args:
19347 path (str): Path to the testchart file.
19348 """
19349 ext = os.path.splitext(path)[-1]
19350 if ext.lower() in (".ti1", ".ti3"):
19351 if ext.lower() == ".ti3":
19352 with open(path, "rb") as f:
19353 ti3_data = f.read()
19354 ti1 = CGATS(ti3_to_ti1(ti3_data))
19355 else:
19356 ti1 = CGATS(path)
19357 else: # icc or icm profile
19358 profile = ICCProfile(path)
19359 ti1 = CGATS(
19360 ti3_to_ti1(profile.tags.get("CIED", "") or profile.tags.get("targ", ""))
19361 )
19362 try:
19363 verify_ti1_rgb_xyz(ti1)
19364 except CGATSError as exception:
19365 msg = {
19366 CGATSKeyError: lang.getstr(
19367 "error.testchart.missing_fields",
19368 (path, "RGB_R, RGB_G, RGB_B, XYZ_X, XYZ_Y, XYZ_Z"),
19369 )
19370 }.get(
19371 exception.__class__,
19372 lang.getstr("error.testchart.invalid", path)
19373 + "\n"
19374 + lang.getstr(str(exception)),
19375 )
19376
19377 InfoDialog(
19378 self,
19379 msg=msg,
19380 ok=lang.getstr("ok"),
19381 bitmap=get_icon(32, "dialog-error"),
19382 )
19383 self.set_default_testchart(force=True)
19384 return
19385 if path != getcfg("calibration.file", False):
19386 self.profile_settings_changed()
19387 debug_print("[D] set_testchart testchart.file:", path)
19388 setcfg("testchart.file", path)
19389 if path not in self.testcharts:
19390 self.set_testcharts(path)
19391 # The case-sensitive index could fail because of
19392 # case insensitive file systems, e.g. if the
19393 # stored filename string is
19394 # "C:\Users\Name\AppData\DisplayCAL\storage\MyFile"
19395 # but the actual filename is
19396 # "C:\Users\Name\AppData\DisplayCAL\storage\myfile"
19397 # (maybe because the user renamed the file)
19398 idx = index_fallback_ignorecase(self.testcharts, path)
19399 self.testchart_ctrl.SetSelection(idx)
19400 self.testchart_ctrl.SetToolTipString(path)
19401 if ti1.queryv1("COLOR_REP") and ti1.queryv1("COLOR_REP")[:3] == "RGB":
19402 self.worker.options_targen = ["-d3"]
19403 self.testchart_patches_amount.SetLabel(str(ti1.queryv1("NUMBER_OF_SETS")))
19404 self._current_testchart_path = path
19405
19406 def check_testchart(self) -> None:
19407 """Check if the current testchart is valid and update controls accordingly."""
19408 if is_ccxx_testchart():
19409 self.set_ccxx_measurement_mode()
19410 else:
19411 self.restore_measurement_mode()
19412 self.update_colorimeter_correction_matrix_ctrl()
19413 if not self.updatingctrls:
19414 self.update_main_controls()
19415
19416 def get_testchart_names(self, path: None | str = None) -> list[str]:
19417 """Get names of available testcharts.
19418
19419 Args:
19420 path (str, optional): Path to the testchart file. If None, uses
19421 the value from the configuration setting "testchart.file".
19422
19423 Returns:
19424 list: List of testchart names.
19425 """
19426 testchart_names = []
19427 self.testcharts = []
19428 if path is None:
19429 path = getcfg("testchart.file")
19430 # print "get_testchart_names", path
19431 if path != "auto" and os.path.exists(path):
19432 testchart_dir = os.path.dirname(path)
19433 try:
19434 testcharts = listdir_re(
19435 testchart_dir,
19436 re.escape(os.path.splitext(os.path.basename(path))[0])
19437 + r"\.(?:icc|icm|ti1|ti3)$",
19438 )
19439 except Exception as exception:
19440 print(
19441 f"Error - directory '{testchart_dir}' listing failed: {exception}"
19442 )
19443 else:
19444 for testchart_name in testcharts:
19445 if testchart_name not in testchart_names:
19446 testchart_names.append(testchart_name)
19447 self.testcharts.append(
19448 os.pathsep.join((testchart_name, testchart_dir))
19449 )
19450 default_testcharts = get_data_path("ti1", r"\.(?:icc|icm|ti1|ti3)$")
19451 if isinstance(default_testcharts, list):
19452 for testchart in default_testcharts:
19453 testchart_dir = os.path.dirname(testchart)
19454 testchart_name = os.path.basename(testchart)
19455 if testchart_name not in testchart_names:
19456 testchart_names.append(testchart_name)
19457 self.testcharts.append(
19458 os.pathsep.join((testchart_name, testchart_dir))
19459 )
19460 self.testcharts = ["auto", *natsort(self.testcharts)]
19461 self.testchart_names = []
19462 for i, chart in enumerate(self.testcharts):
19463 chart = chart.split(os.pathsep)
19464 chart.reverse()
19465 self.testcharts[i] = os.path.join(*chart)
19466 testchart_name = "auto_optimized" if chart[-1] == "auto" else chart[-1]
19467 self.testchart_names.append(lang.getstr(testchart_name))
19468 return self.testchart_names
19469
19470 def set_argyll_bin_handler(
19471 self,
19472 event: wx.Event,
19473 silent: bool = False,
19474 callafter: None | Callable = None,
19475 callafter_args: tuple = (),
19476 ) -> None:
19477 """Set Argyll CMS binary executables directory.
19478
19479 Args:
19480 event (wx.Event): Event that triggered the handler.
19481 silent (bool): If True, do not show progress dialog.
19482 callafter (callable, optional): Function to call after setting the
19483 Argyll CMS binary directory.
19484 callafter_args (tuple, optional): Arguments to pass to the
19485 callable.
19486 """
19487 if (
19488 (getattr(self.worker, "thread", None) and self.worker.thread.is_alive())
19489 or not self.Shown
19490 or not self.Enabled
19491 or get_dialogs()
19492 ):
19493 wx.Bell()
19494 return
19495 if (event and set_argyll_bin(self, silent, callafter, callafter_args)) or (
19496 not event and check_argyll_bin()
19497 ):
19498 self.check_update_controls(
19499 True, callafter=callafter, callafter_args=callafter_args
19500 )
19501 if sys.platform == "win32":
19502 self.send_command(
19503 "apply-profiles",
19504 'setcfg argyll.dir "{}" force'.format(getcfg("argyll.dir")),
19505 )
19506
19507 def check_update_controls(
19508 self,
19509 event: None | wx.Event = None,
19510 silent: bool = False,
19511 callafter: None | Callable = None,
19512 callafter_args: tuple = (),
19513 ) -> bool:
19514 """Update controls and menu items when displays or instruments change.
19515
19516 Return True if update was needed and carried out, False otherwise.
19517
19518 Args:
19519 event (wx.Event, optional): Event that triggered the update.
19520 silent (bool): If True, do not show progress dialog.
19521 callafter (callable, optional): Function to call after the update.
19522 callafter_args (tuple, optional): Arguments to pass to the callable.
19523
19524 Returns:
19525 bool: True if update was needed and carried out, False otherwise.
19526 """
19527 if (
19528 self.worker.is_working()
19529 or not self.Shown
19530 or not self.Enabled
19531 or get_dialogs()
19532 ):
19533 return False
19534 argyll_bin_dir = self.worker.argyll_bin_dir
19535 argyll_version = list(self.worker.argyll_version)
19536 displays = list(self.worker.displays)
19537 comports = list(self.worker.instruments)
19538 if event:
19539 enumerate_ports = not isinstance(event, wx.DisplayChangedEvent)
19540 else:
19541 # Use configured value
19542 enumerate_ports = getcfg("enumerate_ports.auto")
19543 if not event and not silent:
19544 self.worker.enumerate_displays_and_ports(
19545 silent, enumerate_ports=enumerate_ports
19546 )
19547 return self.check_update_controls_consumer(
19548 True,
19549 argyll_bin_dir,
19550 argyll_version,
19551 displays,
19552 comports,
19553 event,
19554 callafter,
19555 callafter_args,
19556 )
19557
19558 args = (
19559 self.check_update_controls_consumer,
19560 self.check_update_controls_producer,
19561 )
19562 kwargs = {
19563 "cargs": (
19564 argyll_bin_dir,
19565 argyll_version,
19566 displays,
19567 comports,
19568 event,
19569 callafter,
19570 callafter_args,
19571 ),
19572 "wkwargs": {
19573 "silent": True,
19574 "enumerate_ports": enumerate_ports,
19575 "displays": displays,
19576 "profile_loader_load_cal": isinstance(event, wx.DisplayChangedEvent),
19577 },
19578 }
19579 if silent:
19580 self.thread = delayedresult.startWorker(*args, **kwargs)
19581 else:
19582 kwargs["progress_msg"] = lang.getstr("enumerating_displays_and_comports")
19583 kwargs["stop_timers"] = False
19584 kwargs["show_remaining_time"] = False
19585 kwargs["fancy"] = False
19586 self.worker.start(*args, **kwargs)
19587
19588 return None
19589
19590 def check_update_controls_producer(
19591 self,
19592 silent: bool = False,
19593 enumerate_ports: bool = True,
19594 displays: None | list = None,
19595 profile_loader_load_cal: bool = False,
19596 ) -> delayedresult.DelayedResult:
19597 """Produce results for check_update_controls.
19598
19599 Args:
19600 silent (bool, optional): If True, do not show progress dialog.
19601 enumerate_ports (bool, optional): If True, enumerate comports.
19602 displays (list, optional): List of detected displays.
19603 profile_loader_load_cal (bool, optional): If True, load calibration
19604 profiles when display changes are detected.
19605
19606 Returns:
19607 delayedresult.DelayedResult: Result of the enumeration.
19608 """
19609 result = self.worker.enumerate_displays_and_ports(
19610 silent, enumerate_ports=enumerate_ports
19611 )
19612 if (
19613 sys.platform == "win32"
19614 and displays != self.worker.displays
19615 and profile_loader_load_cal
19616 and not util_win.calibration_management_isenabled()
19617 ):
19618 # Tell profile loader to load calibration
19619 self.send_command("apply-profiles", "apply-profiles display-changed")
19620 return result
19621
19622 def check_update_controls_consumer(
19623 self,
19624 result: delayedresult.DelayedResult | Exception,
19625 argyll_bin_dir: str,
19626 argyll_version: list,
19627 displays: list,
19628 comports: list,
19629 event: None | wx.Event = None,
19630 callafter: None | Callable = None,
19631 callafter_args: None | tuple = None,
19632 ) -> bool:
19633 """Consumer for check_update_controls_producer.
19634
19635 Args:
19636 result (delayedresult.DelayedResult or Exception): Result from the worker.
19637 argyll_bin_dir (str): Argyll CMS binary directory.
19638 argyll_version (list): Argyll CMS version as a list.
19639 displays (list): List of detected displays.
19640 comports (list): List of detected comports.
19641 event (wx.Event, optional): Event that triggered the update.
19642 callafter (callable, optional): Function to call after the update.
19643 callafter_args (tuple, optional): Arguments to pass to the callable.
19644
19645 Returns:
19646 bool: True if update was needed and carried out, False otherwise.
19647 """
19648 result = self.process_delayed_result(result)
19649 if isinstance(result, Exception):
19650 raise result
19651 self.update_argyll_configuration(argyll_bin_dir, argyll_version, comports)
19652 if displays != self.worker.displays:
19653 self.update_displays(update_ccmx_items=True)
19654 verbose_print(lang.getstr("display_detected"))
19655 if comports != self.worker.instruments:
19656 self.update_comports()
19657 verbose_print(lang.getstr("comport_detected"))
19658 if event and not callafter:
19659 # Check if we should import colorimeter corrections
19660 # or other instrument setup
19661 self.check_instrument_setup()
19662 if displays != self.worker.displays or comports != self.worker.instruments:
19663 if self.IsShownOnScreen():
19664 self.update_menus()
19665 self.update_main_controls()
19666 returnvalue = True
19667 else:
19668 returnvalue = False
19669 if len(self.worker.displays):
19670 if getcfg("calibration.file", False):
19671 # Load LUT curves from last used .cal file
19672 self.load_cal(silent=True)
19673 else:
19674 # Load LUT curves from current display profile (if any,
19675 # and if it contains curves)
19676 self.load_display_profile_cal(None)
19677 callafter(*callafter_args) if callafter else None
19678 return returnvalue
19679
19680 def process_delayed_result(
19681 self, result: delayedresult.DelayedResult | Exception
19682 ) -> delayedresult.DelayedResult | Error:
19683 """Process the result from a delayed operation.
19684
19685 Args:
19686 result (delayedresult.DelayedResult | Exception): The result to
19687 process.
19688 """
19689 if isinstance(result, delayedresult.DelayedResult):
19690 try:
19691 result.get()
19692 except Exception as exception:
19693 if hasattr(exception, "originalTraceback"):
19694 error = exception.originalTraceback
19695 else:
19696 error = traceback.format_exc()
19697 result = Error(error)
19698 return result
19699
19700 def update_argyll_configuration(
19701 self,
19702 argyll_bin_dir: str,
19703 argyll_version: list,
19704 comports: list,
19705 ) -> None:
19706 """Update Argyll CMS configuration based on detected binaries and version.
19707
19708 Args:
19709 argyll_bin_dir (str): Path to the Argyll CMS binary directory.
19710 argyll_version (list): List containing the Argyll CMS version.
19711 comports (list): List of detected comports.
19712 """
19713 if (
19714 argyll_bin_dir == self.worker.argyll_bin_dir
19715 and argyll_version == self.worker.argyll_version
19716 ):
19717 return
19718 self.show_advanced_options_handler()
19719 self.worker.measurement_modes = {}
19720 self.update_measurement_modes()
19721 if comports == self.worker.instruments:
19722 self.update_colorimeter_correction_matrix_ctrl()
19723 self.update_black_point_rate_ctrl()
19724 self.update_drift_compensation_ctrls()
19725 self.setup_observer_ctrl()
19726 self.update_observer_ctrl()
19727 self.update_profile_type_ctrl_items()
19728 self.update_profile_type_ctrl()
19729 self.lut3d_setup_language()
19730 self.lut3d_init_input_profiles()
19731 self.lut3d_update_controls()
19732 self.aboutdialog_handler(None) if hasattr(
19733 self, "aboutdialog"
19734 ) and self.aboutdialog.IsShownOnScreen() else None
19735 self.extra_args.update_controls() if hasattr(self, "extra_args") else None
19736 if hasattr(self, "gamapframe"):
19737 visible = self.gamapframe.IsShownOnScreen()
19738 self.gamapframe.Close()
19739 self.gamapframe.Destroy()
19740 del self.gamapframe
19741 self.gamap_btn_handler(None) if visible else None
19742 if getattr(self, "lut3dframe", None):
19743 visible = self.lut3dframe.IsShownOnScreen()
19744 self.lut3dframe.Close()
19745 self.lut3dframe.Destroy()
19746 del self.lut3dframe
19747 self.lut3d_create_handler(None) if visible else None
19748 if getattr(self, "reportframe", None):
19749 visible = self.reportframe.IsShownOnScreen()
19750 self.reportframe.Close()
19751 self.reportframe.Destroy()
19752 del self.reportframe
19753 self.measurement_report_create_handler(None) if visible else None
19754 if hasattr(self, "tcframe"):
19755 visible = self.tcframe.IsShownOnScreen()
19756 self.tcframe.tc_close_handler()
19757 self.tcframe.Destroy()
19758 del self.tcframe
19759 self.create_testchart_btn_handler(None) if visible else None
19760
19761 def check_instrument_setup(
19762 self, callafter: None | Callable = None, callafter_args: tuple = ()
19763 ) -> None:
19764 """Check if colorimeter corrections should be imported.
19765
19766 Or do other instrument specific setup.
19767
19768 Args:
19769 callafter (callable, optional): Function to call after the setup check.
19770 callafter_args (tuple, optional): Arguments to pass to the callable.
19771 """
19772 # Check if we should import colorimeter corrections
19773 # or do other instrument specific setup
19774 if (
19775 self.worker.is_working()
19776 or not self.Shown
19777 or not self.Enabled
19778 or get_dialogs()
19779 ):
19780 return
19781 if getcfg("colorimeter_correction_matrix_file") in ("AUTO:", ""):
19782 # Check for applicable corrections
19783 ccmx_instruments = iter(self.ccmx_instruments.values())
19784 i1d3 = (
19785 "i1 DisplayPro, ColorMunki Display" in self.worker.instruments
19786 and "" not in ccmx_instruments
19787 )
19788 icd = (
19789 ("DTP94" in self.worker.instruments and "DTP94" not in ccmx_instruments)
19790 or (
19791 "i1 Display 2" in self.worker.instruments
19792 and "i1 Display 2" not in ccmx_instruments
19793 )
19794 or (
19795 "Spyder2" in self.worker.instruments
19796 and "Spyder2" not in ccmx_instruments
19797 )
19798 or (
19799 "Spyder3" in self.worker.instruments
19800 and "Spyder3" not in ccmx_instruments
19801 )
19802 )
19803 else:
19804 # Already using a suitable correction
19805 i1d3 = False
19806 icd = False
19807 spyd2 = (
19808 "Spyder2" in self.worker.instruments
19809 and not self.worker.spyder2_firmware_exists()
19810 )
19811 spyd4 = (
19812 "Spyder4" in self.worker.instruments or "Spyder5" in self.worker.instruments
19813 ) and not self.worker.spyder4_cal_exists()
19814 if spyd2:
19815 spyd2 = self.enable_spyder2_handler(
19816 True,
19817 i1d3 or icd or spyd4,
19818 callafter=callafter,
19819 callafter_args=callafter_args,
19820 )
19821 result = spyd2
19822 if not spyd2 and (i1d3 or icd or spyd4):
19823 result = self.import_colorimeter_corrections_handler(
19824 True, callafter=callafter, callafter_args=callafter_args
19825 )
19826 if not result and callafter:
19827 callafter(*callafter_args)
19828
19829 def load_cal_handler(
19830 self,
19831 event: wx.Event,
19832 path: None | str = None,
19833 update_profile_name: bool = True,
19834 silent: bool = False,
19835 load_vcgt: bool = True,
19836 ) -> None:
19837 """Load settings and calibration.
19838
19839 Args:
19840 event (wx.Event): The event that triggered this method.
19841 path (str, optional): Path to the calibration file. If None, a file
19842 dialog will be shown to select a file. Defaults to None.
19843 update_profile_name (bool, optional): Whether to update the profile
19844 name after loading the calibration. Defaults to True.
19845 silent (bool, optional): If True, suppresses dialog messages.
19846 Defaults to False.
19847 load_vcgt (bool, optional): If True, loads the VCGT from the
19848 calibration file.
19849 """
19850 if not check_set_argyll_bin():
19851 return
19852
19853 if path is None:
19854 path = self.get_calibration_file_path()
19855
19856 if not path:
19857 return
19858
19859 if getcfg("settings.changed"):
19860 return
19861
19862 if not os.path.exists(path):
19863 self.remove_missing_calibration(path)
19864 return
19865
19866 is_preset = path in self.presets
19867 basename = os.path.basename(path)
19868 is_3dlut_preset = is_preset and basename.startswith("video_")
19869
19870 ext = os.path.splitext(path)[-1]
19871 if ext.lower() in COMPRESSED_FILE_EXTENSIONS:
19872 self.import_session_archive(path)
19873 return
19874
19875 profile, ti3_lines = self.parse_calibration_file(path)
19876 if ti3_lines is None:
19877 return
19878 setcfg("last_cal_or_icc_path", path)
19879 update_ccmx_items = True
19880 set_size = True
19881 display_match = False
19882 display_changed = False
19883 instrument_id = None
19884 instrument_match = False
19885 if ext.lower() in ICCPROFILE_FILE_EXTENSIONS:
19886 setcfg("last_icc_path", path)
19887 if path not in self.presets:
19888 setcfg("3dlut.output.profile", path)
19889 setcfg("measurement_report.output_profile", path)
19890 # Disable 3D LUT tab when switching from madVR / Resolve
19891 setcfg("3dlut.tab.enable", 0)
19892 setcfg("3dlut.tab.enable.backup", 0)
19893 (options_dispcal, options_colprof) = get_options_from_profile(profile)
19894 # Get and set the display
19895 # First try to find the correct display by comparing
19896 # the model (if present)
19897 display_name = profile.getDeviceModelDescription()
19898 # Second try to find the correct display by comparing
19899 # the EDID hash (if present)
19900 profile_tags_meta = profile.tags.get("meta", {})
19901 edid_md5 = profile_tags_meta.get("EDID_md5", {}).get("value")
19902 if display_name or edid_md5:
19903 display_name_indexes = []
19904 edid_md5_indexes = []
19905 for i, edid in enumerate(self.worker.display_edid):
19906 if display_name in (
19907 edid.get(b"monitor_name", False),
19908 self.worker.display_names[i],
19909 ):
19910 display_name_indexes.append(i)
19911 if edid_md5 == edid.get(b"hash", False):
19912 edid_md5_indexes.append(i)
19913
19914 if len(display_name_indexes) == 1:
19915 display_index = display_name_indexes[0]
19916 print(
19917 "Found display device matching model description at "
19918 f"index #{display_index:.0f}"
19919 )
19920 elif len(edid_md5_indexes) == 1:
19921 display_index = edid_md5_indexes[0]
19922 print(
19923 "Found display device matching EDID MD5 at index "
19924 f"#{display_index:.0f}"
19925 )
19926 else:
19927 # We got several matches. As we can't be sure which
19928 # is the right one, do nothing.
19929 display_index = None
19930
19931 if display_index is not None:
19932 # Found it
19933 display_match = True
19934 if config.get_display_name(None, False) != config.get_display_name(
19935 display_index, False
19936 ):
19937 # Only need to update if currently selected display
19938 # does not match found one
19939 setcfg("display.number", display_index + 1)
19940 self.get_set_display()
19941 display_changed = True
19942
19943 if (
19944 config.is_virtual_display()
19945 or config.get_display_name() == "SII REPEATER"
19946 ):
19947 # Don't disable 3D LUT tab when switching from
19948 # madVR / Resolve / eeColor
19949 setcfg("3dlut.tab.enable", 1)
19950 setcfg("3dlut.tab.enable.backup", 1)
19951 # Get and set the instrument
19952 instrument_id = (
19953 profile.tags.get("meta", {}).get("MEASUREMENT_device", {}).get("value")
19954 )
19955 if instrument_id:
19956 for i, instrument in enumerate(self.worker.instruments):
19957 if instrument.lower() == instrument_id:
19958 # Found it
19959 instrument_match = True
19960 if self.worker.get_instrument_name().lower() == instrument_id:
19961 # No need to update anything
19962 break
19963 setcfg("comport.number", i + 1)
19964 self.update_comports()
19965 # No need to update ccmx items in update_controls,
19966 # as comport_ctrl_handler took care of it
19967 update_ccmx_items = False
19968 # comport_ctrl_handler already called set_size
19969 set_size = False
19970 break
19971 else:
19972 try:
19973 options_dispcal, options_colprof = get_options_from_cal(path)
19974 except (OSError, CGATSError):
19975 InfoDialog(
19976 self,
19977 msg="{}\n{}".format(lang.getstr("calibration.file.invalid"), path),
19978 ok=lang.getstr("ok"),
19979 bitmap=get_icon(32, "dialog-error"),
19980 )
19981 return
19982 black_point_correction = False
19983 if options_dispcal or options_colprof:
19984 debug_print("[D] options_dispcal:", options_dispcal)
19985 debug_print("[D] options_colprof:", options_colprof)
19986 ccxxsetting = getcfg("colorimeter_correction_matrix_file").split(":", 1)[0]
19987 ccmx = None
19988 # Check if TRC was set
19989 trc = False
19990 if options_dispcal:
19991 for option in options_dispcal:
19992 if option[0:1] in ("g", "G"):
19993 trc = True
19994 # Restore defaults
19995 self.restore_defaults_handler(
19996 include=(
19997 "calibration",
19998 "drift_compensation",
19999 "measure.darken_background",
20000 "measure.override_min_display_update_delay_ms",
20001 "measure.min_display_update_delay_ms",
20002 "measure.override_display_settle_time_mult",
20003 "measure.display_settle_time_mult",
20004 "observer",
20005 "patterngenerator.ffp_insertion",
20006 "trc",
20007 "whitepoint",
20008 ),
20009 exclude=(
20010 "calibration.black_point_correction_choice.show",
20011 "calibration.update",
20012 "calibration.use_video_lut",
20013 "measure.darken_background.show_warning",
20014 "patterngenerator.ffp_insertion.interval",
20015 "patterngenerator.ffp_insertion.duration",
20016 "patterngenerator.ffp_insertion.level",
20017 "trc.should_use_viewcond_adjust.show_msg",
20018 ),
20019 override={"trc": ""} if not trc else None,
20020 )
20021 # Parse options
20022 if options_dispcal:
20023 self.worker.options_dispcal = [f"-{arg}" for arg in options_dispcal]
20024 for option in options_dispcal:
20025 dispcal_options_to_config_map = {
20026 "d": (
20027 self.set_display_number_config_with_option,
20028 (option, display_match, display_changed),
20029 ("display_match", "display_changed"),
20030 ),
20031 "m": (
20032 self.set_interactive_display_adjustment_config_with_option,
20033 (option,),
20034 (),
20035 ),
20036 # "o": ("profile.update", 1),
20037 # "u": ("calibration.update", 1),
20038 "q": (
20039 self.set_calibration_quality_config_with_option,
20040 (option,),
20041 (),
20042 ),
20043 "y": (
20044 self.set_measurement_mode_config_with_option,
20045 (option,),
20046 (),
20047 ),
20048 "t": (
20049 self.set_whitepoint_temperature_config_with_option,
20050 (option,),
20051 (),
20052 ),
20053 "T": (
20054 self.set_whitepoint_temperature_config_with_option,
20055 (option,),
20056 (),
20057 ),
20058 "W": (self.set_whitepoint_config_with_option, (option,), ()),
20059 "b": (
20060 self.set_calibration_luminance_config_with_option,
20061 (option,),
20062 (),
20063 ),
20064 "g": (
20065 self.set_tone_response_curve_config_with_option,
20066 (option,),
20067 (),
20068 ),
20069 "G": (
20070 self.set_tone_response_curve_config_with_option,
20071 (option,),
20072 (),
20073 ),
20074 "f": (
20075 self.set_calibration_black_output_offset_config_with_option,
20076 (option,),
20077 (),
20078 ),
20079 "a": (
20080 self.set_ambient_view_condition_adjustment_config_with_option,
20081 (option,),
20082 (),
20083 ),
20084 "k": (
20085 self.set_black_point_correction_config_with_option,
20086 (option, black_point_correction),
20087 ("black_point_correction",),
20088 ),
20089 "A": (
20090 self.set_calibration_black_point_rate_config_with_option,
20091 (option,),
20092 (),
20093 ),
20094 "B": (
20095 self.set_calibration_black_luminance_config_with_option,
20096 (option,),
20097 (),
20098 ),
20099 # "p": (self.set_measureframe_config_with_option, (option,), ()), # noqa: E501
20100 "P": (self.set_measureframe_config_with_option, (option,), ()),
20101 "V": (
20102 self.set_measurement_mode_adaptive_config_with_option,
20103 (1,),
20104 (),
20105 ),
20106 "YA": (
20107 self.set_measurement_mode_adaptive_config_with_option,
20108 (0,),
20109 (),
20110 ),
20111 "H": (
20112 self.set_measurement_mode_highres_config_with_option,
20113 (1,),
20114 (),
20115 ),
20116 "p": (
20117 self.set_measurement_mode_projector_config_with_option,
20118 (option,),
20119 (),
20120 ),
20121 "F": (
20122 self.set_measure_darken_background_config_with_option,
20123 (1,),
20124 (),
20125 ),
20126 "X": (
20127 self.set_ccss_config_with_option,
20128 (option, path),
20129 ("ccmx", "update_ccmx_items"),
20130 ),
20131 "I": (
20132 self.set_drift_compensation_config_with_option,
20133 (option,),
20134 (),
20135 ),
20136 "Q": (
20137 self.set_tristimulus_observer_config_with_option,
20138 (option,),
20139 ("update_ccmx_items"),
20140 ),
20141 "E": (self.set_video_levels_config_with_option, (), ()),
20142 }
20143 config_option_data = dispcal_options_to_config_map.get(
20144 option[0:1], dispcal_options_to_config_map.get(option[0:2])
20145 )
20146 if config_option_data is None:
20147 debug_print(
20148 f"Couldn't match data for dispcal options: {option[0:1]}"
20149 )
20150 continue
20151 # we must have a setter function
20152 func = config_option_data[0]
20153 args = config_option_data[1]
20154 local_var_names = config_option_data[2]
20155 return_values = func(*args)
20156 if return_values is not None:
20157 # we have some return values, set locals
20158 for local_var_name, return_value in zip(
20159 local_var_names, return_values
20160 ):
20161 locals()[local_var_name] = return_value
20162
20163 if trc and not black_point_correction:
20164 setcfg("calibration.black_point_correction.auto", 1)
20165 self.update_whitepoint_config_from_temperature()
20166 update_ccmx_items = self.update_ccmx_items_from_path(
20167 ccmx, path, ccxxsetting, update_ccmx_items
20168 )
20169
20170 if options_colprof:
20171 # restore defaults
20172 self.restore_defaults_handler(
20173 include=(
20174 "profile",
20175 "gamap_",
20176 "3dlut.create",
20177 "3dlut.output.profile.apply_cal",
20178 "3dlut.trc",
20179 "testchart.auto_optimize",
20180 "testchart.patch_sequence",
20181 ),
20182 exclude=(
20183 "3dlut.tab.enable.backup",
20184 "profile.update",
20185 "profile.name",
20186 "gamap_default_intent",
20187 ),
20188 )
20189 for option in options_colprof:
20190 colprof_options_to_config_map = {
20191 "q": (
20192 self.set_profile_quality_config_with_option,
20193 (option,),
20194 (),
20195 ),
20196 "b": (
20197 self.set_profile_quality_b2a_config_with_option,
20198 (option,),
20199 (),
20200 ),
20201 "a": (
20202 self.set_profile_black_point_compenstation_config_with_option,
20203 (option, is_preset, is_3dlut_preset),
20204 (),
20205 ),
20206 "s": (self.set_gamap_profile_config_with_option, (option,), ()),
20207 "S": (self.set_gamap_profile_config_with_option, (option,), ()),
20208 "c": (
20209 self.set_gamap_src_viewcond_config_with_option,
20210 (option,),
20211 (),
20212 ),
20213 "d": (
20214 self.set_gamap_out_viewcond_config_with_option,
20215 (option,),
20216 (),
20217 ),
20218 "t": (
20219 self.set_gamap_perceptual_intent_config_with_option,
20220 (option,),
20221 (),
20222 ),
20223 "T": (
20224 self.set_gamap_saturation_intent_config_with_option,
20225 (option,),
20226 (),
20227 ),
20228 }
20229 config_option_data = colprof_options_to_config_map.get(
20230 option[0:1], colprof_options_to_config_map.get(option[0:2])
20231 )
20232 if config_option_data is None:
20233 debug_print(
20234 f"Couldn't match data for colprof options: {option[0:1]}"
20235 )
20236 continue
20237 # we must have a setter function
20238 func = config_option_data[0]
20239 args = config_option_data[1]
20240 local_var_names = config_option_data[2]
20241 return_values = func(*args)
20242 if return_values is not None:
20243 # we have some return values, set locals
20244 for local_var_name, return_value in zip(
20245 local_var_names, return_values
20246 ):
20247 locals()[local_var_name] = return_value
20248
20249 setcfg("calibration.file", path)
20250 if b"CTI3" in ti3_lines:
20251 debug_print("[D] load_cal_handler testchart.file:", path)
20252 setcfg("testchart.file", path)
20253 if b'USE_BLACK_POINT_COMPENSATION "YES"' in ti3_lines:
20254 setcfg("profile.black_point_compensation", 1)
20255 elif b'USE_BLACK_POINT_COMPENSATION "NO"' in ti3_lines and (
20256 sys.platform != "darwin" or not is_preset or is_3dlut_preset
20257 ):
20258 # Only disable BPC if not OS X, or if a preset,
20259 # or if a 3D LUT preset
20260 setcfg("profile.black_point_compensation", 0)
20261 if b'HIRES_B2A "YES"' in ti3_lines:
20262 setcfg("profile.b2a.hires", 1)
20263 elif b'HIRES_B2A "NO"' in ti3_lines:
20264 setcfg("profile.b2a.hires", 0)
20265 if b'SMOOTH_B2A "YES"' in ti3_lines:
20266 if b'HIRES_B2A "NO"' not in ti3_lines:
20267 setcfg("profile.b2a.hires", 1)
20268 setcfg("profile.b2a.hires.smooth", 1)
20269 elif b'SMOOTH_B2A "NO"' in ti3_lines:
20270 if b'HIRES_B2A "YES"' not in ti3_lines:
20271 setcfg("profile.b2a.hires", 0)
20272 setcfg("profile.b2a.hires.smooth", 0)
20273 simset = False # Only HDR 3D LUTs will have this set
20274 if b"BEGIN_DATA_FORMAT" in ti3_lines:
20275 cfgend = ti3_lines.index(b"BEGIN_DATA_FORMAT")
20276 cfgpart = CGATS(b"\n".join(ti3_lines[:cfgend]))
20277 lut3d_trc_set = False
20278 config_mapper = {
20279 "SMOOTH_B2A_SIZE": "profile.b2a.hires.size",
20280 "HIRES_B2A_SIZE": "profile.b2a.hires.size",
20281 # NOTE that profile black point
20282 # correction is not the same
20283 # as calibration black point
20284 # correction!
20285 # See Worker.create_profile in
20286 # worker.py
20287 "BLACK_POINT_CORRECTION": "profile.black_point_correction",
20288 "MIN_DISPLAY_UPDATE_DELAY_MS": (
20289 "measure.min_display_update_delay_ms"
20290 ),
20291 "DISPLAY_SETTLE_TIME_MULT": "measure.display_settle_time_mult",
20292 "FFP_INSERTION_INTERVAL": "patterngenerator.ffp_insertion.interval",
20293 "FFP_INSERTION_DURATION": "patterngenerator.ffp_insertion.duration",
20294 "FFP_INSERTION_LEVEL": "patterngenerator.ffp_insertion.level",
20295 "AUTO_OPTIMIZE": "testchart.auto_optimize",
20296 "PATCH_SEQUENCE": "testchart.patch_sequence",
20297 "3DLUT_SOURCE_PROFILE": "3dlut.input.profile",
20298 "3DLUT_TRC": "3dlut.trc",
20299 "3DLUT_HDR_PEAK_LUMINANCE": "3dlut.hdr_peak_luminance",
20300 "3DLUT_HDR_SAT": "3dlut.hdr_sat",
20301 "3DLUT_HDR_HUE": "3dlut.hdr_hue",
20302 "3DLUT_HDR_DISPLAY": "3dlut.hdr_display",
20303 # MaxCLL is no longer used,
20304 # map to mastering display max light level (MaxMLL)
20305 "3DLUT_HDR_MAXCLL": "3dlut.hdr_maxmll",
20306 "3DLUT_HDR_MAXMLL": "3dlut.hdr_maxmll",
20307 "3DLUT_HDR_MAXMLL_ALT_CLIP": "3dlut.hdr_maxmll_alt_clip",
20308 "3DLUT_HDR_MINMLL": "3dlut.hdr_minmll",
20309 "3DLUT_HDR_AMBIENT_LUMINANCE": "3dlut.hdr_ambient_luminance",
20310 "3DLUT_GAMMA": "3dlut.trc_gamma",
20311 "3DLUT_DEGREE_OF_BLACK_OUTPUT_OFFSET": "3dlut.trc_output_offset",
20312 "3DLUT_INPUT_ENCODING": "3dlut.encoding.input",
20313 "3DLUT_OUTPUT_ENCODING": "3dlut.encoding.output",
20314 "3DLUT_GAMUT_MAPPING_MODE": "3dlut.gamap.use_b2a",
20315 "3DLUT_RENDERING_INTENT": "3dlut.rendering_intent",
20316 "3DLUT_FORMAT": "3dlut.format",
20317 "3DLUT_SIZE": "3dlut.size",
20318 "3DLUT_INPUT_BITDEPTH": "3dlut.bitdepth.input",
20319 "3DLUT_OUTPUT_BITDEPTH": "3dlut.bitdepth.output",
20320 "3DLUT_APPLY_CAL": "3dlut.output.profile.apply_cal",
20321 "SIMULATION_PROFILE": "measurement_report.simulation_profile",
20322 }
20323 for keyword in config_mapper:
20324 cfgname = config_mapper[keyword]
20325 cfgvalue = cfgpart.queryv1(keyword)
20326 if keyword in (
20327 "MIN_DISPLAY_UPDATE_DELAY_MS",
20328 "DISPLAY_SETTLE_TIME_MULT",
20329 ):
20330 backup = getcfg(
20331 f"measure.override_{keyword.lower()}.backup", False
20332 )
20333 if (
20334 cfgvalue is not None
20335 and display_match
20336 and (instrument_match or not instrument_id)
20337 ):
20338 # Only set display update delay if a matching
20339 # display/instrument stored in profile meta
20340 # tag or no instrument ID (i.e. a preset)
20341 if backup is None:
20342 setcfg(
20343 f"measure.override_{keyword.lower()}.backup",
20344 getcfg(f"measure.override_{keyword.lower()}"),
20345 )
20346 setcfg(
20347 f"measure.{keyword.lower()}.backup",
20348 getcfg(f"measure.{keyword.lower()}"),
20349 )
20350 setcfg(f"measure.override_{keyword.lower()}", 1)
20351 elif backup is not None:
20352 setcfg(f"measure.override_{keyword.lower()}", backup)
20353 cfgvalue = getcfg(f"measure.{keyword.lower()}.backup")
20354 setcfg(f"measure.override_{keyword.lower()}.backup", None)
20355 setcfg(f"measure.{keyword.lower()}.backup", None)
20356 elif cfgvalue is not None:
20357 if keyword == "AUTO_OPTIMIZE" and cfgvalue:
20358 setcfg("testchart.file", "auto")
20359 if (
20360 is_preset
20361 and not is_3dlut_preset
20362 and sys.platform == "darwin"
20363 ):
20364 # Profile type forced to matrix due to
20365 # OS X bugs with cLUT profiles. Set
20366 # smallest testchart.
20367 cfgvalue = 1
20368 elif keyword == "PATCH_SEQUENCE":
20369 cfgvalue = cfgvalue.lower().replace(b"_rgb_", b"_RGB_")
20370 elif keyword == "3DLUT_GAMMA":
20371 try:
20372 cfgvalue = float(cfgvalue)
20373 except Exception:
20374 pass
20375 else:
20376 if cfgvalue < 0:
20377 gamma_type = "B"
20378 cfgvalue = abs(cfgvalue)
20379 else:
20380 gamma_type = "b"
20381 setcfg("3dlut.trc_gamma_type", gamma_type)
20382 # Sync measurement report settings
20383 setcfg("measurement_report.trc_gamma_type", gamma_type)
20384 setcfg("measurement_report.apply_black_offset", 0)
20385 setcfg("measurement_report.apply_trc", 1)
20386 elif keyword == "3DLUT_GAMUT_MAPPING_MODE":
20387 cfgvalue = 0 if cfgvalue == b"G" else 1
20388 elif keyword in (
20389 "FFP_INSERTION_INTERVAL",
20390 "FFP_INSERTION_DURATION",
20391 "FFP_INSERTION_LEVEL",
20392 ):
20393 setcfg("patterngenerator.ffp_insertion", 1)
20394 if keyword.startswith("3DLUT"):
20395 setcfg("3dlut.create", 1)
20396 setcfg("3dlut.tab.enable", 1)
20397 setcfg("3dlut.tab.enable.backup", 1)
20398 if cfgvalue is not None:
20399 cfgvalue = (
20400 cfgvalue.decode("utf-8")
20401 if isinstance(cfgvalue, bytes)
20402 else str(cfgvalue)
20403 )
20404 if cfgname.endswith("profile") and (
20405 not os.path.isabs(cfgvalue) or not os.path.isfile(cfgvalue)
20406 ):
20407 if os.path.basename(os.path.dirname(cfgvalue)) == "ref":
20408 # Fall back to ref file if not absolute
20409 # path or not found
20410 cfgvalue = (
20411 get_data_path("ref/" + os.path.basename(cfgvalue))
20412 or cfgvalue
20413 )
20414 elif not os.path.dirname(cfgvalue):
20415 # Use profile dir
20416 cfgvalue = os.path.join(os.path.dirname(path), cfgvalue)
20417 setcfg(cfgname, cfgvalue)
20418 if keyword == "SIMULATION_PROFILE":
20419 # Only HDR 3D LUTs will have this set
20420 simset = True
20421 # Sync measurement report settings
20422 if cfgname == "3dlut.input.profile":
20423 if not simset:
20424 setcfg(
20425 "measurement_report.simulation_profile",
20426 cfgvalue,
20427 )
20428 setcfg("measurement_report.use_simulation_profile", 1)
20429 setcfg(
20430 "measurement_report.use_simulation_profile_as_output",
20431 1,
20432 )
20433 elif cfgname in (
20434 "3dlut.trc_gamma",
20435 "3dlut.trc_output_offset",
20436 ):
20437 cfgname = cfgname.replace("3dlut", "measurement_report")
20438 setcfg(cfgname, cfgvalue)
20439 elif cfgname == "3dlut.format":
20440 if cfgvalue == "madVR" and not simset:
20441 setcfg("3dlut.enable", 1)
20442 if (
20443 cfgvalue == "madVR" and not simset
20444 ) or cfgvalue == "eeColor":
20445 setcfg("measurement_report.use_devlink_profile", 0)
20446 elif cfgname == "3dlut.trc":
20447 lut3d_trc_set = True
20448 # Content color space (currently only used for HDR)
20449 for color in ("white", "red", "green", "blue"):
20450 for coord in "xy":
20451 keyword = (
20452 f"3DLUT_CONTENT_COLORSPACE_{color.upper()}_{coord.upper()}"
20453 )
20454 cfgvalue = cfgpart.queryv1(keyword)
20455 if cfgvalue is None:
20456 continue
20457 cfgvalue = (
20458 cfgvalue.decode("utf-8")
20459 if isinstance(cfgvalue, bytes)
20460 else str(cfgvalue)
20461 )
20462 with contextlib.suppress(ValueError):
20463 cfgvalue = round(float(cfgvalue), 4)
20464 setcfg(
20465 f"3dlut.content.colorspace.{color}.{coord}",
20466 cfgvalue,
20467 )
20468 # Make sure 3D LUT TRC enumeration matches parameters for
20469 # older profiles not containing 3DLUT_TRC
20470 if not lut3d_trc_set:
20471 if (
20472 getcfg("3dlut.trc_gamma_type") == "B"
20473 and getcfg("3dlut.trc_output_offset") == 0
20474 and getcfg("3dlut.trc_gamma") == 2.4
20475 ):
20476 setcfg("3dlut.trc", "bt1886") # BT.1886
20477 elif (
20478 getcfg("3dlut.trc_gamma_type") == "b"
20479 and getcfg("3dlut.trc_output_offset") == 1
20480 and getcfg("3dlut.trc_gamma") == 2.2
20481 ):
20482 setcfg("3dlut.trc", "gamma2.2") # Pure power gamma 2.2
20483 else:
20484 setcfg("3dlut.trc", "customgamma") # Custom
20485 if not display_changed:
20486 self.update_menus()
20487 if not update_ccmx_items:
20488 self.update_estimated_measurement_time("cal")
20489 self.lut3d_set_path()
20490 if config.get_display_name() == "Resolve":
20491 setcfg("3dlut.enable", 0)
20492 setcfg("measurement_report.use_devlink_profile", 1)
20493 elif config.get_display_name(None, True) == "Prisma":
20494 setcfg("3dlut.enable", 1)
20495 setcfg("measurement_report.use_devlink_profile", 0)
20496 if getcfg("3dlut.format") == "madVR" and simset:
20497 # Currently, it is not possible to verify HDR 3D LUTs
20498 # through madVR in another way
20499 setcfg("3dlut.enable", 0)
20500 setcfg("measurement_report.use_devlink_profile", 1)
20501 self.update_controls(
20502 update_profile_name=update_profile_name,
20503 update_ccmx_items=update_ccmx_items,
20504 )
20505 if set_size:
20506 self.set_size(True)
20507 writecfg()
20508
20509 if ext.lower() in ICCPROFILE_FILE_EXTENSIONS:
20510 if load_vcgt:
20511 # load calibration into lut
20512 self.load_cal(silent=True)
20513 if options_dispcal and options_colprof:
20514 return
20515 if options_dispcal:
20516 msg = lang.getstr("settings_loaded.cal_and_lut")
20517 else:
20518 msg = lang.getstr("settings_loaded.profile_and_lut")
20519 elif options_dispcal and options_colprof:
20520 msg = lang.getstr("settings_loaded.cal_and_profile")
20521 elif options_dispcal:
20522 if not load_vcgt:
20523 msg = lang.getstr("settings_loaded.cal")
20524 else:
20525 # load calibration into lut
20526 self.load_cal(silent=True)
20527 msg = lang.getstr("settings_loaded.cal_and_lut")
20528 else:
20529 msg = lang.getstr("settings_loaded.profile")
20530
20531 # if not silent:
20532 # InfoDialog(self, msg=msg + "\n" + path, ok=lang.getstr("ok"),
20533 # bitmap=get_icon(32, "dialog-information"))
20534 return
20535
20536 if ext.lower() in ICCPROFILE_FILE_EXTENSIONS:
20537 sel = self.calibration_file_ctrl.GetSelection()
20538 if len(self.recent_cals) > sel and self.recent_cals[sel] == path:
20539 self.recent_cals.remove(self.recent_cals[sel])
20540 self.calibration_file_ctrl.Delete(sel)
20541 cal = getcfg("calibration.file", False) or ""
20542 if cal not in self.recent_cals:
20543 self.recent_cals.append(cal)
20544 # The case-sensitive index could fail because of
20545 # case insensitive file systems, e.g. if the
20546 # stored filename string is
20547 # "C:\Users\Name\AppData\DisplayCAL\storage\MyFile"
20548 # but the actual filename is
20549 # "C:\Users\Name\AppData\DisplayCAL\storage\myfile"
20550 # (maybe because the user renamed the file)
20551 idx = index_fallback_ignorecase(self.recent_cals, cal)
20552 self.calibration_file_ctrl.SetSelection(idx)
20553 if not silent:
20554 InfoDialog(
20555 self,
20556 msg=lang.getstr("no_settings") + "\n" + path,
20557 ok=lang.getstr("ok"),
20558 bitmap=get_icon(32, "dialog-error"),
20559 )
20560 return
20561
20562 # Old .cal file without ARGYLL_DISPCAL_ARGS section
20563
20564 setcfg("last_cal_path", path)
20565
20566 # Restore defaults
20567 self.restore_defaults_handler(
20568 include=(
20569 "calibration",
20570 "profile.update",
20571 "measure.override_min_display_update_delay_ms",
20572 "measure.min_display_update_delay_ms",
20573 "measure.override_display_settle_time_mult",
20574 "measure.display_settle_time_mult",
20575 "trc",
20576 "whitepoint",
20577 ),
20578 exclude=(
20579 "calibration.black_point_correction_choice.show",
20580 "calibration.update",
20581 "trc.should_use_viewcond_adjust.show_msg",
20582 ),
20583 )
20584
20585 self.worker.options_dispcal = []
20586 settings = []
20587 # NOTE: ``ti3_lines`` are ``bytes`` (``parse_calibration_file`` opens
20588 # non-ICC files in binary mode), so every keyword comparison below
20589 # must use ``bytes`` literals, and every value must be decoded before
20590 # being handed to ``str``-only helpers like ``stripzeros``. This
20591 # branch previously compared ``bytes`` keys/values against ``str``
20592 # literals (never true in Python 3) and read ``value.lower()[0]``
20593 # (an ``int`` on ``bytes``, not a one-character string) -- both
20594 # latent bugs that made this whole legacy-``.cal``-file path dead
20595 # code (or, for ``BLACK_POINT_CORRECTION``, a ``TypeError`` crash via
20596 # ``stripzeros(value) >= 0`` comparing a ``str`` to an ``int``).
20597 for line in ti3_lines:
20598 line = line.strip().split(b" ", 1)
20599 if len(line) > 1:
20600 value = line[1][1:-1].decode("utf-8", "replace") # strip quotes
20601 if line[0] == b"DEVICE_CLASS":
20602 if value != "DISPLAY":
20603 InfoDialog(
20604 self,
20605 msg=lang.getstr("calibration.file.invalid") + "\n" + path,
20606 ok=lang.getstr("ok"),
20607 bitmap=get_icon(32, "dialog-error"),
20608 )
20609 return
20610 elif line[0] == b"DEVICE_TYPE":
20611 measurement_mode = value.lower()[0:1]
20612 if measurement_mode in ("c", "l"):
20613 setcfg("measurement_mode", measurement_mode)
20614 self.worker.options_dispcal.append("-y" + measurement_mode)
20615 elif line[0] == b"NATIVE_TARGET_WHITE":
20616 setcfg("whitepoint.colortemp", None)
20617 setcfg("whitepoint.x", None)
20618 setcfg("whitepoint.y", None)
20619 setcfg("3dlut.whitepoint.x", None)
20620 setcfg("3dlut.whitepoint.y", None)
20621 settings.append(lang.getstr("whitepoint"))
20622 elif line[0] == b"TARGET_WHITE_XYZ":
20623 XYZ = value.split() # noqa: N806
20624 i = 0
20625 try:
20626 for component in XYZ:
20627 # Normalize to 0.0 - 1.0
20628 XYZ[i] = float(component) / 100
20629 i += 1
20630 except ValueError:
20631 continue
20632 x, y, Y = XYZ2xyY(XYZ[0], XYZ[1], XYZ[2]) # noqa: N806
20633 XYZ2CCT(XYZ[0], XYZ[1], XYZ[2])
20634 if lang.getstr("whitepoint") not in settings:
20635 setcfg("whitepoint.colortemp", None)
20636 setcfg("whitepoint.x", round(x, 4))
20637 setcfg("whitepoint.y", round(y, 4))
20638 setcfg("3dlut.whitepoint.x", round(x, 4))
20639 setcfg("3dlut.whitepoint.y", round(y, 4))
20640 self.worker.options_dispcal.append(
20641 "-w{},{}".format(
20642 getcfg("whitepoint.x"), getcfg("whitepoint.y")
20643 )
20644 )
20645 settings.append(lang.getstr("whitepoint"))
20646 setcfg("calibration.luminance", stripzeros(round(Y * 100, 3)))
20647 self.worker.options_dispcal.append(
20648 "-b{}".format(getcfg("calibration.luminance"))
20649 )
20650 settings.append(lang.getstr("calibration.luminance"))
20651 elif line[0] == b"TARGET_GAMMA":
20652 setcfg("trc", None)
20653 if value in ("L_STAR", "REC709", "SMPTE240M", "sRGB"):
20654 setcfg("trc.type", "g")
20655 if value == "L_STAR":
20656 setcfg("trc", "l")
20657 elif value == "REC709":
20658 setcfg("trc", "709")
20659 elif value == "SMPTE240M":
20660 setcfg("trc", "240")
20661 elif value == "sRGB":
20662 setcfg("trc", "s")
20663 else:
20664 try:
20665 gamma = stripzeros(value)
20666 if float(gamma) < 0:
20667 setcfg("trc.type", "G")
20668 gamma = abs(float(gamma))
20669 else:
20670 setcfg("trc.type", "g")
20671 setcfg("trc", gamma)
20672 except ValueError:
20673 continue
20674 self.worker.options_dispcal.append(
20675 "-" + getcfg("trc.type") + str(getcfg("trc"))
20676 )
20677 settings.append(lang.getstr("trc"))
20678 elif line[0] == b"DEGREE_OF_BLACK_OUTPUT_OFFSET":
20679 setcfg("calibration.black_output_offset", stripzeros(value))
20680 self.worker.options_dispcal.append(
20681 "-f{}".format(getcfg("calibration.black_output_offset"))
20682 )
20683 settings.append(lang.getstr("calibration.black_output_offset"))
20684 elif line[0] == b"BLACK_POINT_CORRECTION":
20685 if float(stripzeros(value)) >= 0:
20686 black_point_correction = True
20687 setcfg("calibration.black_point_correction", stripzeros(value))
20688 self.worker.options_dispcal.append(
20689 "-k{}".format(getcfg("calibration.black_point_correction"))
20690 )
20691 settings.append(lang.getstr("calibration.black_point_correction"))
20692 elif line[0] == b"TARGET_BLACK_BRIGHTNESS":
20693 setcfg("calibration.black_luminance", stripzeros(value))
20694 self.worker.options_dispcal.append(
20695 "-B{}".format(getcfg("calibration.black_luminance"))
20696 )
20697 settings.append(lang.getstr("calibration.black_luminance"))
20698 elif line[0] == b"QUALITY":
20699 setcfg("calibration.quality", value.lower()[0:1])
20700 self.worker.options_dispcal.append(
20701 "-q{}".format(getcfg("calibration.quality"))
20702 )
20703 settings.append(lang.getstr("calibration.quality"))
20704 if not black_point_correction:
20705 setcfg("calibration.black_point_correction.auto", 1)
20706
20707 setcfg("calibration.file", path)
20708 self.update_controls(update_profile_name=update_profile_name)
20709 if b"CTI3" in ti3_lines:
20710 debug_print("[D] load_cal_handler testchart.file:", path)
20711 setcfg("testchart.file", path)
20712 writecfg()
20713 if load_vcgt:
20714 # load calibration into lut
20715 self.load_cal(silent=True)
20716 if len(settings) == 0:
20717 msg = lang.getstr("no_settings")
20718 else:
20719 msg = lang.getstr("settings_loaded", ", ".join(settings))
20720 if not silent and len(settings) == 0:
20721 InfoDialog(
20722 self,
20723 msg=msg + "\n" + path,
20724 ok=lang.getstr("ok"),
20725 bitmap=get_icon(32, "dialog-information"),
20726 )
20727 if (
20728 load_vcgt
20729 and getattr(self, "lut_viewer", None)
20730 and sys.platform == "win32"
20731 ):
20732 # Needed under Windows when using double buffering
20733 self.lut_viewer.Refresh()
20734
20735 def update_whitepoint_config_from_temperature(self) -> None:
20736 """Update the whitepoint configuration from the color temperature."""
20737 if getcfg("whitepoint.colortemp", False):
20738 # Color temperature
20739 if getcfg("whitepoint.colortemp.locus") == "T":
20740 # Planckian locus
20741 xyY = planckianCT2xyY(getcfg("whitepoint.colortemp")) # noqa: N806
20742 else:
20743 # Daylight locus
20744 xyY = CIEDCCT2xyY(getcfg("whitepoint.colortemp")) # noqa: N806
20745 # Update 3D LUT whitepoint target
20746 if xyY:
20747 setcfg("3dlut.whitepoint.x", xyY[0])
20748 setcfg("3dlut.whitepoint.y", xyY[1])
20749 else:
20750 setcfg("3dlut.whitepoint.x", None)
20751 setcfg("3dlut.whitepoint.y", None)
20752
20753 def update_ccmx_items_from_path(
20754 self, ccmx: str, path: str, ccxxsetting: str, update_ccmx_items: bool
20755 ) -> bool:
20756 """Update the colorimeter correction matrix items based on the path.
20757
20758 Args:
20759 ccmx (str): The colorimeter correction matrix file path.
20760 path (str): The path to the profile.
20761 ccxxsetting (str): The colorimeter correction setting.
20762 update_ccmx_items (bool): Whether to update the CCMX items.
20763
20764 Returns:
20765 bool: True if CCMX items were updated, False otherwise.
20766 """
20767 if not ccmx:
20768 ccxx = safe_glob(
20769 os.path.join(os.path.dirname(path), "*.ccmx")
20770 ) or safe_glob(os.path.join(os.path.dirname(path), "*.ccss"))
20771 if ccxx and len(ccxx) == 1:
20772 ccmx = ccxx[0]
20773 update_ccmx_items = True
20774 if ccmx:
20775 setcfg(
20776 "colorimeter_correction_matrix_file",
20777 f"{ccxxsetting}:{ccmx}",
20778 )
20779 return update_ccmx_items
20780
20781 def set_profile_quality_config_with_option(self, option: str) -> None:
20782 """Set the profile quality configuration.
20783
20784 Args:
20785 option (str): The option string containing the profile quality
20786 setting.
20787 """
20788 setcfg("profile.quality", option[1])
20789
20790 def set_profile_quality_b2a_config_with_option(self, option: str) -> None:
20791 """Set the profile quality B2A configuration.
20792
20793 Args:
20794 option (str): The option string containing the profile quality B2A
20795 setting.
20796 """
20797 setcfg("profile.quality.b2a", option[1] or "l")
20798
20799 def set_profile_black_point_compenstation_config_with_option(
20800 self, option: str, is_preset: bool, is_3dlut_preset: bool
20801 ) -> None:
20802 """Set the profile black point compensation configuration.
20803
20804 Args:
20805 option (str): The option string containing the profile black point
20806 compensation setting.
20807 is_preset (bool): Whether the profile is a preset.
20808 is_3dlut_preset (bool): Whether the profile is a 3D LUT preset.
20809 """
20810 if is_preset and not is_3dlut_preset and sys.platform == "darwin":
20811 # Force profile type to single shaper + matrix
20812 # due to OS X bugs with cLUT profiles and
20813 # matrix profiles with individual shaper curves
20814 option = "aS"
20815 # Force black point compensation due to OS X
20816 # bugs with non BPC profiles
20817 setcfg("profile.black_point_compensation", 1)
20818 setcfg("profile.type", option[1])
20819
20820 def set_gamap_profile_config_with_option(self, option: str) -> None:
20821 """Set the gamap profile configuration.
20822
20823 Args:
20824 option (str): The option string containing the profile.
20825 """
20826 option = option.split(None, 1)
20827 setcfg("gamap_profile", option[-1][1:-1])
20828 setcfg("gamap_perceptual", 1)
20829 if option[0:1] == "S":
20830 setcfg("gamap_saturation", 1)
20831
20832 def set_gamap_src_viewcond_config_with_option(self, option: str) -> None:
20833 """Set the gamap source view condition configuration.
20834
20835 Args:
20836 option (str): The option string containing the source view
20837 condition.
20838 """
20839 setcfg("gamap_src_viewcond", option[1:])
20840
20841 def set_gamap_out_viewcond_config_with_option(self, option: str) -> None:
20842 """Set the gamap output view condition configuration.
20843
20844 Args:
20845 option (str): The option string containing the output view
20846 condition.
20847 """
20848 setcfg("gamap_out_viewcond", option[1:])
20849
20850 def set_gamap_perceptual_intent_config_with_option(self, option: str) -> None:
20851 """Set the gamap perceptual intent configuration.
20852
20853 Args:
20854 option (str): The option string containing the perceptual intent.
20855 """
20856 setcfg("gamap_perceptual_intent", option[1:])
20857
20858 def set_gamap_saturation_intent_config_with_option(self, option: str) -> None:
20859 """Set the gamap saturation intent configuration.
20860
20861 Args:
20862 option (str): The option string containing the saturation intent.
20863 """
20864 setcfg("gamap_saturation_intent", option[1:])
20865
20866 def set_display_number_config_with_option(
20867 self, option: str, display_match: bool, display_changed: bool
20868 ) -> tuple[bool, bool]:
20869 """Set the display number configuration based on the option.
20870
20871 Args:
20872 option (str): The option string containing the display number.
20873 display_match (bool): Current state of display match.
20874 display_changed (bool): Current state of display change.
20875
20876 Returns:
20877 tuple[bool, bool]: Updated display match and change states.
20878 """
20879 if option[1:] in ("web", "madvr"):
20880 # Special case web and madvr so it can be used in
20881 # preset templates which are TI3 files
20882 for i, display_name in enumerate(self.worker.display_names):
20883 if display_name.lower() == option[1:]:
20884 # Found it
20885 display_match = True
20886 if getcfg("display.number") != i + 1:
20887 setcfg("display.number", i + 1)
20888 self.get_set_display()
20889 display_changed = True
20890 break
20891 return display_match, display_changed
20892
20893 def set_interactive_display_adjustment_config_with_option(
20894 self, option: str
20895 ) -> None:
20896 """Set the interactive display adjustment configuration.
20897
20898 Args:
20899 option (str): The option string containing the interactive display
20900 adjustment setting.
20901 """
20902 setcfg("calibration.interactive_display_adjustment", 0)
20903
20904 def set_calibration_quality_config_with_option(self, option: str) -> None:
20905 """Set the calibration quality configuration.
20906
20907 Args:
20908 option (str): The option string containing the calibration quality
20909 setting.
20910 """
20911 setcfg("calibration.quality", option[1])
20912
20913 def set_measurement_mode_config_with_option(self, option: str) -> None:
20914 """Set the measurement mode configuration.
20915
20916 Args:
20917 option (str): The option string containing the measurement mode
20918 setting.
20919 """
20920 if getcfg("measurement_mode") != "auto":
20921 setcfg("measurement_mode", option[1])
20922
20923 def set_whitepoint_temperature_config_with_option(self, option: str) -> None:
20924 """Set the whitepoint temperature configuration.
20925
20926 Args:
20927 option (str): The option string containing the whitepoint
20928 temperature setting.
20929 """
20930 setcfg("whitepoint.colortemp.locus", option[0:1])
20931 if option[1:]:
20932 setcfg("whitepoint.colortemp", int(float(option[1:])))
20933 setcfg("whitepoint.x", None)
20934 setcfg("whitepoint.y", None)
20935
20936 def set_whitepoint_config_with_option(self, option: str) -> None:
20937 """Set the whitepoint configuration.
20938
20939 Args:
20940 option (str): The option string containing the whitepoint setting.
20941 """
20942 option = option[1:].split(",")
20943 setcfg("whitepoint.colortemp", None)
20944 setcfg("whitepoint.x", option[0])
20945 setcfg("whitepoint.y", option[1])
20946 setcfg("3dlut.whitepoint.x", option[0])
20947 setcfg("3dlut.whitepoint.y", option[1])
20948
20949 def set_calibration_luminance_config_with_option(self, option: str) -> None:
20950 """Set the calibration luminance configuration.
20951
20952 Args:
20953 option (str): The option string containing the luminance setting.
20954 """
20955 setcfg("calibration.luminance", option[1:])
20956
20957 def set_tone_response_curve_config_with_option(self, option: str) -> None:
20958 """Set the tone response curve configuration.
20959
20960 Args:
20961 option (str): The option string containing the tone response curve
20962 setting.
20963 """
20964 setcfg("trc.type", option[0:1])
20965 setcfg("trc", option[1:])
20966
20967 def set_calibration_black_output_offset_config_with_option(
20968 self, option: str
20969 ) -> None:
20970 """Set the calibration black output offset configuration.
20971
20972 Args:
20973 option (str): The option string containing the black output.
20974 """
20975 setcfg("calibration.black_output_offset", option[1:])
20976
20977 def set_ambient_view_condition_adjustment_config_with_option(
20978 self, option: str
20979 ) -> None:
20980 """Set the ambient view condition adjustment configuration.
20981
20982 Args:
20983 option (str): The option string containing the ambient view
20984 condition adjustment setting.
20985 """
20986 try:
20987 ambient = float(option[1:])
20988 except ValueError:
20989 pass
20990 else:
20991 setcfg("calibration.ambient_viewcond_adjust", 1)
20992 # Argyll dispcal uses 20% of ambient (in lux,
20993 # fixed steradiant of 3.1415) as adapting
20994 # luminance, but we assume it already *is*
20995 # the adapting luminance. To correct for this,
20996 # scale so that dispcal gets the correct value.
20997 setcfg(
20998 "calibration.ambient_viewcond_adjust.lux",
20999 ambient / 5.0,
21000 )
21001
21002 def set_black_point_correction_config_with_option(
21003 self, option: str, black_point_correction: bool
21004 ) -> bool:
21005 """Set the calibration black point correction configuration.
21006
21007 Args:
21008 option (str): The option string containing the black point correction
21009 setting.
21010 black_point_correction (bool): Current state of black point correction.
21011
21012 Returns:
21013 tuple(bool): Updated state of black point correction.
21014 """
21015 if stripzeros(option[1:]) >= 0:
21016 black_point_correction = True
21017 setcfg("calibration.black_point_correction", option[1:])
21018 return (black_point_correction,)
21019
21020 def set_calibration_black_point_rate_config_with_option(self, option: str) -> None:
21021 """Set the calibration black point rate configuration.
21022
21023 Args:
21024 option (str): The option string containing the black point rate
21025 setting.
21026 """
21027 setcfg("calibration.black_point_rate", option[1:])
21028
21029 def set_calibration_black_luminance_config_with_option(self, option: str) -> None:
21030 """Set the calibration black luminance configuration.
21031
21032 Args:
21033 option (str): The option string containing the black luminance
21034 setting.
21035 """
21036 setcfg("calibration.black_luminance", option[1:])
21037
21038 def set_measureframe_config_with_option(self, option: str) -> None:
21039 """Set the measure frame configuration.
21040
21041 Args:
21042 option (str): The option string containing the measure frame
21043 setting.
21044 """
21045 if len(option[1:]) >= 5:
21046 setcfg("dimensions.measureframe", option[1:])
21047 setcfg("dimensions.measureframe.unzoomed", option[1:])
21048
21049 def set_measurement_mode_adaptive_config_with_option(self, option: str) -> None:
21050 """Set the measurement mode adaptive configuration.
21051
21052 Args:
21053 option (str): The option string containing the adaptive setting.
21054 """
21055 setcfg("measurement_mode.adaptive", option)
21056
21057 def set_measurement_mode_highres_config_with_option(self, option: str) -> None:
21058 """Set the measurement mode high resolution configuration.
21059
21060 Args:
21061 option (str): The option string containing the high resolution
21062 setting.
21063 """
21064 setcfg("measurement_mode.highres", option)
21065
21066 def set_measurement_mode_projector_config_with_option(self, option: str) -> None:
21067 """Set the measurement mode projector configuration.
21068
21069 Args:
21070 option (str): The option string containing the projector setting.
21071 """
21072 if len(option[1:]) == 0:
21073 setcfg("measurement_mode.projector", 1)
21074 self.set_measureframe_config_with_option(option)
21075
21076 def set_measure_darken_background_config_with_option(self, option: str) -> None:
21077 """Set the measure darken background configuration.
21078
21079 Args:
21080 option (str): The option string containing the darken background
21081 setting.
21082 """
21083 setcfg("measure.darken_background", option)
21084
21085 def set_ccss_config_with_option(self, option: str, path: str) -> tuple[str, bool]:
21086 """Set the colorimeter correction matrix file configuration.
21087
21088 Args:
21089 option (str): The option string containing the ccmx file path.
21090 path (str): The path to the calibration file.
21091
21092 Returns:
21093 tuple[str, bool]: The ccmx file path and a boolean indicating
21094 whether to update ccmx items.
21095 """
21096 option = option.split(None, 1)
21097 ccmx = option[-1][1:-1]
21098 if not os.path.isabs(ccmx):
21099 ccmx = os.path.join(os.path.dirname(path), ccmx)
21100 # Need to update ccmx items again even if
21101 # comport_ctrl_handler already did
21102 update_ccmx_items = True
21103 return ccmx, update_ccmx_items
21104
21105 def set_drift_compensation_config_with_option(self, option: str) -> None:
21106 """Set the drift compensation configuration.
21107
21108 Args:
21109 option (str): The option string containing the drift compensation
21110 setting.
21111 """
21112 if "b" in option[1:]:
21113 setcfg("drift_compensation.blacklevel", 1)
21114 if "w" in option[1:]:
21115 setcfg("drift_compensation.whitelevel", 1)
21116
21117 def set_tristimulus_observer_config_with_option(self, option: str) -> bool:
21118 """Set the tristimulus observer configuration.
21119
21120 Args:
21121 option (str): The option string containing the observer setting.
21122
21123 Returns:
21124 tuple(bool): Always returns True in a tuple.
21125 """
21126 setcfg("observer", option[1:])
21127 # Need to update ccmx items again even if
21128 # comport_ctrl_handler already did because CCMX
21129 # observer may override calibration observer
21130 return (True,)
21131
21132 def set_video_levels_config_with_option(self) -> None:
21133 """Set the video levels configuration."""
21134 setcfg("patterngenerator.use_video_levels", 1)
21135 self.update_output_levels_ctrl()
21136
21137 def get_calibration_file_path(self) -> str:
21138 """Get the path to the calibration file.
21139
21140 Returns:
21141 str: The path to the calibration file.
21142 """
21143 path = ""
21144 wildcard = lang.getstr("filetype.cal_icc") + "|*.cal;*.icc;*.icm"
21145 sevenzip = get_program_file("7z", "7-zip")
21146 if sevenzip:
21147 wildcard += ";*.7z"
21148 wildcard += ";*.tar.gz;*.tgz;*.zip"
21149 default_dir, default_file = get_verified_path("last_cal_or_icc_path")
21150 dlg = wx.FileDialog(
21151 self,
21152 lang.getstr("dialog.load_cal"),
21153 defaultDir=default_dir,
21154 defaultFile=default_file,
21155 wildcard=wildcard,
21156 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
21157 )
21158 dlg.Center(wx.BOTH)
21159 if dlg.ShowModal() == wx.ID_OK:
21160 path = dlg.GetPath()
21161 dlg.Destroy()
21162 return path
21163
21164 def remove_missing_calibration(self, path: str) -> None:
21165 """Remove a missing calibration file from the recent calibrations list.
21166
21167 Args:
21168 path (str): The path to the missing calibration file.
21169 """
21170 sel = self.calibration_file_ctrl.GetSelection()
21171 if len(self.recent_cals) > sel and self.recent_cals[sel] == path:
21172 self.recent_cals.remove(self.recent_cals[sel])
21173 recent_cals = self.get_unpreseted_recent_calibrations()
21174 setcfg("recent_cals", os.pathsep.join(recent_cals))
21175 self.calibration_file_ctrl.Delete(sel)
21176 cal = getcfg("calibration.file", False) or ""
21177 if cal not in self.recent_cals:
21178 self.recent_cals.append(cal)
21179 # The case-sensitive index could fail because of
21180 # case insensitive file systems, e.g. if the
21181 # stored filename string is
21182 # "C:\Users\Name\AppData\DisplayCAL\storage\MyFile"
21183 # but the actual filename is
21184 # "C:\Users\Name\AppData\DisplayCAL\storage\myfile"
21185 # (maybe because the user renamed the file)
21186 idx = index_fallback_ignorecase(self.recent_cals, cal)
21187 self.calibration_file_ctrl.SetSelection(idx)
21188 InfoDialog(
21189 self,
21190 msg=lang.getstr("file.missing", path),
21191 ok=lang.getstr("ok"),
21192 bitmap=get_icon(32, "dialog-error"),
21193 )
21194
21195 def parse_calibration_file(self, path: str) -> None | list[bytes]:
21196 """Parse the calibration file at the given path.
21197
21198 Args:
21199 path (str): The path to the calibration file.
21200
21201 Returns:
21202 None | list[bytes]: List of lines from the calibration file or None
21203 if invalid.
21204 """
21205 ti3_lines = []
21206 profile = None
21207 ext = os.path.splitext(path)[-1]
21208 if ext.lower() in ICCPROFILE_FILE_EXTENSIONS:
21209 profile = self.validate_icc_profile(path)
21210 if not profile:
21211 return profile, None
21212 ti3_lines = self.validate_calibration_data(profile, path)
21213 if ti3_lines is None:
21214 return profile, None
21215 else:
21216 try:
21217 with open(path, "rb") as cal:
21218 ti3_lines = [line.strip() for line in cal]
21219 except Exception:
21220 InfoDialog(
21221 self,
21222 msg=lang.getstr("error.file.open", path),
21223 ok=lang.getstr("ok"),
21224 bitmap=get_icon(32, "dialog-error"),
21225 )
21226 return profile, None
21227 return profile, ti3_lines
21228
21229 def validate_icc_profile(self, path: str) -> None | ICCProfile:
21230 """Validate if the given path points to a valid ICC profile."""
21231 try:
21232 profile = ICCProfile(path)
21233 except (OSError, ICCProfileInvalidError):
21234 InfoDialog(
21235 self,
21236 msg=lang.getstr("profile.invalid") + "\n" + path,
21237 ok=lang.getstr("ok"),
21238 bitmap=get_icon(32, "dialog-error"),
21239 )
21240 return None
21241 if profile.profileClass != b"mntr" or profile.colorSpace != b"RGB":
21242 InfoDialog(
21243 self,
21244 msg=lang.getstr(
21245 "profile.unsupported",
21246 (
21247 profile.profileClass.decode("utf-8"),
21248 profile.colorSpace.decode("utf-8"),
21249 ),
21250 )
21251 + "\n"
21252 + path,
21253 ok=lang.getstr("ok"),
21254 bitmap=get_icon(32, "dialog-error"),
21255 )
21256 return None
21257 return profile
21258
21259 def validate_calibration_data(
21260 self, profile: ICCProfile, path: str
21261 ) -> None | list[bytes]:
21262 """Validate the calibration data in the ICC profile.
21263
21264 Args:
21265 profile (ICCProfile): The ICC profile object.
21266 path (str): The path to the ICC profile file.
21267
21268 Returns:
21269 None | list[bytes]: List of lines from the calibration data or None
21270 if invalid.
21271 """
21272 ti3_lines = []
21273 cied = profile.tags.get("CIED")
21274 if cied:
21275 with BytesIO(cied) as cal:
21276 ti3_lines = [line.strip() for line in cal]
21277 else:
21278 targ = profile.tags.get("targ")
21279 from DisplayCAL.icc_profile import Text
21280
21281 if targ and isinstance(targ, Text):
21282 tag_data = targ.tagData
21283 with BytesIO(tag_data) as cal:
21284 ti3_lines = [line.strip() for line in cal]
21285 else:
21286 InfoDialog(
21287 self,
21288 msg=lang.getstr("profile.no_targ") + "\n" + path,
21289 ok=lang.getstr("ok"),
21290 bitmap=get_icon(32, "dialog-error"),
21291 )
21292 return None
21293 return ti3_lines
21294
21295 def delete_calibration_handler(self, event: wx.Event) -> None:
21296 """Delete calibration file and related files.
21297
21298 Args:
21299 event (wx.Event): The event object.
21300 """
21301 cal = getcfg("calibration.file", False)
21302 if not cal or not os.path.exists(cal):
21303 return
21304 caldir = os.path.dirname(cal)
21305 try:
21306 dircontents = os.listdir(caldir)
21307 except Exception as exception:
21308 InfoDialog(
21309 self,
21310 msg=str(exception),
21311 ok=lang.getstr("ok"),
21312 bitmap=get_icon(32, "dialog-error"),
21313 )
21314 return
21315 self.initialize_related_files(cal, dircontents)
21316 result = self.display_delete_confirmation()
21317 if result != wx.ID_OK:
21318 return
21319
21320 delete_related_files, orphan_related_files = (
21321 self.delete_related_files_and_cleanup(cal, dircontents)
21322 )
21323 # The case-sensitive index could fail because of
21324 # case-insensitive file systems, e.g. if the
21325 # stored filename string is
21326 # "C:\Users\Name\AppData\DisplayCAL\storage\MyFile"
21327 # but the actual filename is
21328 # "C:\Users\Name\AppData\DisplayCAL\storage\myfile"
21329 # (maybe because the user renamed the file)
21330 idx = index_fallback_ignorecase(self.recent_cals, cal)
21331 self.recent_cals.remove(cal)
21332 self.calibration_file_ctrl.Delete(idx)
21333 setcfg("calibration.file", None)
21334 setcfg("settings.changed", 1)
21335 recent_cals = self.get_unpreseted_recent_calibrations()
21336 setcfg("recent_cals", os.pathsep.join(recent_cals))
21337 update_colorimeter_correction_matrix_ctrl_items = False
21338 update_testcharts = False
21339 for path in delete_related_files:
21340 if path not in orphan_related_files:
21341 if os.path.splitext(path)[1].lower() in (".ccss", ".ccmx"):
21342 self.delete_colorimeter_correction_matrix_ctrl_item(path)
21343 update_colorimeter_correction_matrix_ctrl_items = True
21344 elif path in self.testcharts:
21345 update_testcharts = True
21346 if update_testcharts:
21347 self.set_testcharts()
21348 self.update_controls(False, update_colorimeter_correction_matrix_ctrl_items)
21349 self.load_display_profile_cal()
21350
21351 def initialize_related_files(self, cal: str, dircontents: list) -> None:
21352 """Initialize the related files dict based on the calibration dir contents.
21353
21354 Args:
21355 cal (str): The path to the calibration file.
21356 dircontents (list): List of files in the calibration directory.
21357 """
21358 self.related_files = {}
21359 for entry in dircontents:
21360 fn, ext = os.path.splitext(entry)
21361 if ext.lower() in (".app", SCRIPT_EXT):
21362 fn, ext = os.path.splitext(fn)
21363 if (
21364 fn.startswith(os.path.splitext(os.path.basename(cal))[0])
21365 or ext.lower() in (".ccss", ".ccmx")
21366 or entry.lower() in ("0_16.ti1", "0_16.ti3", "0_16.log")
21367 ):
21368 self.related_files[entry] = True
21369
21370 def display_delete_confirmation(self) -> None:
21371 """Display a confirmation dialog for deleting calibration files."""
21372 self.dlg = dlg = ConfirmDialog(
21373 self,
21374 msg=lang.getstr("dialog.confirm_delete"),
21375 ok=lang.getstr("delete"),
21376 cancel=lang.getstr("cancel"),
21377 bitmap=get_icon(32, "dialog-warning"),
21378 )
21379 if self.related_files:
21380 scale = getcfg("app.dpi") / config.get_default_dpi()
21381 scale = max(scale, 1)
21382 scrolled = ScrolledPanel(dlg, -1, style=wx.VSCROLL)
21383 sizer = scrolled.Sizer = wx.BoxSizer(wx.VERTICAL)
21384 dlg.sizer3.Add(scrolled, flag=wx.TOP | wx.EXPAND, border=12)
21385 for i, related_file in enumerate(self.related_files):
21386 if i:
21387 sizer.Add((0, 4))
21388 chk = wx.CheckBox(scrolled, -1, related_file)
21389 chk.SetValue(self.related_files[related_file])
21390 dlg.Bind(
21391 wx.EVT_CHECKBOX,
21392 self.delete_calibration_related_handler,
21393 id=chk.GetId(),
21394 )
21395 sizer.Add(chk, flag=wx.ALIGN_LEFT)
21396 scrolled.SetupScrolling()
21397 scrolled.MinSize = (
21398 int(
21399 min(
21400 scrolled.GetVirtualSize()[0]
21401 + 4 * scale
21402 + wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X),
21403 self.GetDisplay().ClientArea[2] - (12 * 3 + 32) * scale,
21404 )
21405 ),
21406 int(
21407 min(
21408 ((chk.Size[1] + 4) * min(len(self.related_files), 20) - 4)
21409 * scale,
21410 max(
21411 self.GetDisplay().ClientArea[3] - dlg.Size[1] - 40 * scale,
21412 chk.Size[1],
21413 ),
21414 )
21415 ),
21416 )
21417 dlg.sizer0.SetSizeHints(dlg)
21418 dlg.sizer0.Layout()
21419 dlg.Center()
21420 result = dlg.ShowModal()
21421 dlg.Destroy()
21422 return result
21423
21424 def delete_related_files_and_cleanup(
21425 self, cal: str, dircontents: list
21426 ) -> tuple[list, list]:
21427 """Delete related files and clean up the calibration directory.
21428
21429 Args:
21430 cal (str): The path to the calibration file.
21431 dircontents (list): List of files in the calibration directory.
21432
21433 Returns:
21434 tuple[list, list]: A tuple containing two lists:
21435 - delete_related_files: List of files intended for deletion.
21436 - orphan_related_files: List of files that could not be deleted.
21437 """
21438 delete_related_files = []
21439 if self.related_files:
21440 delete_related_files.extend(
21441 os.path.join(os.path.dirname(cal), related_file)
21442 for related_file in self.related_files
21443 if self.related_files[related_file]
21444 )
21445 if sys.platform == "darwin":
21446 trashcan = lang.getstr("trashcan.mac")
21447 elif sys.platform == "win32":
21448 trashcan = lang.getstr("trashcan.windows")
21449 else:
21450 trashcan = lang.getstr("trashcan.linux")
21451 orphan_related_files = delete_related_files
21452 try:
21453 if (
21454 sys.platform == "darwin"
21455 and len(delete_related_files) + 1 == len(dircontents)
21456 and ".DS_Store" in dircontents
21457 ) or len(delete_related_files) == len(dircontents):
21458 # Delete whole folder
21459 send2trash([os.path.dirname(cal)])
21460 else:
21461 send2trash(delete_related_files)
21462 orphan_related_files = [
21463 related_file
21464 for related_file in delete_related_files
21465 if os.path.exists(related_file)
21466 ]
21467 if orphan_related_files:
21468 InfoDialog(
21469 self,
21470 msg=lang.getstr("error.deletion", trashcan)
21471 + "\n\n"
21472 + "\n".join(
21473 os.path.basename(related_file)
21474 for related_file in orphan_related_files
21475 ),
21476 ok=lang.getstr("ok"),
21477 bitmap=get_icon(32, "dialog-error"),
21478 )
21479 except OSError as exc:
21480 InfoDialog(
21481 self,
21482 msg=f"{lang.getstr('error.deletion', trashcan)}\n\n{exc!s}",
21483 ok=lang.getstr("ok"),
21484 bitmap=get_icon(32, "dialog-error"),
21485 )
21486
21487 return delete_related_files, orphan_related_files
21488
21489 def delete_calibration_related_handler(self, event: wx.Event) -> None:
21490 """Handle checkbox changes in the delete calibration dialog.
21491
21492 Args:
21493 event (wx.Event): The event that triggered this handler.
21494 """
21495 chk = self.dlg.FindWindowById(event.GetId())
21496 self.related_files[chk.GetLabel()] = chk.GetValue()
21497
21498 def aboutdialog_handler(self, event: wx.Event) -> None:
21499 """Open the About dialog.
21500
21501 Args:
21502 event (wx.Event): The event that triggered this handler.
21503 """
21504 if hasattr(self, "aboutdialog"):
21505 self.aboutdialog.Destroy()
21506 self.aboutdialog = AboutDialog(
21507 self, -1, lang.getstr("menu.about"), size=(100, 100)
21508 )
21509 self.aboutdialog.panel.BackgroundColour = wx.SystemSettings.GetColour(
21510 wx.SYS_COLOUR_WINDOW
21511 )
21512 items = []
21513 scale = max(getcfg("app.dpi") / config.get_default_dpi(), 1)
21514 items.append(wx_Panel(self.aboutdialog.panel, -1, size=(-1, round(6 * scale))))
21515 items[-1].BackgroundColour = "#66CC00"
21516 items.append(
21517 get_header(
21518 self.aboutdialog.panel,
21519 get_bitmap("theme/header", display_missing_icon=False),
21520 label=wrap(lang.getstr("header"), 32),
21521 size=(320, 120),
21522 repeat_sub_bitmap_h=(220, 0, 2, 184),
21523 )
21524 )
21525 separator = wx.Panel(self.aboutdialog.panel, size=(-1, 1))
21526 separator.BackgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
21527 items.append(separator)
21528 items.append((1, 12))
21529 version_title = VERSION_STRING
21530 items.append(
21531 [
21532 HyperLinkCtrl(
21533 self.aboutdialog.panel,
21534 -1,
21535 label=APPNAME,
21536 URL=f"https://{DOMAIN}/",
21537 ),
21538 wx.StaticText(
21539 self.aboutdialog.panel,
21540 -1,
21541 f" {version_title} © {wrap(AUTHOR, 55)}",
21542 ),
21543 ]
21544 )
21545 items.append(
21546 [
21547 HyperLinkCtrl(
21548 self.aboutdialog.panel,
21549 -1,
21550 label="ArgyllCMS",
21551 URL=config.DEFAULTS.get("argyll.domain"),
21552 ),
21553 wx.StaticText(
21554 self.aboutdialog.panel,
21555 -1,
21556 " {} © Graeme Gill".format(
21557 re.sub(r"(?:\.0)+$", ".0", self.worker.argyll_version_string)
21558 ),
21559 ),
21560 ]
21561 )
21562 items.append(wx.StaticText(self.aboutdialog.panel, -1, ""))
21563 items.append(
21564 wx.StaticText(self.aboutdialog.panel, -1, f"{lang.getstr('translations')}:")
21565 )
21566 lauthors = {}
21567 for lcode in lang.LDICT:
21568 lauthor = lang.LDICT[lcode].get("!author", "")
21569 language = lang.LDICT[lcode].get("!language", "")
21570 if lauthor and language:
21571 if not lauthors.get(lauthor):
21572 lauthors[lauthor] = []
21573 lauthors[lauthor].append(language)
21574 lauthors = [(lauthors[lauthor], lauthor) for lauthor in lauthors]
21575 lauthors.sort()
21576 for langs, lauthor in lauthors:
21577 items.append(
21578 wx.StaticText(
21579 self.aboutdialog.panel,
21580 -1,
21581 "{} - {}".format(", ".join(langs), lauthor),
21582 )
21583 )
21584 items.append(wx.StaticText(self.aboutdialog.panel, -1, ""))
21585
21586 # Apricity OS icons
21587 items.append(
21588 [
21589 HyperLinkCtrl(
21590 self.aboutdialog.panel,
21591 -1,
21592 label="Apricity Icons",
21593 URL="https://github.com/Apricity-OS/apricity-icons",
21594 ),
21595 wx.StaticText(self.aboutdialog.panel, -1, " © Apricity OS Team"),
21596 ]
21597 )
21598
21599 # Suru icons
21600 items.append(
21601 [
21602 HyperLinkCtrl(
21603 self.aboutdialog.panel,
21604 -1,
21605 label="Suru Icons",
21606 URL="https://github.com/snwh/suru-icon-theme",
21607 ),
21608 wx.StaticText(self.aboutdialog.panel, -1, " © Sam Hewitt"),
21609 ]
21610 )
21611
21612 # Gnome icons
21613 items.append(
21614 [
21615 wx.StaticText(self.aboutdialog.panel, -1, "Some icons © "),
21616 HyperLinkCtrl(
21617 self.aboutdialog.panel,
21618 -1,
21619 label="GNOME Project",
21620 URL="https://www.gnome.org/",
21621 ),
21622 ]
21623 )
21624
21625 items.append(wx.StaticText(self.aboutdialog.panel, -1, ""))
21626
21627 match = re.match(r"([^(]+)\s*(\([^(]+\))?\s*(\[[^[]+\])?", sys.version)
21628 pyver_long = match.groups() if match else [sys.version]
21629 items.append(
21630 [
21631 HyperLinkCtrl(
21632 self.aboutdialog.panel,
21633 -1,
21634 label="Python",
21635 URL="https://www.python.org/",
21636 ),
21637 wx.StaticText(self.aboutdialog.panel, -1, " " + pyver_long[0].strip()),
21638 ]
21639 )
21640 items.append(
21641 [
21642 HyperLinkCtrl(
21643 self.aboutdialog.panel,
21644 -1,
21645 label="wxPython",
21646 URL="https://www.wxpython.org/",
21647 ),
21648 wx.StaticText(self.aboutdialog.panel, -1, f" {wx.version()}"),
21649 ]
21650 )
21651 items.append(
21652 wx.StaticText(
21653 self.aboutdialog.panel,
21654 -1,
21655 lang.getstr("audio.lib", f"{audio._LIB} {audio._LIB_VERSION}"),
21656 )
21657 )
21658 items.append((1, 12))
21659 self.aboutdialog.add_items(items)
21660 self.aboutdialog.Layout()
21661 self.aboutdialog.Center()
21662 self.aboutdialog.Show()
21663
21664 def readme_handler(self, event: wx.Event) -> None:
21665 """Open the README file in the default web browser.
21666
21667 Args:
21668 event (wx.Event): The event that triggered the action.
21669 """
21670 readme = get_data_path("README-fr.html") if lang.getcode() == "fr" else None
21671 if not readme:
21672 readme = get_data_path("README.html")
21673 if readme:
21674 launch_file(readme)
21675
21676 def license_handler(self, event: wx.Event) -> None:
21677 """Open the license file in the default text editor.
21678
21679 Args:
21680 event (wx.Event): The event that triggered the action.
21681 """
21682 license_path = get_data_path("LICENSE.txt")
21683 if not license_path:
21684 # Debian
21685 license_path = "/usr/share/common-licenses/GPL-3"
21686 if license_path and os.path.isfile(license_path):
21687 launch_file(license_path)
21688
21689 def help_support_handler(self, event: wx.Event) -> None:
21690 """Open the help and support page in the default web browser.
21691
21692 Args:
21693 event (wx.Event): The event that triggered the action.
21694 """
21695 launch_file(f"{DEVELOPMENT_HOME_PAGE}/issues")
21696
21697 def bug_report_handler(self, event: wx.Event) -> None:
21698 """Open the bug report page in the default web browser.
21699
21700 Args:
21701 event (wx.Event): The event that triggered the action.
21702 """
21703 launch_file(f"{DEVELOPMENT_HOME_PAGE}/issues")
21704
21705 def app_update_check_handler(
21706 self, event: wx.Event, silent: bool = False, argyll: bool = False
21707 ) -> None:
21708 """Check for application updates.
21709
21710 Args:
21711 event (wx.Event): The event that triggered the check.
21712 silent (bool): If True, suppress user notifications.
21713 argyll (bool): If True, check for Argyll updates instead.
21714 """
21715 if (
21716 not hasattr(self, "app_update_check")
21717 or not self.app_update_check.is_alive()
21718 ):
21719 self.app_update_check = threading.Thread(
21720 target=app_update_check,
21721 name="ApplicationUpdateCheck",
21722 args=(self, silent, False, argyll),
21723 )
21724 self.app_update_check.start()
21725
21726 def app_auto_update_check_handler(self, event: wx.Event) -> None:
21727 """Handle the application auto-update check menu item toggle.
21728
21729 Args:
21730 event (wx.Event): The event that triggered the toggle.
21731 """
21732 setcfg("update_check", int(self.menuitem_app_auto_update_check.IsChecked()))
21733
21734 def infoframe_toggle_handler(
21735 self, event: wx.Event = None, show: None | bool = None
21736 ) -> None:
21737 """Toggle the visibility of the info frame (log window).
21738
21739 Args:
21740 event (wx.Event, optional): The event that triggered the toggle.
21741 show (bool, optional): If provided, explicitly set the visibility.
21742 """
21743 if show is None:
21744 show = not self.infoframe.IsShownOnScreen()
21745 setcfg("log.show", int(show))
21746 if show:
21747 self.log()
21748 else:
21749 LOGBUFFER.truncate(0)
21750 self.infoframe.Show(show)
21751 self.menuitem_show_log.Check(show)
21752 self.menuitem_log_autoshow.Enable(not show)
21753
21754 def infoframe_autoshow_handler(self, event: wx.Event) -> None:
21755 """Handle the autoshow log menu item toggle.
21756
21757 Args:
21758 event (wx.Event): The event that triggered the toggle.
21759 """
21760 setcfg("log.autoshow", int(self.menuitem_log_autoshow.IsChecked()))
21761
21762 def HideAll(self) -> None: # noqa: N802
21763 """Hide all top-level windows of the application."""
21764 self.stop_timers()
21765 self.gamapframe.Hide() if hasattr(self, "gamapframe") else None
21766 self.aboutdialog.Hide() if hasattr(self, "aboutdialog") else None
21767 self.extra_args.Hide() if hasattr(self, "extra_args") else None
21768 LOGBUFFER.truncate(0)
21769 self.infoframe.Hide()
21770 self.tcframe.Hide() if hasattr(self, "tcframe") else None
21771 self.lut_viewer.Hide() if getattr(
21772 self, "lut_viewer", None
21773 ) and self.lut_viewer.IsShownOnScreen() else None
21774 self.lut3dframe.Hide() if getattr(self, "lut3dframe", None) else None
21775 self.reportframe.Hide() if getattr(self, "reportframe", None) else None
21776 self.synthiccframe.Hide() if getattr(self, "synthiccframe", None) else None
21777 self.wpeditor.Close() if getattr(self, "wpeditor", None) else None
21778 for profile_info in list(self.profile_info.values()):
21779 profile_info.Close()
21780 while self.measureframes:
21781 measureframe = self.measureframes.pop()
21782 measureframe.Close() if measureframe else None
21783 for window in list(wx.GetTopLevelWindows()):
21784 if window and window is not self and window.IsShown():
21785 print(
21786 "Closing",
21787 window,
21788 "'{}'".format(getattr(window, "Title", window.Name)),
21789 )
21790 window.Close()
21791 self.Hide()
21792 self.enable_menus(False)
21793
21794 def Show(self, show: bool = True, start_timers: bool = True) -> None: # noqa: N802
21795 """Show or hide the main application window.
21796
21797 Args:
21798 show (bool): Whether to show or hide the window.
21799 start_timers (bool): Whether to start timers after showing the window.
21800 """
21801 if show and self.measureframe.IsShown():
21802 self.measureframe.Hide()
21803 if not self.IsShownOnScreen():
21804 if hasattr(self, "tcframe"):
21805 self.tcframe.Show(getcfg("tc.show"))
21806 if getcfg("log.show"):
21807 wx.CallAfter(self.infoframe_toggle_handler, show=True)
21808 if (
21809 LUTFrame
21810 and getcfg("lut_viewer.show")
21811 and self.worker.argyll_version > [0, 0, 0]
21812 ):
21813 if getattr(self, "lut_viewer", None):
21814 self.init_lut_viewer(show=True)
21815 else:
21816 # Using wx.CallAfter fixes wrong positioning under wxGTK
21817 # with wxPython 3 on first initialization
21818 wx.CallAfter(self.init_lut_viewer, show=True)
21819 else:
21820 setcfg("lut_viewer.show", 0)
21821 for profile_info in reversed(list(self.profile_info.values())):
21822 profile_info.Show()
21823 if start_timers:
21824 self.start_timers()
21825 self.enable_menus()
21826 wx.Frame.Show(self, show)
21827 if self.worker.progress_wnd and self.worker.progress_wnd.IsShown():
21828 self.Lower()
21829 self.worker.progress_wnd.Raise()
21830 self.update_layout()
21831
21832 def veto_close_event(self, event: wx.Event) -> None:
21833 """Veto the close event if conditions are not met.
21834
21835 Args:
21836 event (wx.Event): The close event to veto.
21837 """
21838 if isinstance(event, wx.CloseEvent) and event.CanVeto():
21839 event.Veto()
21840
21841 def OnClose(self, event: wx.Event = None) -> None: # noqa: N802
21842 """Handle application close event.
21843
21844 Args:
21845 event (wx.Event): The close event, if any.
21846 """
21847 if getattr(self.worker, "thread", None) and self.worker.thread.is_alive():
21848 self.veto_close_event(event)
21849 self.worker.abort_subprocess(True)
21850 return
21851 if sys.platform == "darwin" or DEBUG:
21852 self.focus_handler(event)
21853 if not hasattr(self, "tcframe") or self.tcframe.tc_close_handler():
21854 # If resources are missing, XRC shows an error dialog.
21855 # If the user never closees that dialog before he quits the
21856 # application, this dialog will hinder exiting the main loop.
21857 win = self.get_top_window()
21858 if isinstance(win, wx.Dialog) and win.IsModal():
21859 win.RequestUserAttention()
21860 win.Raise()
21861 self.veto_close_event(event)
21862 return
21863 for win in list(wx.GetTopLevelWindows()):
21864 if (
21865 win
21866 and not win.IsBeingDeleted()
21867 and isinstance(win, VisualWhitepointEditor)
21868 ):
21869 win.Close(force=True)
21870 writecfg()
21871 if getattr(self, "thread", None) and self.thread.is_alive():
21872 self.Disable()
21873 print("Waiting for child thread to exit...")
21874 self.thread.join()
21875 self.listening = False
21876 if isinstance(getattr(self.worker, "madtpg", None), madvr.MadTPGNet):
21877 self.worker.madtpg.shutdown()
21878 for patterngenerator in list(self.worker.patterngenerators.values()):
21879 patterngenerator.listening = False
21880 self.HideAll()
21881 if (
21882 self.worker.tempdir
21883 and os.path.isdir(self.worker.tempdir)
21884 and not os.listdir(self.worker.tempdir)
21885 ):
21886 self.worker.wrapup(False)
21887 wx.GetApp().ExitMainLoop()
21888 else:
21889 self.veto_close_event(event)
21890
21891
21892 if (
21893 sys.platform == "darwin" and intlist(platform.mac_ver()[0].split(".")) >= [10, 10]
21894 ) or os.getenv("XDG_SESSION_TYPE") == "wayland":
21895 # Use a wx.Dialog so we can use ShowModal() which seems to be the only way to
21896 # center the splash screen under Wayland.
21897 # Under macOS, it fixes the splash screen not animating when running
21898 # frozen (from an app bundle created using py2app).
21899 start_cls = wx.Dialog
21900 else:
21901 start_cls = wx.Frame
21902
21903
21904 class StartupFrame(start_cls):
21905 """Splash screen."""
21906
21907 def __init__(self) -> None:
21908 super().__init__()
21909 title = f"{APPNAME} {VERSION_STRING}"
21910 start_cls.__init__(
21911 self,
21912 None,
21913 title="{}: {}".format(title, lang.getstr("startup")),
21914 style=wx.FRAME_SHAPED | wx.NO_BORDER,
21915 )
21916 self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
21917 if wx.VERSION >= (2, 8, 12, 1):
21918 # Setup shape. Required to get rid of window shadow under Ubuntu.
21919 # Note that shaped windows seem to be broken (won't show at all)
21920 # with wxGTK 2.8.12.0 and possibly earlier.
21921 self.mask_bmp = get_bitmap("theme/splash-mask")
21922 if wx.Platform == "__WXGTK__":
21923 # wxGTK requires that the window be created before you can
21924 # set its shape, so delay the call to SetWindowShape until
21925 # this event.
21926 self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
21927 elif sys.platform != "darwin" or intlist(
21928 platform.mac_ver()[0].split(".")
21929 ) < [10, 14]:
21930 # On wxMSW and wxMac the window has already been created.
21931 self.SetWindowShape()
21932
21933 # Setup splash screen
21934 self.use_simple_splash = bool(getcfg("splash.simple"))
21935 self.splash_bmp = get_bitmap(
21936 "theme/splash-simple" if self.use_simple_splash else "theme/splash"
21937 )
21938 self.splash_anim = []
21939 for pth in get_data_path("theme/splash_anim", r"\.png$") or []:
21940 self.splash_anim.append(get_bitmap(os.path.splitext(pth)[0]))
21941 self.zoom_scales = []
21942 if getcfg("splash.zoom"):
21943 # Zoom in instead of fade
21944 numframes = 15
21945 self.splash_alpha = self.splash_bmp.ConvertToImage().GetAlphaData()
21946 minv = 1.0 / self.splash_bmp.Size[0]
21947 for x in range(numframes):
21948 scale = minv + colormath.special_pow(
21949 0.35 + x / (numframes - 1.0) * (1 - 0.35), -2084
21950 ) * (1 - minv)
21951 self.zoom_scales.append(scale)
21952 self.zoom_scales.append(1.02)
21953 self.zoom_scales.append(1.0)
21954 # Fade in major version number
21955 self.splash_version_anim = []
21956 splash_version = get_bitmap("theme/splash_version")
21957 if splash_version:
21958 im = splash_version.ConvertToImage()
21959 for alpha in [0, 0.2, 0.4, 0.6, 0.8, 1, 0.95, 0.9, 0.85, 0.8, 0.75]:
21960 imcopy = im.AdjustChannels(1, 1, 1, alpha)
21961 self.splash_version_anim.append(imcopy.ConvertToBitmap())
21962 self.frame = 0
21963 clientarea = self.GetDisplay().ClientArea
21964 self.splash_x, self.splash_y = (
21965 clientarea[0] + int(clientarea[2] / 2.0 - self.splash_bmp.Size[0] / 2.0),
21966 clientarea[1] + int(clientarea[3] / 2.0 - self.splash_bmp.Size[1] / 2.0),
21967 )
21968 self.Pulse(
21969 "\n".join(
21970 [
21971 lang.getstr("welcome_back" if hascfg("recent_cals") else "welcome"),
21972 lang.getstr("startup"),
21973 ]
21974 )
21975 )
21976
21977 self._bufferbitmap = wx.EmptyBitmap(
21978 self.splash_bmp.Size[0], self.splash_bmp.Size[1]
21979 )
21980 self._buffereddc = wx.MemoryDC(self._bufferbitmap)
21981 self.worker = Worker()
21982 self.grab_image()
21983 self.SetClientSize(self.splash_bmp.Size)
21984 self.SetPosition((self.splash_x, self.splash_y))
21985 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
21986 self.Bind(wx.EVT_PAINT, self.OnPaint)
21987 if len(self.zoom_scales):
21988 self._alpha = 255
21989 else:
21990 self.SetTransparent(0)
21991 self._alpha = 0
21992
21993 audio.safe_init()
21994 if audio._LIB:
21995 print(lang.getstr("audio.lib", f"{audio._LIB} {audio._LIB_VERSION}"))
21996 # Startup sound
21997 # Needs to be stereo!
21998 if getcfg("startup_sound.enable"):
21999 self.startup_sound = audio.Sound(get_data_path("theme/intro_new.wav"))
22000 self.startup_sound.volume = 0.8
22001 self.startup_sound.safe_play()
22002
22003 # We need to use CallLater instead of CallAfter otherwise dialogs
22004 # will not show while the main frame is not yet initialized
22005 wx.CallLater(1, self.startup)
22006 self.ShowModal() if isinstance(self, wx.Dialog) else self.Show()
22007
22008 def gamma_correct_image(
22009 self, bmp_path: str, gamut: str = "Rec. 709", gamma: float = 2.0
22010 ) -> tuple[str, str]:
22011 """Gamma correct the image to the given gammut and gamma.
22012
22013 Args:
22014 bmp_path (str): Path to the bitmap image to be corrected.
22015 gamut (str): The color gamut to convert to (default: "Rec. 709").
22016 gamma (float): The gamma value to apply (default: 2.0).
22017
22018 Returns:
22019 tuple[str, str]: Tuple containing the paths to the corrected bitmap
22020 and the TIFF file.
22021 """
22022 # We want to color convert the screenshot to the given gamut and gamma
22023 # to get rid of visible color differences.
22024 try:
22025 import PIL
22026 import PIL.Image
22027 import PIL.ImageCms
22028 except ImportError as exception:
22029 PIL = None # noqa: N806
22030 print("Info: Couldn't import PIL:", exception)
22031 else:
22032 gamut_with_gamma = list(colormath.get_rgb_space(gamut))
22033 gamut_with_gamma[0] = gamma
22034 gamut_with_gamma_profile = ICCProfile.from_rgb_space(
22035 gamut_with_gamma,
22036 b"%s gamma %s"
22037 % (bytes(gamut, "utf-8"), bytes(str(f"{gamma:.1f}"), "utf-8")),
22038 )
22039 gamut_with_gamma_io = BytesIO(gamut_with_gamma_profile.data)
22040 try:
22041 gamut_with_gamma_cms = PIL.ImageCms.getOpenProfile(gamut_with_gamma_io)
22042 except Exception as exception:
22043 gamut_with_gamma_cms = None
22044 print("Info:", exception)
22045
22046 tif_path = os.path.join(self.worker.tempdir, "screencap.tif")
22047 if not PIL or not gamut_with_gamma_cms:
22048 return bmp_path, tif_path
22049
22050 # Open screenshot as PIL image
22051 try:
22052 pim = PIL.Image.open(bmp_path)
22053 except Exception as exception:
22054 print("Info: Couldn't open image:", exception)
22055 else:
22056 if "icc_profile" in pim.info:
22057 # Get embedded ICC profile from image
22058 inprofile_io = BytesIO(pim.info["icc_profile"])
22059 # Convert from display profile to the given gamma and gamut
22060 try:
22061 inprofile_cms = PIL.ImageCms.getOpenProfile(inprofile_io)
22062 PIL.ImageCms.profileToProfile(
22063 pim, inprofile_cms, gamut_with_gamma_cms, inPlace=True
22064 )
22065 # Convert PIL image to wx.Image
22066 # XXX: Doesn't seem to work correctly, converted
22067 # image consists of vertical stripes - probably an
22068 # issue with order of RGB data?
22069 # width, height = pim.size
22070 # img = wx.ImageFromBuffer(width, height,
22071 # pim.tobytes())
22072 pim.save(tif_path)
22073 except Exception as exception:
22074 print("Info:", exception)
22075 else:
22076 bmp_path = tif_path
22077 # We are done with PIL image now
22078
22079 return bmp_path, tif_path
22080
22081 def grab_image(self) -> None:
22082 """Grab screen shot."""
22083 if self.use_simple_splash:
22084 return
22085 is_wayland = os.getenv("XDG_SESSION_TYPE") == "wayland"
22086 # Grab a bitmap of the screen area we're going to draw on
22087 if sys.platform != "darwin" and not is_wayland:
22088 dc = wx.ScreenDC()
22089 # Grab from ScreenDC if not Mac OS X or Wayland
22090 self._buffereddc.Blit(
22091 0,
22092 0,
22093 self.splash_bmp.Size[0],
22094 self.splash_bmp.Size[1],
22095 dc,
22096 self.splash_x,
22097 self.splash_y,
22098 )
22099 elif not isinstance(self.worker.create_tempdir(), Exception):
22100 # Use screencapture utility under Mac OS X and Wayland
22101 if sys.platform == "darwin":
22102 self.grab_image_macos()
22103 else:
22104 # Wayland
22105 self.grab_image_wayland()
22106
22107 def grab_image_macos(self) -> None:
22108 """Grab a screenshot on macOS."""
22109 # Use screencapture utility under Mac OS X
22110 splashdimensions = (
22111 self.splash_x,
22112 self.splash_y,
22113 self.splash_bmp.Size[0],
22114 self.splash_bmp.Size[1],
22115 )
22116 extra_args = []
22117 is_mavericks = intlist(platform.mac_ver()[0].split(".")) >= [10, 9]
22118 if is_mavericks:
22119 # Under 10.9 we can specify screen region as arguments
22120 extra_args = ["-R{:.0f},{:.0f},{:.0f},{:.0f}".format(*splashdimensions)]
22121 extra_args.append("-x")
22122 screencap = which("screencapture")
22123
22124 bmp_path = os.path.join(self.worker.tempdir, "screencap.png")
22125 tif_path = bmp_path
22126 gamma = 2.04 # somewhat arbitrary gamma value, but works the best for macOS
22127 if self.worker.exec_cmd(
22128 screencap,
22129 [*extra_args, "screencap.png"],
22130 capture_output=True,
22131 skip_scripts=True,
22132 silent=True,
22133 ) and os.path.isfile(bmp_path):
22134 result = True
22135 else:
22136 result = False
22137 img = None
22138 if not result:
22139 return
22140 bmp_path, tif_path = self.gamma_correct_image(bmp_path, gamma=gamma)
22141 if not img:
22142 img = wx.Image(bmp_path)
22143 if img.IsOk():
22144 if wx.VERSION > (3,):
22145 quality = wx.IMAGE_QUALITY_BICUBIC
22146 else:
22147 quality = wx.IMAGE_QUALITY_HIGH
22148 if is_mavericks and (
22149 img.Width != self.splash_bmp.Size[0] > 0
22150 or img.Height != self.splash_bmp.Size[1] > 0
22151 ):
22152 # Retina
22153 img.Rescale(
22154 round(img.Width * (self.splash_bmp.Size[0] / float(img.Width))),
22155 round(img.Height * (self.splash_bmp.Size[1] / float(img.Height))),
22156 quality,
22157 )
22158
22159 if (
22160 not is_mavericks
22161 and img.Width >= self.splash_x + self.splash_bmp.Size[0]
22162 and img.Height >= self.splash_y + self.splash_bmp.Size[1]
22163 ):
22164 # macOS pre 10.9 or Wayland we have to get the
22165 # splashscreen region from the full screenshot bitmap
22166 img = img.GetSubImage(splashdimensions)
22167 if bmp_path != tif_path:
22168 # Fallback
22169 img.GammaCorrect(from_gamma=1.8, to_gamma=gamma)
22170 bmp = img.ConvertToBitmap()
22171 self._buffereddc.DrawBitmap(bmp, 0, 0)
22172 self.worker.wrapup(False)
22173
22174 def grab_image_wayland(self) -> None:
22175 """Grab a screenshot on Wayland."""
22176 # Use screencapture utility under Wayland
22177 splashdimensions = (
22178 self.splash_x,
22179 self.splash_y,
22180 self.splash_bmp.Size[0],
22181 self.splash_bmp.Size[1],
22182 )
22183 extra_args = []
22184 geometry = [0, 0, 0, 0]
22185 # Wayland
22186 if os.getenv("XDG_CURRENT_DESKTOP", "").split(":")[0] == "KDE":
22187 extra_args.extend(
22188 ["--fullscreen", "--background", "--nonotify", "--output"]
22189 )
22190 # XXX: Even though the documentation suggests otherwise,
22191 # spectacle's --background mode still prompts for user
22192 # interaction to actually take the screenshot...
22193 screencap = None # which("spectacle")
22194 else:
22195 extra_args.append("-f")
22196 screencap = which("gnome-screenshot")
22197 # Determine HiDPI scaling factor
22198 geometry = self.GetDisplay().Geometry
22199 bmp_path = os.path.join(self.worker.tempdir, "screencap.png")
22200 if self.worker.exec_cmd(
22201 screencap,
22202 [*extra_args, "screencap.png"],
22203 capture_output=True,
22204 skip_scripts=True,
22205 silent=True,
22206 ) and os.path.isfile(bmp_path):
22207 result = True
22208 else:
22209 result = False
22210 img = None
22211 if not result:
22212 return
22213 if not img:
22214 img = wx.Image(bmp_path)
22215 if img.IsOk():
22216 if wx.VERSION > (3,):
22217 quality = wx.IMAGE_QUALITY_BICUBIC
22218 else:
22219 quality = wx.IMAGE_QUALITY_HIGH
22220 if img.Width != geometry[2] > 0 or img.Height != geometry[3] > 0:
22221 # Wayland + HiDPI
22222 img.Rescale(
22223 round(img.Width * (geometry[2] / float(img.Width))),
22224 round(img.Height * (geometry[3] / float(img.Height))),
22225 quality,
22226 )
22227 if (
22228 img.Width >= self.splash_x + self.splash_bmp.Size[0]
22229 and img.Height >= self.splash_y + self.splash_bmp.Size[1]
22230 ):
22231 # Wayland we have to get the
22232 # splashscreen region from the full screenshot bitmap
22233 img = img.GetSubImage(splashdimensions)
22234 bmp = img.ConvertToBitmap()
22235 self._buffereddc.DrawBitmap(bmp, 0, 0)
22236 self.worker.wrapup(False)
22237
22238 def startup(self) -> None:
22239 """Start the splash screen animation."""
22240 if sys.platform not in ("darwin", "win32"):
22241 # Drawing of window shadow can be prevented under some desktop
22242 # environments that would normally try to draw a shadow by never
22243 # making the window fully opaque
22244 endalpha = 254
22245 else:
22246 endalpha = 255
22247 if self.IsShown() and self._alpha < endalpha:
22248 self._alpha += 15
22249 self._alpha = min(self._alpha, endalpha)
22250 self.SetTransparent(self._alpha)
22251 if sys.platform not in ("darwin", "win32"):
22252 self.Refresh()
22253 self.Update()
22254 wx.CallLater(1, self.startup)
22255 return
22256 if (
22257 self.frame
22258 < (
22259 len(self.zoom_scales)
22260 + len(self.splash_anim)
22261 + len(self.splash_version_anim)
22262 )
22263 - 1
22264 ):
22265 self.frame += 1
22266 self.Refresh()
22267 self.Update()
22268 if self.frame < len(self.zoom_scales):
22269 wx.CallLater(1, self.startup)
22270 else:
22271 wx.CallLater(int(1000 / 30.0), self.startup)
22272 return
22273 # Give 20 seconds for display & instrument enumeration to run.
22274 # This should be plenty and will kill the subprocess in case it hangs.
22275 self.timeout = wx.CallLater(20000, self.worker.abort_subprocess)
22276 inst_count = len(getcfg("instruments"))
22277 delayedresult.startWorker(
22278 self.setup_frame,
22279 self.worker.enumerate_displays_and_ports,
22280 wkwargs={
22281 "enumerate_ports": not FORCE_SKIP_INITIAL_INSTRUMENT_DETECTION
22282 and (
22283 getcfg("enumerate_ports.auto")
22284 # Always detect instruments when
22285 # there were several instruments
22286 # the last time the app was used.
22287 # This is actually required under
22288 # Win10 1903 or newer because
22289 # ordering is not guaranteed
22290 # consistent between reboots even
22291 # if the connected instruments are
22292 # the same.
22293 # For consistency's sake, do it under
22294 # all platforms.
22295 or not inst_count
22296 or inst_count > 1
22297 ),
22298 "silent": True,
22299 },
22300 )
22301
22302 def setup_frame(self, result: delayedresult.DelayedResult) -> None:
22303 """Set up the main frame after the splash screen.
22304
22305 Args:
22306 result (delayedresult.DelayedResult): The result of the worker
22307 enumeration.
22308 """
22309 if self.timeout.IsRunning():
22310 self.timeout.Stop()
22311 self.timeout = None
22312 try:
22313 result.get()
22314 except Exception as exception:
22315 if hasattr(exception, "originalTraceback"):
22316 error = exception.originalTraceback
22317 else:
22318 error = traceback.format_exc()
22319 print(error)
22320 show_result_dialog(UnloggedError(exception))
22321 verbose_print(lang.getstr("initializing_gui"))
22322 app = wx.GetApp()
22323 app.frame = MainFrame(self.worker)
22324 self.setup_frame_finish(app)
22325
22326 def setup_frame_finish(self, app: wx.App) -> None:
22327 """Finish setting up the main frame after the splash screen.
22328
22329 Args:
22330 app (wx.App): The wx application instance.
22331 """
22332 if self.IsShown() and self._alpha > 0:
22333 self._alpha -= 15
22334 self._alpha = max(self._alpha, 0)
22335 self.SetTransparent(self._alpha)
22336 if sys.platform not in ("darwin", "win32"):
22337 self.Refresh()
22338 self.Update()
22339 wx.CallLater(1, self.setup_frame_finish, app)
22340 return
22341 app.SetTopWindow(app.frame)
22342 app.frame.listen()
22343 app.frame.Show()
22344 app.process_argv(1)
22345 wx.CallAfter(app.frame.Raise)
22346 # Check for updates if configured
22347 if getcfg("update_check"):
22348 # Give time for the main window to gain focus before checking for
22349 # update, otherwise the main window may steal the update
22350 # confirmation dialog's focus which looks weird
22351 wx.CallAfter(app.frame.app_update_check_handler, None, silent=True)
22352 else:
22353 # Check if we need to run instrument setup
22354 wx.CallAfter(
22355 app.frame.check_instrument_setup,
22356 check_donation,
22357 (app.frame, False),
22358 )
22359 # If resources are missing, XRC shows an error dialog which immediately
22360 # gets hidden when we close ourselves because we are the parent.
22361 # Hide instead.
22362 win = app.frame.get_top_window()
22363 if isinstance(win, wx.Dialog):
22364 if isinstance(self, wx.Dialog):
22365 self.EndModal(wx.ID_CANCEL)
22366 else:
22367 self.Hide()
22368 else:
22369 self.Destroy()
22370
22371 def OnEraseBackground(self, event: wx.EraseEvent) -> None: # noqa: N802
22372 """Handle the erase background event for the splash screen.
22373
22374 Args:
22375 event (wx.EraseEvent): The erase event.
22376 """
22377
22378 def OnPaint(self, event: wx.PaintEvent) -> None: # noqa: N802
22379 """Handle the paint event for the splash screen.
22380
22381 Args:
22382 event (wx.PaintEvent): The paint event.
22383 """
22384 if sys.platform != "win32":
22385 # AutoBufferedPaintDCFactory is the magic needed for crisp text
22386 # rendering in HiDPI mode under OS X and Linux
22387 cls = wx.AutoBufferedPaintDCFactory
22388 else:
22389 cls = wx.BufferedPaintDC
22390 self.Draw(cls(self))
22391
22392 def Draw(self, dc: wx.DC) -> None: # noqa: N802
22393 """Draw the splash screen.
22394
22395 Args:
22396 dc (wx.DC): The device context to draw on.
22397 """
22398 # Background
22399 dc.SetBackgroundMode(wx.BRUSHSTYLE_TRANSPARENT)
22400 if isinstance(dc, wx.ScreenDC):
22401 dc.StartDrawingOnTop()
22402 x, y = self.splash_x, self.splash_y
22403 else:
22404 dc.Clear()
22405 if hasattr(self, "_buffereddc"):
22406 dc.Blit(
22407 0,
22408 0,
22409 self.splash_bmp.Size[0],
22410 self.splash_bmp.Size[1],
22411 self._buffereddc,
22412 0,
22413 0,
22414 )
22415 x = y = 0
22416 if self.frame < len(self.zoom_scales):
22417 pdc = dc
22418 bufferbitmap = wx.EmptyBitmap(
22419 self.splash_bmp.Size[0], self.splash_bmp.Size[1]
22420 )
22421 dc = wx.MemoryDC()
22422 dc.SelectObject(bufferbitmap)
22423 dc.SetBackgroundMode(wx.BRUSHSTYLE_TRANSPARENT)
22424 dc.DrawBitmap(self.splash_bmp, x, y)
22425 # Text
22426 rect = wx.Rect(
22427 0, int(self.splash_bmp.Size[1] * 0.75), self.splash_bmp.Size[0], 40
22428 )
22429 dc.SetFont(self.GetFont())
22430 # Version label
22431 label_str = VERSION_STRING
22432 dc.SetTextForeground("#101010")
22433 yoff = 10
22434 scale = getcfg("app.dpi") / config.get_default_dpi()
22435 if scale > 1:
22436 yoff = round(yoff * scale)
22437 yoff -= 10
22438 dc.DrawLabel(
22439 label_str,
22440 wx.Rect(rect.x, 110 + yoff, rect.width, 32),
22441 wx.ALIGN_CENTER | wx.ALIGN_TOP,
22442 )
22443 dc.SetTextForeground(wx.BLACK)
22444 dc.DrawLabel(
22445 label_str,
22446 wx.Rect(rect.x, 111 + yoff, rect.width, 32),
22447 wx.ALIGN_CENTER | wx.ALIGN_TOP,
22448 )
22449 dc.SetTextForeground("#CCCCCC")
22450 dc.DrawLabel(
22451 label_str,
22452 wx.Rect(rect.x, 112 + yoff, rect.width, 32),
22453 wx.ALIGN_CENTER | wx.ALIGN_TOP,
22454 )
22455 # Message
22456 dc.SetTextForeground("#101010")
22457 dc.DrawLabel(
22458 self._msg,
22459 wx.Rect(rect.x, rect.y + 2, rect.width, rect.height),
22460 wx.ALIGN_CENTER | wx.ALIGN_TOP,
22461 )
22462 dc.SetTextForeground(wx.BLACK)
22463 dc.DrawLabel(
22464 self._msg,
22465 wx.Rect(rect.x, rect.y + 1, rect.width, rect.height),
22466 wx.ALIGN_CENTER | wx.ALIGN_TOP,
22467 )
22468 dc.SetTextForeground("#CCCCCC")
22469 dc.DrawLabel(self._msg, rect, wx.ALIGN_CENTER | wx.ALIGN_TOP)
22470 if self.frame < len(self.zoom_scales):
22471 # Zoom
22472 dc.DrawBitmap(self.splash_anim[0], x, y)
22473 dc.SelectObject(wx.NullBitmap)
22474 scale = self.zoom_scales[self.frame]
22475 frame = bufferbitmap.ConvertToImage()
22476 frame.SetAlphaData(self.splash_alpha)
22477 if scale < 1:
22478 frame = frame.Blur(round(1 * (1 - scale)))
22479 if wx.VERSION > (3,):
22480 quality = wx.IMAGE_QUALITY_BILINEAR
22481 else:
22482 quality = wx.IMAGE_QUALITY_HIGH
22483 frame.Rescale(
22484 max(round(self.splash_bmp.Size[0] * scale), 1),
22485 max(round(self.splash_bmp.Size[1] * scale), 1),
22486 quality,
22487 )
22488 frame.Resize(
22489 self.splash_bmp.Size,
22490 (
22491 round(self.splash_bmp.Size[0] / 2 - frame.Width / 2),
22492 round(self.splash_bmp.Size[1] / 2 - frame.Height / 2),
22493 ),
22494 )
22495 pdc.DrawBitmap(frame.ConvertToBitmap(), x, y)
22496 else:
22497 # Animation
22498 if self.splash_anim:
22499 dc.DrawBitmap(
22500 self.splash_anim[
22501 min(
22502 self.frame - len(self.zoom_scales),
22503 len(self.splash_anim) - 1,
22504 )
22505 ],
22506 x,
22507 y,
22508 )
22509 if self.frame > len(self.zoom_scales) + len(self.splash_anim) - 1:
22510 dc.DrawBitmap(
22511 self.splash_version_anim[
22512 self.frame - len(self.zoom_scales) - len(self.splash_anim)
22513 ],
22514 x,
22515 y,
22516 )
22517 if isinstance(dc, wx.ScreenDC):
22518 dc.EndDrawingOnTop()
22519
22520 def Pulse(self, msg: None | str = None) -> tuple[bool, bool]: # noqa: N802
22521 """Pulse the splash screen with a message.
22522
22523 Args:
22524 msg (None | str): The message to display on the splash screen.
22525
22526 Returns:
22527 tuple[bool, bool]: A tuple indicating whether the message was set
22528 and whether the splash screen is shown.
22529 """
22530 if msg:
22531 self._msg = msg
22532 if self.IsShown():
22533 self.Refresh()
22534 self.Update()
22535 return True, False
22536
22537 def SetWindowShape(self, *args) -> None: # noqa: N802
22538 """Set the window shape to the splash bitmap."""
22539 r = wx.RegionFromBitmapColour(self.mask_bmp, wx.BLACK)
22540 self.hasShape = self.SetShape(r)
22541
22542 UpdatePulse = Pulse
22543
22544
22545 class MeasurementFileCheckSanityDialog(ConfirmDialog):
22546 """Dialog to check the sanity of a measurement file.
22547
22548 Args:
22549 parent (wx.Window): The parent window for the dialog.
22550 ti3 (CGATS): The measurement file to check.
22551 suspicious (list): List of suspicious measurements.
22552 force (bool): Whether to force the dialog to show even if no suspicious
22553 measurements are found.
22554 """
22555
22556 def __init__(
22557 self, parent: wx.Windows, ti3: CGATS, suspicious: list, force: bool = False
22558 ) -> None:
22559 scale = getcfg("app.dpi") / config.get_default_dpi()
22560 scale = max(scale, 1)
22561 ConfirmDialog.__init__(
22562 self,
22563 parent,
22564 title=(
22565 os.path.basename(ti3.filename)
22566 if ti3.filename
22567 else lang.getstr("measurement_file.check_sanity")
22568 ),
22569 ok=lang.getstr("ok"),
22570 cancel=lang.getstr("cancel"),
22571 alt=lang.getstr("invert_selection"),
22572 bitmap=get_icon(32, "dialog-warning"),
22573 wrap=120,
22574 )
22575 msg_col1 = lang.getstr("warning.suspicious_delta_e")
22576 msg_col2 = lang.getstr("warning.suspicious_delta_e.info")
22577
22578 margin = 12
22579
22580 dlg = self
22581
22582 dlg.sizer3.Remove(0) # Remove message textbox
22583 dlg.message.Destroy()
22584 dlg.sizer4 = wx.BoxSizer(wx.HORIZONTAL)
22585 dlg.sizer3.Add(dlg.sizer4)
22586 dlg.message_col1 = wx.StaticText(dlg, -1, msg_col1)
22587 dlg.message_col1.Wrap(int(450 * scale))
22588 dlg.sizer4.Add(dlg.message_col1, flag=wx.RIGHT, border=20)
22589 dlg.message_col2 = wx.StaticText(dlg, -1, msg_col2)
22590 dlg.message_col2.Wrap(int(450 * scale))
22591 dlg.sizer4.Add(dlg.message_col2, flag=wx.LEFT, border=20)
22592
22593 dlg.Unbind(wx.EVT_BUTTON, dlg.alt)
22594 dlg.Bind(wx.EVT_BUTTON, dlg.invert_selection_handler, id=dlg.alt.GetId())
22595
22596 dlg.select_all_btn = wx.Button(dlg.buttonpanel, -1, lang.getstr("deselect_all"))
22597 dlg.sizer2.Insert(2, dlg.select_all_btn)
22598 dlg.sizer2.Insert(2, (margin, margin))
22599 dlg.Bind(wx.EVT_BUTTON, dlg.select_all_handler, id=dlg.select_all_btn.GetId())
22600
22601 dlg.ti3 = ti3
22602 dlg.suspicious = suspicious
22603 dlg.mods = {}
22604 dlg.force = force
22605
22606 style = wx.BORDER_SIMPLE if "gtk3" in wx.PlatformInfo else wx.BORDER_THEME
22607 dlg.grid = CustomGrid(
22608 dlg, -1, size=(int(940 * scale), int(200 * scale)), style=style
22609 )
22610 grid = dlg.grid
22611 grid.DisableDragRowSize()
22612 grid.SetCellHighlightPenWidth(0)
22613 grid.SetCellHighlightROPenWidth(0)
22614 grid.SetDefaultCellAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
22615 grid.SetMargins(0, 0)
22616 grid.SetRowLabelAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
22617 grid.SetScrollRate(5, 5)
22618 grid.draw_horizontal_grid_lines = False
22619 grid.draw_vertical_grid_lines = False
22620 grid.CreateGrid(0, 15)
22621 grid.SetColLabelSize(round(self.grid.GetDefaultRowSize() * 2.4))
22622 dc = wx.MemoryDC(wx.EmptyBitmap(1, 1))
22623 dc.SetFont(grid.GetLabelFont())
22624 w, h = dc.GetTextExtent(
22625 f"99{dlg.ti3.DATA[dlg.ti3.NUMBER_OF_SETS - 1].SAMPLE_ID}"
22626 )
22627 grid.SetRowLabelSize(max(w, grid.GetDefaultRowSize()))
22628 w, h = dc.GetTextExtent("9999999999")
22629 for i in range(grid.GetNumberCols()):
22630 if i in (4, 5) or i > 8:
22631 attr = wx.grid.GridCellAttr()
22632 attr.SetReadOnly(True)
22633 grid.SetColAttr(i, attr)
22634 size = (
22635 (22 * scale)
22636 if i == 0
22637 else self.grid.GetDefaultRowSize()
22638 if i in (4, 5)
22639 else w
22640 )
22641 grid.SetColSize(i, int(size))
22642 for i, label in enumerate(
22643 [
22644 "",
22645 "R %",
22646 "G %",
22647 "B %",
22648 "",
22649 "",
22650 "X",
22651 "Y",
22652 "Z",
22653 "\u0394E*00\nXYZ A/B",
22654 "0.5 \u0394E*00\nRGB A/B",
22655 "\u0394E*00\nRGB-XYZ",
22656 "\u0394L*00\nRGB-XYZ",
22657 "\u0394C*00\nRGB-XYZ",
22658 "\u0394H*00\nRGB-XYZ",
22659 ]
22660 ):
22661 grid.SetColLabelValue(i, label)
22662 attr = wx.grid.GridCellAttr()
22663 # attr.SetReadOnly(True)
22664 attr.SetRenderer(CustomCellBoolRenderer())
22665 grid.SetColAttr(0, attr)
22666 font = grid.GetDefaultCellFont()
22667 if font.PointSize > 11:
22668 font.PointSize = 11
22669 grid.SetDefaultCellFont(font)
22670 grid.DisableDragColSize()
22671 grid.EnableGridLines(False)
22672
22673 black = ti3.queryi1({"RGB_R": 0, "RGB_G": 0, "RGB_B": 0})
22674 black = black["XYZ_X"], black["XYZ_Y"], black["XYZ_Z"] if black else black
22675 dlg.black = black
22676 white = ti3.queryi1({"RGB_R": 100, "RGB_G": 100, "RGB_B": 100})
22677 white = white["XYZ_X"], white["XYZ_Y"], white["XYZ_Z"] if white else white
22678 dlg.white = white
22679 dlg.suspicious_items = []
22680 grid.BeginBatch()
22681 for _i, (
22682 prev,
22683 item,
22684 delta,
22685 sRGB_delta, # noqa: N806
22686 prev_delta_to_sRGB, # noqa: N806
22687 delta_to_sRGB, # noqa: N806
22688 ) in enumerate(suspicious):
22689 for cur in (prev, item):
22690 if not cur or cur in dlg.suspicious_items:
22691 continue
22692 dlg.suspicious_items.append(cur)
22693 grid.AppendRows(1)
22694 row = grid.GetNumberRows() - 1
22695 grid.SetRowLabelValue(row, f"{cur.SAMPLE_ID:.0f}")
22696 RGB = [] # noqa: N806
22697 for k, label in enumerate("RGB"):
22698 value = cur[f"RGB_{label}"]
22699 grid.SetCellValue(row, 1 + k, f"{value:.4f}")
22700 RGB.append(value)
22701 XYZ = [] # noqa: N806
22702 for k, label in enumerate("XYZ"):
22703 value = cur[f"XYZ_{label}"]
22704 grid.SetCellValue(row, 6 + k, f"{value:.4f}")
22705 XYZ.append(value)
22706 if cur is prev:
22707 dlg.update_row(row, RGB, XYZ, None, None, prev_delta_to_sRGB)
22708 else:
22709 dlg.update_row(row, RGB, XYZ, delta, sRGB_delta, delta_to_sRGB)
22710 grid.EndBatch()
22711
22712 grid.Bind(wx.EVT_KEY_DOWN, dlg.key_handler)
22713 grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, dlg.cell_change_handler)
22714 grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, dlg.cell_click_handler)
22715
22716 dlg.sizer3.Add(grid, 1, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
22717
22718 dlg.buttonpanel.Layout()
22719 dlg.sizer0.SetSizeHints(dlg)
22720 dlg.sizer0.Layout()
22721
22722 # This workaround is needed to update cell colours
22723 grid.SelectAll()
22724 grid.ClearSelection()
22725
22726 dlg.Center()
22727
22728 def cell_change_handler(self, event: wx.grid.GridEvent) -> None:
22729 """Handle cell change events in the grid.
22730
22731 Args:
22732 event (wx.grid.GridEvent): The grid event that triggered this method.
22733
22734 Raises:
22735 ValueError: If the value entered in the cell is invalid.
22736 """
22737 dlg = self
22738 grid = dlg.grid
22739 if event.Col <= 0:
22740 dlg.check_select_status()
22741 return
22742 item = dlg.suspicious_items[event.Row]
22743 label = "_RGB__XYZ"[event.Col]
22744 label = f"RGB_{label}" if event.Col < 6 else f"XYZ_{label}"
22745 strval = "0{}".format(grid.GetCellValue(event.Row, event.Col).replace(",", "."))
22746 try:
22747 value = float(strval)
22748 if (label[:3] == "RGB" or label == "XYZ_Y") and value > 100:
22749 raise ValueError(f"Value {value!r} is invalid")
22750 if value < 0:
22751 raise ValueError(f"Negative value {value!r} is invalid")
22752 except ValueError:
22753 wx.Bell()
22754 strval = f"{item[label]:.4f}"
22755 if "." in strval:
22756 strval = strval.rstrip("0").rstrip(".")
22757 grid.SetCellValue(
22758 event.Row, event.Col, re.sub(r"^0+(?!\.)", "", strval) or "0"
22759 )
22760 return
22761
22762 grid.SetCellValue(event.Row, event.Col, re.sub(r"^0+(?!\.)", "", strval) or "0")
22763 RGB = [float(grid.GetCellValue(event.Row, i)) for i in (1, 2, 3)] # noqa: N806
22764 XYZ = [float(grid.GetCellValue(event.Row, i)) for i in (6, 7, 8)] # noqa: N806
22765 # Update row
22766 (
22767 sRGBLab, # noqa: N806
22768 Lab, # noqa: N806
22769 delta_to_sRGB, # noqa: N806
22770 criteria1,
22771 debuginfo,
22772 ) = check_ti3_criteria1(RGB, XYZ, dlg.black, dlg.white, print_debuginfo=True)
22773 if grid.GetCellValue(event.Row, 9):
22774 prev = dlg.suspicious_items[event.Row - 1]
22775 prev_RGB = prev["RGB_R"], prev["RGB_G"], prev["RGB_B"] # noqa: N806
22776 prev_XYZ = prev["XYZ_X"], prev["XYZ_Y"], prev["XYZ_Z"] # noqa: N806
22777 (
22778 prev_sRGBLab, # noqa: N806
22779 prev_Lab, # noqa: N806
22780 prev_delta_to_sRGB, # noqa: N806
22781 prev_criteria1,
22782 prev_debuginfo,
22783 ) = check_ti3_criteria1(
22784 prev_RGB, prev_XYZ, dlg.black, dlg.white, print_debuginfo=False
22785 )
22786 (delta, sRGB_delta, criteria2) = check_ti3_criteria2( # noqa: N806
22787 prev_Lab, Lab, prev_sRGBLab, sRGBLab, prev_RGB, RGB
22788 )
22789 else:
22790 delta, sRGB_delta = (None,) * 2 # noqa: N806
22791 dlg.update_row(event.Row, RGB, XYZ, delta, sRGB_delta, delta_to_sRGB)
22792
22793 if item[label] != value:
22794 if not dlg.mods.get(event.Row):
22795 dlg.mods[event.Row] = {}
22796 dlg.mods[event.Row][label] = value
22797
22798 dlg.ok.Enable(not dlg.force or bool(dlg.mods))
22799
22800 # This workaround is needed to update cell colours
22801 cells = grid.GetSelection()
22802 grid.SelectAll()
22803 grid.ClearSelection()
22804 for row, col in cells:
22805 grid.SelectBlock(row, col, row, col, True)
22806
22807 def cell_click_handler(self, event: wx.grid.GridEvent) -> None:
22808 """Handle cell click events in the grid.
22809
22810 Args:
22811 event (wx.grid.GridEvent): The grid event that triggered this
22812 method.
22813 """
22814 if event.Col != 0:
22815 event.Skip()
22816 return
22817
22818 value = "" if self.grid.GetCellValue(event.Row, event.Col) else "1"
22819 self.grid.SetCellValue(event.Row, event.Col, value)
22820 self.check_select_status()
22821 event.Skip()
22822
22823 def check_select_status(
22824 self,
22825 has_false_values: None | bool = None,
22826 has_true_values: None | bool = None,
22827 ) -> None:
22828 """Check the selection status of the grid and update the dialog buttons.
22829
22830 Args:
22831 has_false_values (None | bool): If True, there are rows with false
22832 values.
22833 has_true_values (None | bool): If True, there are rows with true
22834 values.
22835 """
22836 dlg = self
22837 if None in (has_false_values, has_true_values):
22838 for index in range(dlg.grid.GetNumberRows()):
22839 if dlg.grid.GetCellValue(index, 0) != "1":
22840 has_false_values = True
22841 else:
22842 has_true_values = True
22843 dlg.ok.Enable(has_false_values or not self.force or bool(dlg.mods))
22844 if has_true_values:
22845 dlg.select_all_btn.SetLabel(lang.getstr("deselect_all"))
22846 else:
22847 dlg.select_all_btn.SetLabel(lang.getstr("select_all"))
22848
22849 def invert_selection_handler(self, event: wx.Event) -> None:
22850 """Invert the selection of rows in the grid.
22851
22852 Args:
22853 event (wx.Event): The event that triggered this method.
22854 """
22855 dlg = self
22856 has_false_values = False
22857 has_true_values = False
22858 for index in range(dlg.grid.GetNumberRows()):
22859 if dlg.grid.GetCellValue(index, 0) == "1":
22860 value = ""
22861 has_false_values = True
22862 else:
22863 value = "1"
22864 has_true_values = True
22865 dlg.grid.SetCellValue(index, 0, value)
22866 self.check_select_status(has_false_values, has_true_values)
22867
22868 def key_handler(self, event: wx.Event) -> None:
22869 """Handle key events in the grid.
22870
22871 Args:
22872 event (wx.Event): The key event that triggered this method.
22873 """
22874 dlg = self
22875 if event.KeyCode != wx.WXK_SPACE:
22876 event.Skip()
22877 return
22878 if dlg.grid.GridCursorCol != 0:
22879 return
22880 dlg.cell_click_handler(
22881 CustomGridCellEvent(
22882 wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
22883 dlg.grid,
22884 dlg.grid.GridCursorRow,
22885 dlg.grid.GridCursorCol,
22886 )
22887 )
22888
22889 def mark_cell(self, row: int, col: int, ok: bool = False) -> None:
22890 """Mark a cell in the grid with a bold font and red text if not ok.
22891
22892 Args:
22893 row (int): The row index of the cell to mark.
22894 col (int): The column index of the cell to mark.
22895 ok (bool, optional): If True, the cell will be marked as ok (normal
22896 font and color).
22897 """
22898 grid = self.grid
22899 font = grid.GetCellFont(row, col)
22900 font.SetWeight(wx.FONTWEIGHT_NORMAL if ok else wx.FONTWEIGHT_BOLD)
22901 grid.SetCellFont(row, col, font)
22902 grid.SetCellTextColour(
22903 row, col, grid.GetDefaultCellTextColour() if ok else wx.Colour(204, 0, 0)
22904 )
22905
22906 def select_all_handler(self, event: wx.Event) -> None:
22907 """Toggle selection of all rows in the grid.
22908
22909 Args:
22910 event (wx.Event): The event that triggered this method.
22911 """
22912 dlg = self
22913 if dlg.select_all_btn.GetLabel() == lang.getstr("select_all"):
22914 value = "1"
22915 else:
22916 value = ""
22917 for index in range(dlg.grid.GetNumberRows()):
22918 dlg.grid.SetCellValue(index, 0, value)
22919 self.check_select_status(not value, value)
22920
22921 def update_row(
22922 self,
22923 row: int,
22924 RGB: list[float], # noqa: N803
22925 XYZ: list[float], # noqa: N803
22926 delta: None | dict,
22927 sRGB_delta: None | dict, # noqa: N803
22928 delta_to_sRGB: dict, # noqa: N803
22929 ) -> None:
22930 """Update a grid row with RGB, XYZ, and delta and delta_to_sRGB values.
22931
22932 Args:
22933 row (int): The row index to update.
22934 RGB (list): A list of RGB values as floats in the range [0, 100].
22935 XYZ (list): A list of XYZ values as floats in the range [0, 100].
22936 delta (None | dict): A dictionary containing delta values or None.
22937 sRGB_delta (None | dict): A dictionary containing sRGB delta values
22938 or None.
22939 delta_to_sRGB (dict): A dictionary containing delta values to sRGB.
22940 It should contain keys 'E', 'L', 'C', 'H', and their
22941 corresponding '_ok' values indicating whether the deltas
22942 are within acceptable limits.
22943 """
22944 dlg = self
22945 grid = dlg.grid
22946 # XXX: Careful when rounding floats!
22947 # Incorrect: int(round(50 * 2.55)) = 127 (127.499999)
22948 # Correct: int(round(50 / 100.0 * 255)) = 128 (127.5)
22949 RGB255 = [round(v / 100.0 * 255) for v in RGB] # noqa: N806
22950 dlg.grid.SetCellBackgroundColour(row, 4, wx.Colour(*RGB255))
22951 if dlg.white:
22952 XYZ = colormath.adapt(XYZ[0], XYZ[1], XYZ[2], dlg.white, "D65") # noqa: N806
22953 RGB255 = [ # noqa: N806
22954 round(v)
22955 for v in colormath.XYZ2RGB(
22956 XYZ[0] / 100.0, XYZ[1] / 100.0, XYZ[2] / 100.0, scale=255
22957 )
22958 ]
22959 dlg.grid.SetCellBackgroundColour(row, 5, wx.Colour(*RGB255))
22960 grid.SetCellValue(
22961 row,
22962 0,
22963 (
22964 "1"
22965 if (not delta or (delta["E_ok"] and delta["L_ok"]))
22966 and delta_to_sRGB["ok"]
22967 else ""
22968 ),
22969 )
22970 for col in range(3):
22971 dlg.mark_cell(
22972 row,
22973 6 + col,
22974 (not delta or (delta["E_ok"] and (delta["L_ok"] or col != 1)))
22975 and delta_to_sRGB["ok"],
22976 )
22977 if delta:
22978 grid.SetCellValue(row, 9, f"{delta['E']:.2f}")
22979 dlg.mark_cell(row, 9, delta["E_ok"])
22980 if sRGB_delta:
22981 grid.SetCellValue(row, 10, f"{sRGB_delta['E']:.2f}")
22982 for col, elch in enumerate("ELCH"):
22983 grid.SetCellValue(row, 11 + col, f"{delta_to_sRGB[elch]:.2f}")
22984 dlg.mark_cell(row, 11 + col, delta_to_sRGB[f"{elch}_ok"])
22985
22986
22987 def main() -> None:
22988 """Main function to start the application."""
22989 initcfg()
22990 lang.init()
22991 # Startup messages
22992 verbose_print(lang.getstr("startup"))
22993 if sys.platform != "darwin":
22994 if not AUTOSTART:
22995 print(lang.getstr("warning.autostart_system"))
22996 if not AUTOSTART_HOME:
22997 print(lang.getstr("warning.autostart_user"))
22998 app = BaseApp(0) # Don't redirect stdin/stdout
22999 app.TopWindow = StartupFrame()
23000 app.MainLoop()
23001
23002
23003 if __name__ == "__main__":
23004 main()