| 1 |
"""Core functionality for display calibration and profiling workflows. |
| 2 |
|
| 3 |
It includes classes and methods for interacting with hardware instruments, |
| 4 |
handling pattern generators, managing profiles, and executing Argyll CMS |
| 5 |
utilities. The module also supports various platform-specific features and |
| 6 |
integrates with external tools like madVR and colord. |
| 7 |
""" |
| 8 |
|
| 9 |
# stdlib |
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
import atexit |
| 13 |
import codecs |
| 14 |
import contextlib |
| 15 |
import ctypes |
| 16 |
import datetime |
| 17 |
import functools |
| 18 |
import getpass |
| 19 |
import http.client |
| 20 |
import math |
| 21 |
import mimetypes |
| 22 |
import operator |
| 23 |
import os |
| 24 |
import platform |
| 25 |
import random |
| 26 |
import re |
| 27 |
import shutil |
| 28 |
import socket |
| 29 |
import string |
| 30 |
import struct |
| 31 |
import subprocess as sp |
| 32 |
import sys |
| 33 |
import tempfile |
| 34 |
import textwrap |
| 35 |
import threading |
| 36 |
import traceback |
| 37 |
import urllib.error |
| 38 |
import urllib.parse |
| 39 |
import urllib.request |
| 40 |
import warnings |
| 41 |
import zipfile |
| 42 |
import zlib |
| 43 |
from binascii import hexlify |
| 44 |
from collections import UserString |
| 45 |
from functools import partial |
| 46 |
from hashlib import md5, sha256 |
| 47 |
from io import BytesIO |
| 48 |
from pathlib import Path |
| 49 |
from threading import current_thread, main_thread |
| 50 |
from time import sleep, strftime, time |
| 51 |
from typing import Any, Callable, ClassVar |
| 52 |
|
| 53 |
import distro |
| 54 |
from send2trash import send2trash |
| 55 |
|
| 56 |
if sys.platform == "darwin": |
| 57 |
from _thread import start_new_thread |
| 58 |
elif sys.platform == "win32": |
| 59 |
from ctypes import windll |
| 60 |
else: |
| 61 |
import grp |
| 62 |
|
| 63 |
# 3rd party |
| 64 |
if sys.platform == "win32": |
| 65 |
import pythoncom |
| 66 |
import pywintypes |
| 67 |
import win32api |
| 68 |
import win32con |
| 69 |
import win32event |
| 70 |
import winerror |
| 71 |
from win32com.shell import shell as win32com_shell |
| 72 |
|
| 73 |
# custom |
| 74 |
from DisplayCAL import audio, colormath, config, defaultpaths, imfile, madvr, wexpect |
| 75 |
from DisplayCAL import localization as lang |
| 76 |
from DisplayCAL.argyll import ( |
| 77 |
check_argyll_bin, |
| 78 |
check_set_argyll_bin, |
| 79 |
get_argyll_instrument_config, |
| 80 |
get_argyll_util, |
| 81 |
get_argyll_utilname, |
| 82 |
get_argyll_version_string, |
| 83 |
make_argyll_compatible_path, |
| 84 |
parse_argyll_version_string, |
| 85 |
) |
| 86 |
from DisplayCAL.argyll_cgats import ( |
| 87 |
add_dispcal_options_to_cal, |
| 88 |
add_options_to_ti3, |
| 89 |
cal_to_fake_profile, |
| 90 |
cal_to_vcgt, |
| 91 |
extract_cal_from_profile, |
| 92 |
extract_cal_from_ti3, |
| 93 |
extract_device_gray_primaries, |
| 94 |
extract_fix_copy_cal, |
| 95 |
ti3_to_ti1, |
| 96 |
verify_cgats, |
| 97 |
verify_ti1_rgb_xyz, |
| 98 |
) |
| 99 |
from DisplayCAL.argyll_instruments import ( |
| 100 |
get_canonical_instrument_name, |
| 101 |
) |
| 102 |
from DisplayCAL.argyll_instruments import ( |
| 103 |
instruments as all_instruments, |
| 104 |
) |
| 105 |
from DisplayCAL.argyll_names import ( |
| 106 |
INTENTS, |
| 107 |
OBSERVERS, |
| 108 |
VIEWCONDS, |
| 109 |
) |
| 110 |
from DisplayCAL.cgats import ( |
| 111 |
CGATS, |
| 112 |
CGATSError, |
| 113 |
CGATSInvalidError, |
| 114 |
CGATSInvalidOperationError, |
| 115 |
CGATSKeyError, |
| 116 |
CGATSTypeError, |
| 117 |
CGATSValueError, |
| 118 |
rpad, |
| 119 |
sort_by_rec709_luma, |
| 120 |
sort_by_rgb, |
| 121 |
sort_by_rgb_sum, |
| 122 |
stable_sort_by_l, |
| 123 |
) |
| 124 |
from DisplayCAL.colormath import VidRGB_to_eeColor, eeColor_to_VidRGB |
| 125 |
from DisplayCAL.config import ( |
| 126 |
APPBASENAME, |
| 127 |
AUTOSTART, |
| 128 |
AUTOSTART_HOME, |
| 129 |
DEFAULTS, |
| 130 |
ENC, |
| 131 |
EXE, |
| 132 |
EXE_EXT, |
| 133 |
EXEDIR, |
| 134 |
FS_ENC, |
| 135 |
ISAPP, |
| 136 |
PROFILE_EXT, |
| 137 |
PYDIR, |
| 138 |
SCRIPT_EXT, |
| 139 |
get_data_path, |
| 140 |
get_icon, |
| 141 |
get_total_patches, |
| 142 |
getcfg, |
| 143 |
is_ccxx_testchart, |
| 144 |
setcfg, |
| 145 |
setcfg_cond, |
| 146 |
split_display_name, |
| 147 |
writecfg, |
| 148 |
) |
| 149 |
from DisplayCAL.debughelpers import ( |
| 150 |
DownloadError, |
| 151 |
Error, |
| 152 |
Info, |
| 153 |
UnloggedError, |
| 154 |
UnloggedInfo, |
| 155 |
UnloggedWarning, |
| 156 |
UntracedError, |
| 157 |
Warn, |
| 158 |
handle_error, |
| 159 |
) |
| 160 |
from DisplayCAL.edid import WMIError, get_display_name_from_system_profiler, get_edid |
| 161 |
from DisplayCAL.icc_profile import ( |
| 162 |
GAMUT_VOLUME_SRGB, |
| 163 |
ChromaticAdaptionTag, |
| 164 |
ChromaticityType, |
| 165 |
CRInterpolation, |
| 166 |
CurveType, |
| 167 |
DictType, |
| 168 |
ICCProfile, |
| 169 |
ICCProfileInvalidError, |
| 170 |
ICCProfileTag, |
| 171 |
LUT16Type, |
| 172 |
MultiLocalizedUnicodeType, |
| 173 |
ProfileSequenceDescType, |
| 174 |
Text, |
| 175 |
TextDescriptionType, |
| 176 |
TextType, |
| 177 |
VideoCardGammaTableType, |
| 178 |
VideoCardGammaType, |
| 179 |
XYZType, |
| 180 |
_mp_apply, |
| 181 |
create_RGB_A2B_XYZ, |
| 182 |
create_synthetic_hdr_clut_profile, |
| 183 |
get_display_profile, |
| 184 |
s15Fixed16Number, |
| 185 |
s15Fixed16Number_tohex, |
| 186 |
set_display_profile, |
| 187 |
) |
| 188 |
from DisplayCAL.log import LOG, DummyLogger, LogFile, get_file_logger |
| 189 |
from DisplayCAL.meta import DOMAIN, VERSION_STRING |
| 190 |
from DisplayCAL.meta import NAME as APPNAME |
| 191 |
from DisplayCAL.multiprocess import cpu_count, pool_slice |
| 192 |
from DisplayCAL.network import LoggingHTTPRedirectHandler, NoHTTPRedirectHandler |
| 193 |
from DisplayCAL.options import ( |
| 194 |
ALWAYS_FAIL_DOWNLOAD, |
| 195 |
DEBUG, |
| 196 |
EECOLOR65, |
| 197 |
EXPERIMENTAL, |
| 198 |
TEST, |
| 199 |
TEST_BADSSL, |
| 200 |
TEST_REQUIRE_SENSOR_CAL, |
| 201 |
VERBOSE, |
| 202 |
) |
| 203 |
from DisplayCAL.patterngenerators import ( |
| 204 |
PrismaPatternGeneratorClient, |
| 205 |
ResolveCMPatternGeneratorServer, |
| 206 |
ResolveLSPatternGeneratorServer, |
| 207 |
WebWinHTTPPatternGeneratorServer, |
| 208 |
) |
| 209 |
from DisplayCAL.util_decimal import stripzeros |
| 210 |
from DisplayCAL.util_dict import dict_sort |
| 211 |
from DisplayCAL.util_http import encode_multipart_formdata |
| 212 |
from DisplayCAL.util_io import ( |
| 213 |
EncodedWriter, |
| 214 |
Files, |
| 215 |
GzipFileProper, |
| 216 |
LineBufferedStream, |
| 217 |
LineCache, |
| 218 |
TarFileProper, |
| 219 |
) |
| 220 |
from DisplayCAL.util_io import StringIOu as StringIO |
| 221 |
from DisplayCAL.util_list import intlist, natsort |
| 222 |
|
| 223 |
if sys.platform == "darwin": |
| 224 |
from DisplayCAL.util_mac import ( |
| 225 |
get_model_id, |
| 226 |
mac_app_activate, |
| 227 |
mac_terminal_do_script, |
| 228 |
mac_terminal_set_colors, |
| 229 |
osascript, |
| 230 |
) |
| 231 |
elif sys.platform == "win32": |
| 232 |
from DisplayCAL import util_win |
| 233 |
from DisplayCAL.util_win import run_as_admin, shell_exec, win_ver |
| 234 |
|
| 235 |
try: |
| 236 |
import wmi |
| 237 |
except Exception as exception: |
| 238 |
print("Error - could not import WMI:", exception) |
| 239 |
wmi = None |
| 240 |
else: |
| 241 |
# Linux |
| 242 |
from DisplayCAL.defaultpaths import XDG_DATA_HOME |
| 243 |
|
| 244 |
try: |
| 245 |
from DisplayCAL.util_dbus import ( |
| 246 |
BUSTYPE_SESSION, |
| 247 |
DBusException, |
| 248 |
DBusObject, |
| 249 |
dbus_session, |
| 250 |
dbus_system, |
| 251 |
) |
| 252 |
except ImportError: |
| 253 |
dbus_session = None |
| 254 |
dbus_system = None |
| 255 |
from DisplayCAL import colord |
| 256 |
from DisplayCAL.util_os import ( |
| 257 |
dlopen, |
| 258 |
getenvu, |
| 259 |
is_superuser, |
| 260 |
launch_file, |
| 261 |
make_win32_compatible_long_path, |
| 262 |
mksfile, |
| 263 |
mkstemp_bypath, |
| 264 |
quote_args, |
| 265 |
which, |
| 266 |
) |
| 267 |
|
| 268 |
if sys.platform not in ("darwin", "win32"): |
| 269 |
from DisplayCAL.util_os import getgroups |
| 270 |
if sys.platform == "win32" and sys.getwindowsversion() >= (6,): |
| 271 |
from DisplayCAL.util_os import win64_disable_file_system_redirection |
| 272 |
|
| 273 |
from DisplayCAL.util_str import ( |
| 274 |
make_filename_safe, |
| 275 |
safe_asciize, |
| 276 |
safe_basestring, |
| 277 |
safe_str, |
| 278 |
strtr, |
| 279 |
universal_newlines, |
| 280 |
) |
| 281 |
from DisplayCAL.worker_base import ( |
| 282 |
WorkerBase, |
| 283 |
Xicclu, |
| 284 |
XiccluMP, |
| 285 |
_mp_generate_B2A_clut, |
| 286 |
_xicclu_mp, |
| 287 |
printcmdline, |
| 288 |
) |
| 289 |
from DisplayCAL.wx_addons import BetterCallLater, BetterWindowDisabler, wx |
| 290 |
from DisplayCAL.wx_display_adjustment_frame import DisplayAdjustmentFrame |
| 291 |
from DisplayCAL.wx_display_uniformity_frame import DisplayUniformityFrame |
| 292 |
from DisplayCAL.wx_untethered_frame import UntetheredFrame |
| 293 |
from DisplayCAL.wx_windows import ( |
| 294 |
ConfirmDialog, |
| 295 |
HtmlInfoDialog, |
| 296 |
InfoDialog, |
| 297 |
ProgressDialog, |
| 298 |
SimpleTerminal, |
| 299 |
show_result_dialog, |
| 300 |
) |
| 301 |
|
| 302 |
real_display_size_mm = None |
| 303 |
if sys.platform not in ("darwin", "win32"): |
| 304 |
try: |
| 305 |
from DisplayCAL import real_display_size_mm |
| 306 |
except ImportError as exception: |
| 307 |
warnings.warn(str(exception), ImportWarning, stacklevel=2) |
| 308 |
from wx.lib import delayedresult |
| 309 |
|
| 310 |
INST_CAL_MSGS = [ |
| 311 |
"Do a reflective white calibration", |
| 312 |
"Do a transmissive white calibration", |
| 313 |
"Do a transmissive dark calibration", |
| 314 |
"Place the instrument on its reflective white reference", |
| 315 |
"Click the instrument on its reflective white reference", |
| 316 |
"Place the instrument in the dark", |
| 317 |
"Place cap on the instrument", # i1 Pro/SpyderX |
| 318 |
"Place ambient adapter and cap on the instrument", |
| 319 |
"Set instrument sensor to calibration position", # ColorMunki |
| 320 |
"Place the instrument on its transmissive white source", |
| 321 |
"Use the appropriate tramissive blocking", |
| 322 |
"Change filter on instrument to", |
| 323 |
] |
| 324 |
USE_WPOPEN = 0 |
| 325 |
|
| 326 |
keycodes = { |
| 327 |
wx.WXK_NUMPAD0: ord("0"), |
| 328 |
wx.WXK_NUMPAD1: ord("1"), |
| 329 |
wx.WXK_NUMPAD2: ord("2"), |
| 330 |
wx.WXK_NUMPAD3: ord("3"), |
| 331 |
wx.WXK_NUMPAD4: ord("4"), |
| 332 |
wx.WXK_NUMPAD5: ord("5"), |
| 333 |
wx.WXK_NUMPAD6: ord("6"), |
| 334 |
wx.WXK_NUMPAD7: ord("7"), |
| 335 |
wx.WXK_NUMPAD8: ord("8"), |
| 336 |
wx.WXK_NUMPAD9: ord("9"), |
| 337 |
wx.WXK_NUMPAD_ADD: ord("+"), |
| 338 |
wx.WXK_NUMPAD_ENTER: ord("\n"), |
| 339 |
wx.WXK_NUMPAD_EQUAL: ord("="), |
| 340 |
wx.WXK_NUMPAD_DIVIDE: ord("/"), |
| 341 |
wx.WXK_NUMPAD_MULTIPLY: ord("*"), |
| 342 |
wx.WXK_NUMPAD_SUBTRACT: ord("-"), |
| 343 |
} |
| 344 |
|
| 345 |
|
| 346 |
workers = [] |
| 347 |
|
| 348 |
|
| 349 |
WAIT_FILE_TEMPLATE = """# coding=utf-8 |
| 350 |
import os, sys, time |
| 351 |
if sys.platform != "win32": |
| 352 |
print(*(["\\nCurrent RGB"] + sys.argv[1:])) |
| 353 |
abortfilename = os.path.join(r"{script_dir}", ".abort") |
| 354 |
okfilename = os.path.join(r"{script_dir}", ".ok") |
| 355 |
while True: |
| 356 |
if os.path.isfile(abortfilename): |
| 357 |
break |
| 358 |
if os.path.isfile(okfilename): |
| 359 |
try: |
| 360 |
os.remove(okfilename) |
| 361 |
except OSError as e: |
| 362 |
pass |
| 363 |
else: |
| 364 |
break |
| 365 |
time.sleep(0.001) |
| 366 |
""" |
| 367 |
|
| 368 |
INSTRUMENT_MEASUREMENT_MODES_TEST_OUTPUT = """Measure spot values, Version 1.7.0_beta |
| 369 |
Author: Graeme W. Gill, licensed under the GPL Version 2 or later |
| 370 |
Diagnostic: Usage requested |
| 371 |
usage: spotread [-options] [logfile] |
| 372 |
-v Verbose mode |
| 373 |
-s Print spectrum for each reading |
| 374 |
-S Plot spectrum for each reading |
| 375 |
-c listno Set communication port from the following list (default 1) |
| 376 |
1 = 'COM13 (Klein K-10)' |
| 377 |
2 = 'COM1' |
| 378 |
3 = 'COM3' |
| 379 |
4 = 'COM4' |
| 380 |
-t Use transmission measurement mode |
| 381 |
-e Use emissive measurement mode (absolute results) |
| 382 |
-eb Use display white brightness relative measurement mode |
| 383 |
-ew Use display white point relative chromatically adjusted mode |
| 384 |
-p Use telephoto measurement mode (absolute results) |
| 385 |
-pb Use projector white brightness relative measurement mode |
| 386 |
-pw Use projector white point relative chromatically adjusted mode |
| 387 |
-a Use ambient measurement mode (absolute results) |
| 388 |
-f Use ambient flash measurement mode (absolute results) |
| 389 |
-y F K-10: Factory Default [Default,CB1] |
| 390 |
c K-10: Default CRT File |
| 391 |
P K-10: Klein DLP Lux |
| 392 |
E K-10: Klein SMPTE C |
| 393 |
b K-10: TVL XVM245 |
| 394 |
d K-10: Klein LED Bk LCD |
| 395 |
m K-10: Klein Plasma |
| 396 |
p K-10: DLP Screen |
| 397 |
o K-10: TVL LEM150 |
| 398 |
O K-10: Sony EL OLED |
| 399 |
z K-10: Eizo CG LCD |
| 400 |
L K-10: FSI 2461W |
| 401 |
h K-10: HP DreamColor 2 |
| 402 |
1 K-10: LCD CCFL Wide Gamut IPS (LCD2690WUXi) |
| 403 |
l|c Other: l = LCD, c = CRT |
| 404 |
-I illum Set simulated instrument illumination using FWA (def -i illum): |
| 405 |
M0, M1, M2, A, C, D50, D50M2, D65, F5, F8, F10 or file.sp] |
| 406 |
-i illum Choose illuminant for computation of CIE XYZ from spectral data & FWA: |
| 407 |
A, C, D50 (def.), D50M2, D65, F5, F8, F10 or file.sp |
| 408 |
-Q observ Choose CIE Observer for spectral data or CCSS instrument: |
| 409 |
1931_2 (def), 1964_10, S&B 1955_2, shaw, J&V 1978_2 |
| 410 |
(Choose FWA during operation) |
| 411 |
-F filter Set filter configuration (if aplicable): |
| 412 |
n None |
| 413 |
p Polarising filter |
| 414 |
6 D65 |
| 415 |
u U.V. Cut |
| 416 |
-E extrafilterfile Apply extra filter compensation file |
| 417 |
-x Display Yxy instead of Lab |
| 418 |
-h Display LCh instead of Lab |
| 419 |
-V Show running average and std. devation from ref. |
| 420 |
-T Display correlated color temperatures and CRI |
| 421 |
-N Disable auto calibration of instrument |
| 422 |
-O Do one cal. or measure and exit |
| 423 |
-H Start in high resolution spectrum mode (if available) |
| 424 |
-X file.ccmx Apply Colorimeter Correction Matrix |
| 425 |
-Y r|n Override refresh, non-refresh display mode |
| 426 |
-Y R:rate Override measured refresh rate with rate Hz |
| 427 |
-Y A Use non-adaptive integration time mode (if available). |
| 428 |
-W n|h|x Override serial port flow control: n = none, h = HW, x = Xon/Xoff |
| 429 |
-D [level] Print debug diagnostics to stderr |
| 430 |
logfile Optional file to save reading results as text""" # noqa: E501 |
| 431 |
|
| 432 |
|
| 433 |
def add_keywords_to_cgats(cgats, keywords): |
| 434 |
"""Add keywords to CGATS.""" |
| 435 |
if not isinstance(cgats, CGATS): |
| 436 |
cgats = CGATS(cgats) |
| 437 |
for keyword in keywords: |
| 438 |
value = keywords[keyword] |
| 439 |
cgats[0].add_keyword(keyword, value) |
| 440 |
return cgats |
| 441 |
|
| 442 |
|
| 443 |
def check_create_dir(path): |
| 444 |
"""Try to create a directory and show an error message on failure.""" |
| 445 |
if not os.path.exists(path): |
| 446 |
try: |
| 447 |
os.makedirs(path) |
| 448 |
except Exception as exception: |
| 449 |
return Error(f"{lang.getstr('error.dir_creation', path)}\n\n{exception}") |
| 450 |
if not os.path.isdir(path): |
| 451 |
return Error(lang.getstr("error.dir_notdir", path)) |
| 452 |
return True |
| 453 |
|
| 454 |
|
| 455 |
def check_cal_isfile(cal=None, missing_msg=None, notfile_msg=None, silent=False): |
| 456 |
"""Check if a calibration file exists and show an error message if not.""" |
| 457 |
if not silent: |
| 458 |
if not missing_msg: |
| 459 |
missing_msg = lang.getstr("error.calibration.file_missing", cal) |
| 460 |
if not notfile_msg: |
| 461 |
notfile_msg = lang.getstr("file_notfile", cal) |
| 462 |
return check_file_isfile(cal, missing_msg, notfile_msg, silent) |
| 463 |
|
| 464 |
|
| 465 |
def check_profile_isfile( |
| 466 |
profile_path=None, missing_msg=None, notfile_msg=None, silent=False |
| 467 |
): |
| 468 |
"""Check if a profile exists and show an error message if not.""" |
| 469 |
if not silent: |
| 470 |
if not missing_msg: |
| 471 |
missing_msg = lang.getstr("error.profile.file_missing", profile_path) |
| 472 |
if not notfile_msg: |
| 473 |
notfile_msg = lang.getstr("file_notfile", profile_path) |
| 474 |
return check_file_isfile(profile_path, missing_msg, notfile_msg, silent) |
| 475 |
|
| 476 |
|
| 477 |
def check_file_isfile(filename, missing_msg=None, notfile_msg=None, silent=False): |
| 478 |
"""Check if a file exists and show an error message if not.""" |
| 479 |
if not os.path.exists(filename): |
| 480 |
if not silent: |
| 481 |
if not missing_msg: |
| 482 |
missing_msg = lang.getstr("file.missing", filename) |
| 483 |
return Error(missing_msg) |
| 484 |
return False |
| 485 |
if not os.path.isfile(filename): |
| 486 |
if not silent: |
| 487 |
if not notfile_msg: |
| 488 |
notfile_msg = lang.getstr("file.notfile", filename) |
| 489 |
return Error(notfile_msg) |
| 490 |
return False |
| 491 |
return True |
| 492 |
|
| 493 |
|
| 494 |
def check_ti3_criteria1( |
| 495 |
RGB, |
| 496 |
XYZ, |
| 497 |
black_XYZ, |
| 498 |
white_XYZ, |
| 499 |
delta_to_sRGB_threshold_E=10, |
| 500 |
delta_to_sRGB_threshold_L=10, |
| 501 |
delta_to_sRGB_threshold_C=75, |
| 502 |
delta_to_sRGB_threshold_H=75, |
| 503 |
print_debuginfo=True, |
| 504 |
): |
| 505 |
"""Check if delta E between a patch and its sRGB equivalent is suspiciously high.""" |
| 506 |
sRGBLab = colormath.RGB2Lab( |
| 507 |
RGB[0] / 100.0, RGB[1] / 100.0, RGB[2] / 100.0, noadapt=not white_XYZ |
| 508 |
) |
| 509 |
if white_XYZ: |
| 510 |
if black_XYZ: |
| 511 |
black_Lab = colormath.XYZ2Lab( |
| 512 |
*colormath.adapt(black_XYZ[0], black_XYZ[1], black_XYZ[2], white_XYZ) |
| 513 |
) |
| 514 |
black_C = math.sqrt(math.pow(black_Lab[1], 2) + math.pow(black_Lab[2], 2)) |
| 515 |
if black_Lab[0] < 3 and black_C < 3: |
| 516 |
# Sanity check: Is this color reasonably dark and achromatic? |
| 517 |
# Then do BPC so we can compare better to perfect black sRGB |
| 518 |
XYZ = colormath.blend_blackpoint( |
| 519 |
XYZ[0], XYZ[1], XYZ[2], black_XYZ, None, white_XYZ |
| 520 |
) |
| 521 |
XYZ = colormath.adapt(XYZ[0], XYZ[1], XYZ[2], white_XYZ) |
| 522 |
Lab = colormath.XYZ2Lab(*XYZ) |
| 523 |
|
| 524 |
delta_to_sRGB = colormath.delta(*sRGBLab + Lab + (2000,)) |
| 525 |
|
| 526 |
# Depending on how (a)chromatic the sRGB color is, scale the thresholds |
| 527 |
# Use math derived from DE2000 formula to get chroma and hue angle |
| 528 |
L, a, b = sRGBLab |
| 529 |
b_pow = math.pow(b, 2) |
| 530 |
C = math.sqrt(math.pow(a, 2) + b_pow) |
| 531 |
C_pow = math.pow(C, 7) |
| 532 |
G = 0.5 * (1 - math.sqrt(C_pow / (C_pow + math.pow(25, 7)))) |
| 533 |
a = (1 + G) * a |
| 534 |
C = math.sqrt(math.pow(a, 2) + b_pow) |
| 535 |
h = ( |
| 536 |
0 |
| 537 |
if a == 0 and b == 0 |
| 538 |
else math.degrees(math.atan2(b, a)) + (0 if b >= 0 else 360.0) |
| 539 |
) |
| 540 |
# C and h scaling factors |
| 541 |
C_scale = C / 100.0 |
| 542 |
h_scale = h / 360.0 |
| 543 |
# RGB hue, saturation and value scaling factors |
| 544 |
H, S, V = colormath.RGB2HSV(*[v / 100.0 for v in RGB]) |
| 545 |
SV_scale = S * V |
| 546 |
# Scale the thresholds |
| 547 |
delta_to_sRGB_threshold_E += delta_to_sRGB_threshold_E * max(C_scale, SV_scale) |
| 548 |
delta_to_sRGB_threshold_L += delta_to_sRGB_threshold_L * max(C_scale, SV_scale) |
| 549 |
# Allow higher chroma errors as luminance of reference decreases |
| 550 |
L_scale = max(1 - (1 * C_scale) + (100.0 - L) / 100.0, 1) |
| 551 |
delta_to_sRGB_threshold_C = ( |
| 552 |
delta_to_sRGB_threshold_C * max(C_scale, SV_scale) + 2 |
| 553 |
) * L_scale |
| 554 |
delta_to_sRGB_threshold_H = ( |
| 555 |
delta_to_sRGB_threshold_H * max(C_scale, h_scale, H, SV_scale) + 2 |
| 556 |
) * L_scale |
| 557 |
|
| 558 |
criteria1 = delta_to_sRGB["E"] > delta_to_sRGB_threshold_E and ( |
| 559 |
abs(delta_to_sRGB["L"]) > delta_to_sRGB_threshold_L |
| 560 |
or abs(delta_to_sRGB["C"]) > delta_to_sRGB_threshold_C |
| 561 |
or abs(delta_to_sRGB["H"]) > delta_to_sRGB_threshold_H |
| 562 |
) |
| 563 |
# This patch has an unusually high delta 00 to its sRGB equivalent |
| 564 |
|
| 565 |
delta_to_sRGB["E_ok"] = delta_to_sRGB["E"] <= delta_to_sRGB_threshold_E |
| 566 |
delta_to_sRGB["L_ok"] = abs(delta_to_sRGB["L"]) <= delta_to_sRGB_threshold_L |
| 567 |
delta_to_sRGB["C_ok"] = abs(delta_to_sRGB["C"]) <= delta_to_sRGB_threshold_C |
| 568 |
delta_to_sRGB["H_ok"] = abs(delta_to_sRGB["H"]) <= delta_to_sRGB_threshold_H |
| 569 |
delta_to_sRGB["ok"] = ( |
| 570 |
delta_to_sRGB["E_ok"] |
| 571 |
and delta_to_sRGB["L_ok"] |
| 572 |
and delta_to_sRGB["C_ok"] |
| 573 |
and delta_to_sRGB["H_ok"] |
| 574 |
) |
| 575 |
|
| 576 |
debuginfo = ( |
| 577 |
f"RGB: {RGB[0]:6.2f} {RGB[1]:6.2f} {RGB[2]:6.2f} " |
| 578 |
f"RGB(sRGB)->Lab(D50): {sRGBLab[0]:6.2f} {sRGBLab[1]:6.2f} {sRGBLab[2]:6.2f} " |
| 579 |
f"L_scale: {L_scale:5.3f} C: {C:5.2f} C_scale: {C_scale:5.3f} h: {h:5.2f} " |
| 580 |
f"h_scale: {h_scale:5.3f} H: {H * 360:5.2f} H_scale: {H:5.3f} S: {S:5.2f} " |
| 581 |
f"V: {V:5.2f} SV_scale: {SV_scale:5.3f} " |
| 582 |
f"Thresholds: E {delta_to_sRGB_threshold_E:5.2f} " |
| 583 |
f"L {delta_to_sRGB_threshold_L:5.2f} C {delta_to_sRGB_threshold_C:5.2f} " |
| 584 |
f"H {delta_to_sRGB_threshold_H:5.2f} " |
| 585 |
f"XYZ->Lab(D50): {Lab[0]:6.2f} {Lab[1]:6.2f} {Lab[2]:6.2f} " |
| 586 |
f"delta RGB(sRGB)->Lab(D50) to XYZ->Lab(D50): dE {delta_to_sRGB['E']:5.2f} " |
| 587 |
f"dL {delta_to_sRGB['L']:5.2f} dC {delta_to_sRGB['C']:5.2f} " |
| 588 |
f"dH {delta_to_sRGB['H']:5.2f}" |
| 589 |
) |
| 590 |
if print_debuginfo: |
| 591 |
print(debuginfo) |
| 592 |
|
| 593 |
return sRGBLab, Lab, delta_to_sRGB, criteria1, debuginfo |
| 594 |
|
| 595 |
|
| 596 |
def check_ti3_criteria2( |
| 597 |
prev_Lab, Lab, prev_sRGBLab, sRGBLab, prev_RGB, RGB, sRGB_delta_E_scale_factor=0.5 |
| 598 |
): |
| 599 |
"""Check if the delta E between two patches is suspiciously low.""" |
| 600 |
delta = colormath.delta(*prev_Lab + Lab + (2000,)) |
| 601 |
sRGB_delta = colormath.delta(*prev_sRGBLab + sRGBLab + (2000,)) |
| 602 |
sRGB_delta["E"] *= sRGB_delta_E_scale_factor |
| 603 |
|
| 604 |
criteria2 = delta["E"] < sRGB_delta["E"] |
| 605 |
# These two patches have different RGB values |
| 606 |
# but suspiciously low delta E 76. |
| 607 |
|
| 608 |
if criteria2 and ( |
| 609 |
prev_RGB[0] == prev_RGB[1] == prev_RGB[2] and RGB[0] == RGB[1] == RGB[2] |
| 610 |
): |
| 611 |
# If RGB gray, check if the Y difference makes sense |
| 612 |
criteria2 = (RGB[0] > prev_RGB[0] and Lab[0] <= prev_Lab[0]) or ( |
| 613 |
RGB[0] < prev_RGB[0] and Lab[0] >= prev_Lab[0] |
| 614 |
) |
| 615 |
delta["L_ok"] = not criteria2 |
| 616 |
delta["E_ok"] = True |
| 617 |
else: |
| 618 |
delta["E_ok"] = not criteria2 |
| 619 |
delta["L_ok"] = True |
| 620 |
|
| 621 |
return delta, sRGB_delta, criteria2 |
| 622 |
|
| 623 |
|
| 624 |
def check_ti3(ti3, print_debuginfo=True): |
| 625 |
"""Check for suspiciously low delta E between patches with different RGB values. |
| 626 |
|
| 627 |
Used as a means to find misreads. |
| 628 |
|
| 629 |
The expected dE is calculated by converting from a patches RGB values |
| 630 |
(assuming sRGB) to Lab and comparing the values. |
| 631 |
|
| 632 |
""" |
| 633 |
if not isinstance(ti3, CGATS): |
| 634 |
ti3 = CGATS(ti3) |
| 635 |
data = ti3.queryv1("DATA") |
| 636 |
datalen = len(data) |
| 637 |
black = data.queryi1({"RGB_R": 0, "RGB_G": 0, "RGB_B": 0}) |
| 638 |
if black: |
| 639 |
black = black["XYZ_X"], black["XYZ_Y"], black["XYZ_Z"] |
| 640 |
elif print_debuginfo: |
| 641 |
print("Warning - no black patch found in CGATS") |
| 642 |
white = data.queryi1({"RGB_R": 100, "RGB_G": 100, "RGB_B": 100}) |
| 643 |
if white: |
| 644 |
white = white["XYZ_X"], white["XYZ_Y"], white["XYZ_Z"] |
| 645 |
elif print_debuginfo: |
| 646 |
print("Warning - no white patch found in CGATS") |
| 647 |
suspicious = [] |
| 648 |
prev = {} |
| 649 |
delta = {} |
| 650 |
for index in data: |
| 651 |
item = data[index] |
| 652 |
(sRGBLab, Lab, delta_to_sRGB, criteria1, debuginfo) = check_ti3_criteria1( |
| 653 |
(item["RGB_R"], item["RGB_G"], item["RGB_B"]), |
| 654 |
(item["XYZ_X"], item["XYZ_Y"], item["XYZ_Z"]), |
| 655 |
black, |
| 656 |
white, |
| 657 |
print_debuginfo=False, |
| 658 |
) |
| 659 |
if criteria1 or ( |
| 660 |
prev |
| 661 |
and ( |
| 662 |
max(prev["item"]["RGB_R"], item["RGB_R"]) |
| 663 |
- min(prev["item"]["RGB_R"], item["RGB_R"]) |
| 664 |
> 1.0 / 2.55 |
| 665 |
or max(prev["item"]["RGB_G"], item["RGB_G"]) |
| 666 |
- min(prev["item"]["RGB_G"], item["RGB_G"]) |
| 667 |
> 1.0 / 2.55 |
| 668 |
or max(prev["item"]["RGB_B"], item["RGB_B"]) |
| 669 |
- min(prev["item"]["RGB_B"], item["RGB_B"]) |
| 670 |
> 1.0 / 2.55 |
| 671 |
) |
| 672 |
): |
| 673 |
if prev: |
| 674 |
(delta, sRGB_delta, criteria2) = check_ti3_criteria2( |
| 675 |
prev["Lab"], |
| 676 |
Lab, |
| 677 |
prev["sRGBLab"], |
| 678 |
sRGBLab, |
| 679 |
( |
| 680 |
prev["item"]["RGB_R"], |
| 681 |
prev["item"]["RGB_G"], |
| 682 |
prev["item"]["RGB_B"], |
| 683 |
), |
| 684 |
(item["RGB_R"], item["RGB_G"], item["RGB_B"]), |
| 685 |
) |
| 686 |
else: |
| 687 |
criteria2 = False |
| 688 |
if criteria1 or criteria2: |
| 689 |
if print_debuginfo: |
| 690 |
if criteria2: |
| 691 |
debuginfo = ( |
| 692 |
f"{debuginfo} dE to previous XYZ->Lab(D50): " |
| 693 |
f"{delta['E']:5.3f} dE_OK: {delta['E_ok']} " |
| 694 |
f"L_OK: {delta['L_ok']} " |
| 695 |
"0.5 dE RGB(sRGB)->Lab(D50) to previous " |
| 696 |
f"RGB(sRGB)->Lab(D50): {sRGB_delta['E']:5.3f}" |
| 697 |
) |
| 698 |
sample_id = f"Patch #{{:.0{len(str(datalen)):d}f}}" |
| 699 |
print(sample_id.format(item.SAMPLE_ID), debuginfo) |
| 700 |
suspicious.append( |
| 701 |
( |
| 702 |
prev["item"] if criteria2 else None, |
| 703 |
item, |
| 704 |
delta if criteria2 else None, |
| 705 |
sRGB_delta if criteria2 else None, |
| 706 |
prev["delta_to_sRGB"] if criteria2 else None, |
| 707 |
delta_to_sRGB, |
| 708 |
) |
| 709 |
) |
| 710 |
prev["item"] = item |
| 711 |
prev["sRGBLab"] = sRGBLab |
| 712 |
prev["Lab"] = Lab |
| 713 |
prev["delta_to_sRGB"] = delta_to_sRGB |
| 714 |
return suspicious |
| 715 |
|
| 716 |
|
| 717 |
def create_shaper_curves( |
| 718 |
RGB_XYZ, |
| 719 |
bwd_mtx, |
| 720 |
single_curve=False, |
| 721 |
bpc=True, |
| 722 |
logfn=None, |
| 723 |
slope_limit=False, |
| 724 |
profile=None, |
| 725 |
options_dispcal=None, |
| 726 |
optimize=False, |
| 727 |
cat="Bradford", |
| 728 |
): |
| 729 |
"""Create input (device to PCS) shaper curves.""" |
| 730 |
RGB_XYZ = dict_sort(RGB_XYZ) |
| 731 |
R_R = [] |
| 732 |
G_G = [] |
| 733 |
B_B = [] |
| 734 |
R_X = [] |
| 735 |
G_Y = [] |
| 736 |
B_Z = [] |
| 737 |
XYZbp = None |
| 738 |
XYZwp = None |
| 739 |
for R, G, B in RGB_XYZ: |
| 740 |
X, Y, Z = RGB_XYZ[(R, G, B)] |
| 741 |
X, Y, Z = colormath.adapt(X, Y, Z, RGB_XYZ[(100, 100, 100)], cat=cat) |
| 742 |
if 100 > R > 0 and min(X, Y, Z) < 100.0 / 65535: |
| 743 |
# Skip non-black/non-white gray values not encodable in 16-bit |
| 744 |
continue |
| 745 |
if 100 > R > 0 and G_Y and (Y < G_Y[-1] * 100 or Y > 100): # noqa: SIM300 |
| 746 |
# Skip values with negative Y increments, |
| 747 |
# or Y above 100 with RGB < 100 |
| 748 |
if logfn: |
| 749 |
logfn( |
| 750 |
f"Warning: Skipping RGB {R:.2f} {G:.2f} {B:.2f} " |
| 751 |
f"XYZ {X:.6f} {Y:.6f} {Z:.6f}", |
| 752 |
"because Y is not monotonically increasing", |
| 753 |
) |
| 754 |
continue |
| 755 |
R_R.append(R / 100.0) |
| 756 |
G_G.append(G / 100.0) |
| 757 |
B_B.append(B / 100.0) |
| 758 |
R_X.append(X / 100.0) |
| 759 |
G_Y.append(Y / 100.0) |
| 760 |
B_Z.append(Z / 100.0) |
| 761 |
if R == G == B == 0: |
| 762 |
XYZbp = [v / 100.0 for v in (X, Y, Z)] |
| 763 |
elif R == G == B == 100: |
| 764 |
XYZwp = [v / 100.0 for v in (X, Y, Z)] |
| 765 |
|
| 766 |
numvalues = len(R_R) |
| 767 |
|
| 768 |
if numvalues <= 2 or XYZbp[1] >= XYZwp[1] * 0.9: |
| 769 |
# Botched measurements |
| 770 |
raise UntracedError(lang.getstr("error.luminance.not_monotonically_increasing")) |
| 771 |
|
| 772 |
if XYZwp[1] <= 0 or math.isnan(XYZwp[1]): |
| 773 |
raise UntracedError(lang.getstr("error.luminance.invalid")) |
| 774 |
|
| 775 |
# Scale black to zero |
| 776 |
for i in range(numvalues): |
| 777 |
if bwd_mtx * [1, 1, 1] == [1, 1, 1]: |
| 778 |
(R_X[i], G_Y[i], B_Z[i]) = colormath.apply_bpc( |
| 779 |
R_X[i], G_Y[i], B_Z[i], XYZbp, (0, 0, 0), XYZwp |
| 780 |
) |
| 781 |
else: |
| 782 |
(R_X[i], G_Y[i], B_Z[i]) = colormath.blend_blackpoint( |
| 783 |
R_X[i], G_Y[i], B_Z[i], XYZbp |
| 784 |
) |
| 785 |
|
| 786 |
# Interpolate TRC |
| 787 |
|
| 788 |
use_individual_channel_gammas = True |
| 789 |
|
| 790 |
gammas = [[], [], []] |
| 791 |
for j, gamma in enumerate(gammas): |
| 792 |
values = [] |
| 793 |
for i, v in enumerate((R_R, G_G, B_B)[j]): |
| 794 |
channel = (R_X, G_Y, B_Z)[j] |
| 795 |
vv = colormath.convert_range( |
| 796 |
channel[i], channel[0], XYZwp[j], channel[0], 1 |
| 797 |
) |
| 798 |
if use_individual_channel_gammas: |
| 799 |
channel[i] = vv |
| 800 |
values.append((v, vv)) |
| 801 |
gamma[:] = colormath.get_gamma(values, average=False) |
| 802 |
gamma.insert(0, gamma[0]) |
| 803 |
gamma.append(gamma[-1]) |
| 804 |
|
| 805 |
# cLUT profile or Shaper + matrix profile |
| 806 |
final = 2049 if bwd_mtx * [1, 1, 1] == [1, 1, 1] else 256 |
| 807 |
|
| 808 |
if all(len(gamma) == numvalues for gamma in gammas): |
| 809 |
# Follow curvature by using gamma as hint |
| 810 |
# This can be used to fill in 'missing' values with the right slope |
| 811 |
# E.g. suppose we have measured at signal levels 0%, 25%, 50%, 75%, 100% |
| 812 |
# Linearly interpolating between those (or even using polynomials) |
| 813 |
# will yield unacceptable results especially near black due to not |
| 814 |
# following the typical curvature of additive displays. Using this |
| 815 |
# method, a sensible curvature is maintained. |
| 816 |
|
| 817 |
numentries = numvalues |
| 818 |
while numentries < 2**12 + 1: |
| 819 |
numentries = (numentries - 1) * 2 + 1 |
| 820 |
|
| 821 |
RGB = (R_R, G_G, B_B) |
| 822 |
|
| 823 |
gammas_resized = [ |
| 824 |
gamma |
| 825 |
and colormath.interp_fill( |
| 826 |
RGB[j], |
| 827 |
gamma, |
| 828 |
(numvalues - 1) * 2 + 1, |
| 829 |
# numentries, |
| 830 |
True, |
| 831 |
) |
| 832 |
for j, gamma in enumerate(gammas) |
| 833 |
] |
| 834 |
|
| 835 |
for gamma in gammas_resized: |
| 836 |
gamma[1:-1] = colormath.smooth_avg(gamma[1:-1], 1) |
| 837 |
|
| 838 |
gammas_resized = [ |
| 839 |
gamma and colormath.interp_resize(gamma, numentries, True) |
| 840 |
for gamma in gammas_resized |
| 841 |
] |
| 842 |
|
| 843 |
for i in range(1, numvalues - 1): |
| 844 |
X, Y, Z = R_X[i], G_Y[i], B_Z[i] |
| 845 |
if use_individual_channel_gammas: |
| 846 |
R_X[i], G_Y[i], B_Z[i] = ( |
| 847 |
v ** (1.0 / gammas[j][i]) for j, v in enumerate((X, Y, Z)) |
| 848 |
) |
| 849 |
else: |
| 850 |
if Y < 0: |
| 851 |
# This should NOT happen - is this check needed? |
| 852 |
if logfn: |
| 853 |
logfn("Warning: Y is negative - clamping to zero") |
| 854 |
Y = 0 |
| 855 |
if Y: |
| 856 |
Y2 = Y ** (1.0 / gammas[1][i]) |
| 857 |
R_X[i], G_Y[i], B_Z[i] = (v / Y * Y2 for v in (X, Y, Z)) |
| 858 |
|
| 859 |
for j, values in enumerate((R_X, G_Y, B_Z)): |
| 860 |
values[:] = colormath.interp_fill(RGB[j], values, numentries, True) |
| 861 |
|
| 862 |
for i in range(1, numentries - 1): |
| 863 |
X, Y, Z = R_X[i], G_Y[i], B_Z[i] |
| 864 |
if use_individual_channel_gammas: |
| 865 |
X, Y, Z = ( |
| 866 |
colormath.convert_range( |
| 867 |
v ** gammas_resized[j][i], |
| 868 |
(R_X, G_Y, B_Z)[j][0], |
| 869 |
1, |
| 870 |
(R_X, G_Y, B_Z)[j][0], |
| 871 |
XYZwp[j], |
| 872 |
) |
| 873 |
for j, v in enumerate((X, Y, Z)) |
| 874 |
) |
| 875 |
R_X[i], G_Y[i], B_Z[i] = X, Y, Z |
| 876 |
elif Y: |
| 877 |
Y2 = Y ** gammas_resized[1][i] |
| 878 |
R_X[i], G_Y[i], B_Z[i] = (v / Y * Y2 for v in (X, Y, Z)) |
| 879 |
|
| 880 |
for values in RGB: |
| 881 |
values[:] = colormath.interp_fill(values, values, numentries, True) |
| 882 |
|
| 883 |
# for i in range(numentries): |
| 884 |
# print(i, R_R[i], G_G[i], B_B[i], gammas_resized[0][i], |
| 885 |
# gammas_resized[1][i], gammas_resized[2][i], R_X[i], |
| 886 |
# G_Y[i], B_Z[i]) |
| 887 |
|
| 888 |
numentries = final |
| 889 |
else: |
| 890 |
# Hmm. Can this happen? Use old (pre 3.8.9.2) interpolation |
| 891 |
numentries = 33 |
| 892 |
|
| 893 |
rinterp = colormath.Interp(R_R, R_X, use_numpy=True) |
| 894 |
ginterp = colormath.Interp(G_G, G_Y, use_numpy=True) |
| 895 |
binterp = colormath.Interp(B_B, B_Z, use_numpy=True) |
| 896 |
|
| 897 |
curves = [[], [], []] |
| 898 |
|
| 899 |
maxval = numentries - 1.0 |
| 900 |
powinterp = { |
| 901 |
"r": colormath.Interp([], []), |
| 902 |
"g": colormath.Interp([], []), |
| 903 |
"b": colormath.Interp([], []), |
| 904 |
} |
| 905 |
# RGBwp = bwd_mtx * XYZwp |
| 906 |
for n in range(numentries): |
| 907 |
n /= maxval |
| 908 |
if numentries < final: |
| 909 |
# Apply slight power to input value so we sample near |
| 910 |
# black more accurately |
| 911 |
n **= 1.2 |
| 912 |
Y = ginterp(n) |
| 913 |
X = rinterp(n) |
| 914 |
Z = binterp(n) |
| 915 |
if Y >= 1: |
| 916 |
# Fix Y >= 1 to whitepoint. Mainly for HDR with PQ clipping, |
| 917 |
# where input gray < 1 can result in >= white Y |
| 918 |
X, Y, Z = XYZwp |
| 919 |
elif single_curve: |
| 920 |
X, Y, Z = [v * Y for v in XYZwp] |
| 921 |
RGB = bwd_mtx * (X, Y, Z) |
| 922 |
for i, channel in enumerate("rgb"): |
| 923 |
v = RGB[i] |
| 924 |
v = min(max(v, 0), 1) |
| 925 |
if slope_limit: |
| 926 |
v = max(v, n / 64.25) |
| 927 |
if numentries < final: |
| 928 |
powinterp[channel].xp.append(n) |
| 929 |
powinterp[channel].fp.append(v) |
| 930 |
else: |
| 931 |
curves[i].append(v) |
| 932 |
if numentries < final: |
| 933 |
for n in range(numentries): |
| 934 |
for i, channel in enumerate("rgb"): |
| 935 |
v = powinterp[channel](n / maxval) |
| 936 |
curves[i].append(v) |
| 937 |
|
| 938 |
for curve in curves: |
| 939 |
# Ensure monotonically increasing |
| 940 |
curve[:] = colormath.make_monotonically_increasing(curve) |
| 941 |
if numentries < final: |
| 942 |
# Interpolate to final resolution |
| 943 |
# Spline interpolation to larger size |
| 944 |
x = (i / (final - 1.0) * (len(curve) - 1) for i in range(final)) |
| 945 |
spline = CRInterpolation(curve) |
| 946 |
curve[:] = (min(max(spline(v), 0), 1) for v in x) |
| 947 |
# Ensure still monotonically increasing |
| 948 |
curve[:] = colormath.make_monotonically_increasing(curve) |
| 949 |
|
| 950 |
if optimize: |
| 951 |
curves = _create_optimized_shaper_curves( |
| 952 |
bwd_mtx, bpc, single_curve, curves, profile, options_dispcal, XYZbp, logfn |
| 953 |
) |
| 954 |
|
| 955 |
if bwd_mtx * [1, 1, 1] != [1, 1, 1]: |
| 956 |
# Matrix display profile: the matrix maps device (1, 1, 1) to the PCS |
| 957 |
# media white, so the shaper (TRC) curves have to reach 1.0 at device |
| 958 |
# maximum for device white to actually map to media white. The curves |
| 959 |
# are built (and optimized) from a fit normalized to the matrix white, |
| 960 |
# which can leave their endpoint slightly below 1.0 when the matrix |
| 961 |
# white and the gray ramp white are not perfectly consistent. A sub-1.0 |
| 962 |
# endpoint makes device max map to a fraction of media white, which in |
| 963 |
# turn makes a CMM clip near-white source values to device white when it |
| 964 |
# inverts the profile at limited (e.g. 8 bit) precision. Normalize each |
| 965 |
# curve so its endpoint is exactly 1.0 to avoid this near-white crush |
| 966 |
# (issue #710). This matches what Argyll's colprof does for matrix |
| 967 |
# profiles. Scaling is uniform, so the curve shape (gamma) and gray |
| 968 |
# neutrality are preserved. |
| 969 |
for curve in curves: |
| 970 |
endpoint = curve[-1] |
| 971 |
if endpoint and endpoint != 1.0: |
| 972 |
curve[:] = [min(v / endpoint, 1.0) for v in curve] |
| 973 |
|
| 974 |
return curves |
| 975 |
|
| 976 |
|
| 977 |
def _create_optimized_shaper_curves( |
| 978 |
bwd_mtx, bpc, single_curve, curves, profile, options_dispcal, XYZbp=None, logfn=None |
| 979 |
): |
| 980 |
# Get black and white luminance |
| 981 |
if isinstance(profile.tags.get("lumi"), XYZType): |
| 982 |
white_cdm2 = profile.tags.lumi.Y |
| 983 |
else: |
| 984 |
white_cdm2 = 100.0 |
| 985 |
black_Y = (XYZbp and XYZbp[1]) or 0 |
| 986 |
black_cdm2 = black_Y * white_cdm2 |
| 987 |
|
| 988 |
# Calibration gamma defaults |
| 989 |
gamma_type = None |
| 990 |
calgamma = 0 |
| 991 |
outoffset = None |
| 992 |
# Get actual calibration gamma (if any) |
| 993 |
calgarg = get_arg("g", options_dispcal) |
| 994 |
if not calgarg: |
| 995 |
calgarg = get_arg("G", options_dispcal) |
| 996 |
if ( |
| 997 |
calgarg |
| 998 |
and isinstance(profile.tags.get("vcgt"), VideoCardGammaType) |
| 999 |
and not profile.tags.vcgt.is_linear() |
| 1000 |
): |
| 1001 |
calgamma = {"l": -3.0, "s": -2.4, "709": -709, "240": -240}.get( |
| 1002 |
calgarg[1][1:], calgamma |
| 1003 |
) |
| 1004 |
if not calgamma: |
| 1005 |
with contextlib.suppress(ValueError): |
| 1006 |
# Not a gamma value, if it raises a ValueError, ignore |
| 1007 |
calgamma = float(calgarg[1][1:]) |
| 1008 |
if calgamma: |
| 1009 |
gamma_type = calgarg[1][0] |
| 1010 |
outoffset = DEFAULTS["calibration.black_output_offset"] |
| 1011 |
calfarg = get_arg("f", options_dispcal) |
| 1012 |
if calfarg: |
| 1013 |
with contextlib.suppress(ValueError): |
| 1014 |
outoffset = float(calfarg[1][1:]) |
| 1015 |
caltrc = CurveType(profile=profile) |
| 1016 |
if calgamma > 0: |
| 1017 |
caltrc.set_bt1886_trc(black_Y, outoffset, calgamma, gamma_type) |
| 1018 |
else: |
| 1019 |
caltrc.set_trc(calgamma) |
| 1020 |
caltf = caltrc.get_transfer_function(True, (0, 1), black_Y, outoffset) |
| 1021 |
if logfn: |
| 1022 |
logfn(f"Black relative luminance = {round(black_Y, 6):.6f}") |
| 1023 |
if outoffset is not None and logfn: |
| 1024 |
logfn(f"Black output offset = {round(outoffset, 2):.2f}") |
| 1025 |
if calgamma > 0 and logfn: |
| 1026 |
logfn( |
| 1027 |
"Calibration gamma = {:.2f} {}".format( |
| 1028 |
round(calgamma, 2), {"g": "relative", "G": "absolute"}.get(gamma_type) |
| 1029 |
) |
| 1030 |
) |
| 1031 |
if calgamma and logfn: |
| 1032 |
logfn( |
| 1033 |
"Calibration overall transfer function ≈ " |
| 1034 |
f"{caltf[0][0]} (Δ {1 - caltf[1]:.2%})" |
| 1035 |
) |
| 1036 |
if calgamma > 0 and black_Y: |
| 1037 |
# Calculate effective gamma |
| 1038 |
midpoint = colormath.interp( |
| 1039 |
(len(caltrc) - 1) / 2.0, list(range(len(caltrc))), caltrc |
| 1040 |
) |
| 1041 |
gamma = colormath.get_gamma([(0.5, midpoint / 65535.0)]) |
| 1042 |
if logfn: |
| 1043 |
logfn(f"Calibration effective gamma = {gamma:.2f}") |
| 1044 |
tfs = [] |
| 1045 |
for i, channel in enumerate("rgb"): |
| 1046 |
trc = CurveType(profile=profile) |
| 1047 |
trc[:] = [v / float(curves[i][-1]) * 65535 for v in curves[i]] |
| 1048 |
# Get transfer function and see if we have a good match |
| 1049 |
# to a standard. If we do, use the standard transfer |
| 1050 |
# function instead of our measurement based one. |
| 1051 |
# This avoids artifacts when processing is done in |
| 1052 |
# limited (e.g. 8 bit) precision by a color managed |
| 1053 |
# application and the source profile uses the same |
| 1054 |
# standard transfer function. |
| 1055 |
tf = trc.get_transfer_function(True, (0, 1), black_Y, outoffset) |
| 1056 |
label = ["Transfer function", channel.upper()] |
| 1057 |
label.append(f"≈ {tf[0][0]} (Δ {1 - tf[1]:.2%})") |
| 1058 |
if logfn: |
| 1059 |
logfn(" ".join(label)) |
| 1060 |
gamma = tf[0][1] |
| 1061 |
if gamma > 0 and black_Y: |
| 1062 |
# Calculate effective gamma |
| 1063 |
gamma = colormath.get_gamma([(0.5, 0.5**gamma)], vmin=-black_Y) |
| 1064 |
if logfn: |
| 1065 |
logfn(f"Effective gamma = {round(gamma, 2):.2f}") |
| 1066 |
# Only use standard transfer function if we got a good match |
| 1067 |
if tf[1] >= 0.98: |
| 1068 |
# Good match |
| 1069 |
if logfn: |
| 1070 |
logfn("Got good match (+-2%)") |
| 1071 |
if ( |
| 1072 |
single_curve |
| 1073 |
and calgamma |
| 1074 |
and round(tf[0][1], 1) == round(caltf[0][1], 1) |
| 1075 |
): |
| 1076 |
# Use calibration gamma |
| 1077 |
tf = caltf |
| 1078 |
if logfn: |
| 1079 |
logfn("Using calibration transfer function") |
| 1080 |
tfs.append((tf, trc)) |
| 1081 |
|
| 1082 |
if len(tfs) == 3: |
| 1083 |
# Only use standard transfer function if we got a good |
| 1084 |
# identical match for all three channels. |
| 1085 |
optcurves = [] |
| 1086 |
for i, channel in enumerate("rgb"): |
| 1087 |
tf, trc = tfs[i] |
| 1088 |
gamma = tf[0][1] |
| 1089 |
if gamma > 0 and black_Y: |
| 1090 |
# Calculate effective gamma |
| 1091 |
egamma = colormath.get_gamma([(0.5, 0.5**gamma)], vmin=-black_Y) |
| 1092 |
else: |
| 1093 |
egamma = gamma |
| 1094 |
if outoffset is None: |
| 1095 |
outoffset = tf[0][2] |
| 1096 |
if ( |
| 1097 |
gamma > 0 |
| 1098 |
and bpc |
| 1099 |
and (outoffset == 1.0 or not black_Y) |
| 1100 |
and bwd_mtx * [1, 1, 1] != [1, 1, 1] |
| 1101 |
): |
| 1102 |
# Single gamma value, BPC, all output offset or |
| 1103 |
# zero black luminance |
| 1104 |
if gamma_type == "g": |
| 1105 |
gamma = egamma |
| 1106 |
# Use multi-entry curve (not single-entry gamma) so the |
| 1107 |
# v / 65535 conversion below stays in [0, 1] range. |
| 1108 |
trc.set_trc(gamma) |
| 1109 |
# Complex or gamma with offset |
| 1110 |
elif gamma == -1023: |
| 1111 |
# DICOM is a special case |
| 1112 |
trc.set_dicom_trc(black_cdm2, white_cdm2) |
| 1113 |
elif gamma == -1886: |
| 1114 |
# BT.1886 is a special case |
| 1115 |
trc.set_bt1886_trc(black_Y) |
| 1116 |
elif gamma == -2084: |
| 1117 |
# SMPTE 2084 is a special case |
| 1118 |
trc.set_smpte2084_trc(black_cdm2, white_cdm2) |
| 1119 |
elif gamma > 0 and black_Y: |
| 1120 |
# BT.1886-like or power law with offset |
| 1121 |
if bpc and gamma_type == "g": |
| 1122 |
# Use effective gamma needed to |
| 1123 |
# achieve target effective gamma |
| 1124 |
# after accounting for BPC |
| 1125 |
eegamma = colormath.get_gamma([(0.5, 0.5**egamma)], vmin=-black_Y) |
| 1126 |
else: |
| 1127 |
eegamma = egamma |
| 1128 |
trc.set_bt1886_trc(black_Y, outoffset, eegamma, "g") |
| 1129 |
else: |
| 1130 |
# L*, sRGB, Rec. 709, SMPTE 240M, or |
| 1131 |
# power law without offset |
| 1132 |
if bpc and gamma_type == "g": |
| 1133 |
# Use effective gamma |
| 1134 |
gamma = egamma |
| 1135 |
trc.set_trc(gamma) |
| 1136 |
trc.apply_bpc() |
| 1137 |
tf = trc.get_transfer_function(True, (0, 1), black_Y, outoffset) |
| 1138 |
if logfn: |
| 1139 |
logfn(f"Using transfer function for {channel.upper()}: {tf[0][0]}") |
| 1140 |
gamma = tf[0][1] |
| 1141 |
if gamma > 0 and black_Y: |
| 1142 |
# Calculate effective gamma |
| 1143 |
gamma = colormath.get_gamma([(0.5, 0.5**gamma)], vmin=-black_Y) |
| 1144 |
if logfn: |
| 1145 |
logfn(f"Effective gamma = {round(gamma, 2):.2f}") |
| 1146 |
optcurves.append([v / 65535.0 * curves[i][-1] for v in trc]) |
| 1147 |
curves = optcurves |
| 1148 |
|
| 1149 |
return curves |
| 1150 |
|
| 1151 |
|
| 1152 |
def _applycal_bug_workaround(profile): |
| 1153 |
# Argyll applycal can't deal with single gamma TRC tags |
| 1154 |
# or TRC tags with less than 256 entries |
| 1155 |
for channel in "rgb": |
| 1156 |
trc_tag = profile.tags.get(channel + "TRC") |
| 1157 |
if isinstance(trc_tag, CurveType) and len(trc_tag) < 256: |
| 1158 |
num_entries = len(trc_tag) |
| 1159 |
if num_entries <= 1: |
| 1160 |
# Single gamma |
| 1161 |
gamma = trc_tag[0] if num_entries else 1.0 |
| 1162 |
trc_tag.set_trc(gamma, 256) |
| 1163 |
else: |
| 1164 |
# Interpolate to 256 entries |
| 1165 |
entry_max = num_entries - 1.0 |
| 1166 |
interp = colormath.Interp( |
| 1167 |
[i / entry_max for i in range(num_entries)], trc_tag[:] |
| 1168 |
) |
| 1169 |
trc_tag[:] = [interp(i / 255.0) for i in range(256)] |
| 1170 |
|
| 1171 |
|
| 1172 |
def get_current_profile_path( |
| 1173 |
include_display_profile: bool = True, |
| 1174 |
save_profile_if_no_path: bool = False, |
| 1175 |
) -> None | str: |
| 1176 |
"""Get the current profile path from the configuration. |
| 1177 |
|
| 1178 |
Args: |
| 1179 |
include_display_profile (bool): Whether to include the display profile. |
| 1180 |
save_profile_if_no_path (bool): Whether to save the profile if it has no path. |
| 1181 |
|
| 1182 |
Returns: |
| 1183 |
None | str: The profile path or None if not found. |
| 1184 |
""" |
| 1185 |
profile = None |
| 1186 |
profile_path = getcfg("calibration.file", False) |
| 1187 |
if profile_path: |
| 1188 |
filename, ext = os.path.splitext(profile_path) |
| 1189 |
if ext.lower() in (".icc", ".icm"): |
| 1190 |
try: |
| 1191 |
profile = ICCProfile(profile_path) |
| 1192 |
except Exception as exception: |
| 1193 |
print(f"ICCProfile({profile_path}):", exception) |
| 1194 |
elif include_display_profile: |
| 1195 |
profile = config.get_display_profile() |
| 1196 |
if profile and not profile.filename and save_profile_if_no_path: |
| 1197 |
if profile.ID == "\0" * 16: |
| 1198 |
profile.calculate_id() |
| 1199 |
profile_cache_path = os.path.join(defaultpaths.CACHE, "icc") |
| 1200 |
if check_create_dir(profile_cache_path) is True: |
| 1201 |
profile.filename = os.path.join( |
| 1202 |
profile_cache_path, |
| 1203 |
"id=" + hexlify(profile.ID).decode() + PROFILE_EXT, |
| 1204 |
) |
| 1205 |
if not os.path.isfile(profile.filename): |
| 1206 |
profile.write() |
| 1207 |
if profile: |
| 1208 |
return profile.filename |
| 1209 |
|
| 1210 |
return profile |
| 1211 |
|
| 1212 |
|
| 1213 |
def parse_argument_string(args): |
| 1214 |
"""Parse an argument string and return a list of arguments.""" |
| 1215 |
return [ |
| 1216 |
re.sub(r'^["\']|["\']$', "", arg) |
| 1217 |
for arg in re.findall( |
| 1218 |
r'(?:^|\s+)(-[^\s"\']+|"[^"]+?"|\'[^\']+?\'|[^\s"\']+)', args |
| 1219 |
) |
| 1220 |
] |
| 1221 |
|
| 1222 |
|
| 1223 |
def get_cfg_option_from_args(option_name, argmatch, args, whole=False): |
| 1224 |
"""Parse args and return option (if found), otherwise return default.""" |
| 1225 |
option = DEFAULTS[option_name] |
| 1226 |
iarg = get_arg(argmatch, args, whole) |
| 1227 |
if iarg: |
| 1228 |
if len(iarg[1]) == len(argmatch): |
| 1229 |
# Option value is the next argument |
| 1230 |
if len(args) > iarg[0] + 1: |
| 1231 |
option = args[iarg[0] + 1] |
| 1232 |
else: |
| 1233 |
# Option value follows argument directly |
| 1234 |
option = iarg[1][len(argmatch) :] |
| 1235 |
return option |
| 1236 |
|
| 1237 |
|
| 1238 |
def get_options_from_args(dispcal_args=None, colprof_args=None) -> tuple[str, str]: |
| 1239 |
"""Extract options used for dispcal and colprof from argument strings.""" |
| 1240 |
re_options_dispcal = [ |
| 1241 |
r"[moupHVFE]", |
| 1242 |
r"d(?:\d+(?:,\d+)?|madvr|web)", |
| 1243 |
r"[cv]\d+", |
| 1244 |
r"q(?:{})".format("|".join(config.VALID_VALUES["calibration.quality"])), |
| 1245 |
r"y(?:{})".format( |
| 1246 |
"|".join([_f for _f in config.VALID_VALUES["measurement_mode"] if _f]) |
| 1247 |
), |
| 1248 |
r"[tT](?:\d+(?:\.\d+)?)?", |
| 1249 |
r"w\d+(?:\.\d+)?,\d+(?:\.\d+)?", |
| 1250 |
r"[bfakAB]\d+(?:\.\d+)?", |
| 1251 |
r"(?:g(?:240|709|l|s)|[gG]\d+(?:\.\d+)?)", |
| 1252 |
r"[pP]\d+(?:\.\d+)?,\d+(?:\.\d+)?,\d+(?:\.\d+)?", |
| 1253 |
r'X(?:\s*\d+|\s+["\'][^"\']+?["\'])', # Argyll >= 1.3.0 colorimeter correction |
| 1254 |
# matrix / |
| 1255 |
# Argyll >= 1.3.4 calibration spectral |
| 1256 |
# sample |
| 1257 |
r"I[bw]{,2}", # Argyll >= 1.3.0 drift compensation |
| 1258 |
r"YA", # Argyll >= 1.5.0 disable adaptive mode |
| 1259 |
r"Q\w+", |
| 1260 |
] |
| 1261 |
re_options_colprof = [ |
| 1262 |
r"q[lmh]", |
| 1263 |
r"b[lmh]", # B2A quality |
| 1264 |
r"a(?:{})".format("|".join(config.VALID_VALUES["profile.type"])), |
| 1265 |
r'[sSMA]\s+["\'][^"\']+?["\']', |
| 1266 |
r"[cd](?:{})(?=\W|$)".format("|".join(VIEWCONDS)), |
| 1267 |
r"[tT](?:{})(?=\W|$)".format("|".join(INTENTS)), |
| 1268 |
] |
| 1269 |
options_dispcal = [] |
| 1270 |
options_colprof = [] |
| 1271 |
|
| 1272 |
if dispcal_args: |
| 1273 |
if isinstance(dispcal_args, bytes): |
| 1274 |
dispcal_args = dispcal_args.decode("UTF-8") |
| 1275 |
options_dispcal = re.findall( |
| 1276 |
r" -({})".format("|".join(re_options_dispcal)), f" {dispcal_args}" |
| 1277 |
) |
| 1278 |
if colprof_args: |
| 1279 |
if isinstance(colprof_args, bytes): |
| 1280 |
colprof_args = colprof_args.decode("UTF-8") |
| 1281 |
options_colprof = re.findall( |
| 1282 |
r" -(" + "|".join(re_options_colprof) + ")", " " + colprof_args |
| 1283 |
) |
| 1284 |
return options_dispcal, options_colprof |
| 1285 |
|
| 1286 |
|
| 1287 |
def get_options_from_cprt(cprt): |
| 1288 |
"""Extract options used for dispcal and colprof from profile copyright.""" |
| 1289 |
if not isinstance(cprt, str): |
| 1290 |
if isinstance(cprt, (TextDescriptionType, MultiLocalizedUnicodeType)): |
| 1291 |
cprt = str(cprt) |
| 1292 |
else: |
| 1293 |
cprt = str(cprt, FS_ENC, "replace") |
| 1294 |
dispcal_args = cprt.split(" dispcal ") |
| 1295 |
colprof_args = None |
| 1296 |
if len(dispcal_args) > 1: |
| 1297 |
dispcal_args[1] = dispcal_args[1].split(" colprof ") |
| 1298 |
if len(dispcal_args[1]) > 1: |
| 1299 |
colprof_args = dispcal_args[1][1] |
| 1300 |
dispcal_args = dispcal_args[1][0] |
| 1301 |
else: |
| 1302 |
dispcal_args = None |
| 1303 |
colprof_args = cprt.split(" colprof ") |
| 1304 |
colprof_args = colprof_args[1] if len(colprof_args) > 1 else None |
| 1305 |
return dispcal_args, colprof_args |
| 1306 |
|
| 1307 |
|
| 1308 |
def get_options_from_cal(cal) -> tuple[list, list]: |
| 1309 |
"""Try and get options from calibration file. |
| 1310 |
|
| 1311 |
First, try the 'ARGYLL_DISPCAL_ARGS' and 'ARGYLL_COLPROF_ARGS' tags. If |
| 1312 |
either does not exist, fall back to the copyright tag.""" |
| 1313 |
if not isinstance(cal, CGATS): |
| 1314 |
cal = CGATS(cal) |
| 1315 |
if 0 in cal: |
| 1316 |
cal = cal[0] |
| 1317 |
if not cal or "ARGYLL_DISPCAL_ARGS" not in cal or not cal.ARGYLL_DISPCAL_ARGS: |
| 1318 |
return [], [] |
| 1319 |
dispcal_args = cal.ARGYLL_DISPCAL_ARGS[0] |
| 1320 |
return get_options_from_args(dispcal_args) |
| 1321 |
|
| 1322 |
|
| 1323 |
def get_options_from_profile(profile): |
| 1324 |
"""Try and get options from profile. |
| 1325 |
|
| 1326 |
First, try the 'targ' tag and look for the special DisplayCAL sections of |
| 1327 |
'ARGYLL_DISPCAL_ARGS' and 'ARGYLL_COLPROF_ARGS'. If either does not exist, |
| 1328 |
fall back to the copyright tag (DisplayCAL < 0.4.0.2) |
| 1329 |
""" |
| 1330 |
if not isinstance(profile, ICCProfile): |
| 1331 |
profile = ICCProfile(profile) |
| 1332 |
dispcal_args = None |
| 1333 |
colprof_args = None |
| 1334 |
if "targ" in profile.tags: |
| 1335 |
ti3 = CGATS(profile.tags.targ) |
| 1336 |
if 1 in ti3 and "ARGYLL_DISPCAL_ARGS" in ti3[1] and ti3[1].ARGYLL_DISPCAL_ARGS: |
| 1337 |
dispcal_args = ti3[1].ARGYLL_DISPCAL_ARGS[0] |
| 1338 |
if 0 in ti3 and "ARGYLL_COLPROF_ARGS" in ti3[0] and ti3[0].ARGYLL_COLPROF_ARGS: |
| 1339 |
colprof_args = ti3[0].ARGYLL_COLPROF_ARGS[0] |
| 1340 |
if not dispcal_args and "cprt" in profile.tags: |
| 1341 |
dispcal_args = get_options_from_cprt(profile.getCopyright())[0] |
| 1342 |
if not colprof_args and "cprt" in profile.tags: |
| 1343 |
colprof_args = get_options_from_cprt(profile.getCopyright())[1] |
| 1344 |
return get_options_from_args(dispcal_args, colprof_args) |
| 1345 |
|
| 1346 |
|
| 1347 |
def get_options_from_ti3(ti3): |
| 1348 |
"""Get dispcal and colprof options from TI3 file if present. |
| 1349 |
|
| 1350 |
This looks for the special DisplayCAL sections of 'ARGYLL_DISPCAL_ARGS' and |
| 1351 |
'ARGYLL_COLPROF_ARGS'. |
| 1352 |
""" |
| 1353 |
if not isinstance(ti3, CGATS): |
| 1354 |
ti3 = CGATS(ti3) |
| 1355 |
dispcal_args = None |
| 1356 |
colprof_args = None |
| 1357 |
if 1 in ti3 and "ARGYLL_DISPCAL_ARGS" in ti3[1] and ti3[1].ARGYLL_DISPCAL_ARGS: |
| 1358 |
dispcal_args = ti3[1].ARGYLL_DISPCAL_ARGS[0] |
| 1359 |
if 0 in ti3 and "ARGYLL_COLPROF_ARGS" in ti3[0] and ti3[0].ARGYLL_COLPROF_ARGS: |
| 1360 |
colprof_args = ti3[0].ARGYLL_COLPROF_ARGS[0] |
| 1361 |
return get_options_from_args(dispcal_args, colprof_args) |
| 1362 |
|
| 1363 |
|
| 1364 |
def get_pattern_geometry(): |
| 1365 |
"""Return pattern geometry for pattern generator.""" |
| 1366 |
x, y, size = [float(v) for v in getcfg("dimensions.measureframe").split(",")] |
| 1367 |
if os.getenv("XDG_SESSION_TYPE") == "wayland": |
| 1368 |
# No way to get coordinates under Wayland, default to center |
| 1369 |
x = y = 0.5 |
| 1370 |
size = size * DEFAULTS["size.measureframe"] |
| 1371 |
match = re.search(r"@ -?\d+, -?\d+, (\d+)x(\d+)", getcfg("displays", raw=True)) |
| 1372 |
display_size = [int(item) for item in match.groups()] if match else [1920, 1080] |
| 1373 |
w, h = [min(size / v, 1.0) for v in display_size] |
| 1374 |
if config.get_display_name(None, True) == "Prisma": |
| 1375 |
w = h |
| 1376 |
x = (display_size[0] - w * display_size[0]) * x / display_size[0] |
| 1377 |
y = (display_size[1] - h * display_size[1]) * y / display_size[1] |
| 1378 |
x, y, w, h = [max(v, 0) for v in (x, y, w, h)] |
| 1379 |
size = w * h |
| 1380 |
return x, y, w, h, size |
| 1381 |
|
| 1382 |
|
| 1383 |
def get_python_and_pythonpath(): |
| 1384 |
"""Return (system) python and pythonpath.""" |
| 1385 |
# Determine the path of python, and python module search paths |
| 1386 |
# If we are running 'frozen', expect python.exe in the same directory |
| 1387 |
# as the packed executable. |
| 1388 |
# py2exe: The python executable can be included via setup script by |
| 1389 |
# adding it to 'data_files' |
| 1390 |
pythonpath = list(sys.path) |
| 1391 |
dirname = os.path.dirname(sys.executable) |
| 1392 |
if sys.platform == "win32": |
| 1393 |
if getattr(sys, "frozen", False): |
| 1394 |
pythonpath = [dirname] |
| 1395 |
# If we are running 'frozen', add library.zip and lib\library.zip |
| 1396 |
# to sys.path |
| 1397 |
# py2exe: Needs appropriate 'zipfile' option in setup script and |
| 1398 |
# 'bundle_files' 3 |
| 1399 |
pythonpath.append(os.path.join(dirname, "library.zip")) |
| 1400 |
pythonpath.append(os.path.join(dirname, "library.zip", APPNAME)) |
| 1401 |
if os.path.isdir(os.path.join(dirname, "lib")): |
| 1402 |
dirname = os.path.join(dirname, "lib") |
| 1403 |
pythonpath.append(os.path.join(dirname, "library.zip")) |
| 1404 |
pythonpath.append(os.path.join(dirname, "library.zip", APPNAME)) |
| 1405 |
python = os.path.join(dirname, "python.exe") |
| 1406 |
# Linux / Mac OS X |
| 1407 |
elif ISAPP: |
| 1408 |
python = os.path.join(dirname, "python") |
| 1409 |
else: |
| 1410 |
paths = os.defpath.split(os.pathsep) |
| 1411 |
python = ( |
| 1412 |
which("python3.7", paths) |
| 1413 |
or which("python3.6", paths) |
| 1414 |
or "/usr/bin/env python" |
| 1415 |
) |
| 1416 |
return (python, pythonpath) |
| 1417 |
|
| 1418 |
|
| 1419 |
def get_arg(argmatch, args, whole=False) -> None | tuple[int, str]: |
| 1420 |
"""Return first found entry beginning with the argmatch string or None. |
| 1421 |
|
| 1422 |
Returns: |
| 1423 |
None: if no match found. |
| 1424 |
tuple[int, str]: index and value of the match. |
| 1425 |
""" |
| 1426 |
for i, arg in enumerate(args): |
| 1427 |
if (whole and arg == argmatch) or (not whole and arg.startswith(argmatch)): |
| 1428 |
return i, arg |
| 1429 |
return None |
| 1430 |
|
| 1431 |
|
| 1432 |
def get_default_headers(): |
| 1433 |
"""Get default headers for HTTP request.""" |
| 1434 |
if sys.platform == "darwin": |
| 1435 |
# Python's platform.platform output is useless under Mac OS X |
| 1436 |
# (e.g. 'Darwin-15.0.0-x86_64-i386-64bit' for Mac OS X 10.11 El Capitan) |
| 1437 |
oscpu = f"Mac OS X {platform.mac_ver()[0]}; {platform.mac_ver()[-1]}" |
| 1438 |
elif sys.platform == "win32": |
| 1439 |
machine = platform.machine() |
| 1440 |
oscpu = "{}; {}".format( |
| 1441 |
safe_str(" ".join([v for v in win_ver() if v]), "ASCII", "asciize"), |
| 1442 |
{"AMD64": "x86_64"}.get(machine, machine), |
| 1443 |
) |
| 1444 |
else: |
| 1445 |
# Linux |
| 1446 |
oscpu = ( |
| 1447 |
f"{distro.id()} {distro.version()} {distro.codename()}; " |
| 1448 |
f"{platform.machine()}" |
| 1449 |
) |
| 1450 |
return { |
| 1451 |
"User-Agent": f"{APPNAME}/{VERSION_STRING} ({oscpu})", |
| 1452 |
"Accept-Language": f"{lang.getcode()},*;q=0.5", |
| 1453 |
} |
| 1454 |
|
| 1455 |
|
| 1456 |
def http_request( |
| 1457 |
parent=None, |
| 1458 |
domain=None, |
| 1459 |
request_type="GET", |
| 1460 |
path="", |
| 1461 |
params=None, |
| 1462 |
files=None, |
| 1463 |
headers=None, |
| 1464 |
charset="UTF-8", |
| 1465 |
failure_msg="", |
| 1466 |
silent=False, |
| 1467 |
): |
| 1468 |
"""HTTP request wrapper.""" |
| 1469 |
if params is None: |
| 1470 |
params = {} |
| 1471 |
if files: |
| 1472 |
content_type, params = encode_multipart_formdata(iter(params.items()), files) |
| 1473 |
else: |
| 1474 |
for key in params: |
| 1475 |
params[key] = safe_str(params[key], charset) |
| 1476 |
params = urllib.parse.urlencode(params) |
| 1477 |
if headers is None: |
| 1478 |
headers = get_default_headers() |
| 1479 |
if request_type == "GET": |
| 1480 |
path += "?" + params |
| 1481 |
params = None |
| 1482 |
elif files: |
| 1483 |
headers.update( |
| 1484 |
{"Content-Type": content_type, "Content-Length": str(len(params))} |
| 1485 |
) |
| 1486 |
else: |
| 1487 |
headers.update( |
| 1488 |
{ |
| 1489 |
"Content-Type": "application/x-www-form-urlencoded", |
| 1490 |
"Accept": "text/plain", |
| 1491 |
} |
| 1492 |
) |
| 1493 |
conn = http.client.HTTPConnection(domain) |
| 1494 |
try: |
| 1495 |
conn.request(request_type, path, params, headers) |
| 1496 |
resp = conn.getresponse() |
| 1497 |
except (OSError, http.client.HTTPException) as exception: |
| 1498 |
msg = " ".join( |
| 1499 |
[ |
| 1500 |
failure_msg, |
| 1501 |
lang.getstr( |
| 1502 |
"connection.fail", " ".join([str(arg) for arg in exception.args]) |
| 1503 |
), |
| 1504 |
] |
| 1505 |
).strip() |
| 1506 |
print(msg) |
| 1507 |
if not silent: |
| 1508 |
wx.CallAfter( |
| 1509 |
InfoDialog, |
| 1510 |
parent, |
| 1511 |
msg=msg, |
| 1512 |
ok=lang.getstr("ok"), |
| 1513 |
bitmap=get_icon(32, "dialog-error"), |
| 1514 |
log=False, |
| 1515 |
) |
| 1516 |
return False |
| 1517 |
if resp.status >= 400: |
| 1518 |
uri = "http://" + domain + path |
| 1519 |
msg = ( |
| 1520 |
" ".join( |
| 1521 |
[ |
| 1522 |
failure_msg, |
| 1523 |
lang.getstr( |
| 1524 |
"connection.fail.http", |
| 1525 |
" ".join([str(resp.status), resp.reason]), |
| 1526 |
), |
| 1527 |
] |
| 1528 |
).strip() |
| 1529 |
+ "\n" |
| 1530 |
+ uri |
| 1531 |
) |
| 1532 |
print(msg) |
| 1533 |
html = universal_newlines(resp.read().strip()) |
| 1534 |
html = re.sub( |
| 1535 |
re.compile(r"<script.*?</script>", re.I | re.S), |
| 1536 |
"<!-- SCRIPT removed -->", |
| 1537 |
html, |
| 1538 |
) |
| 1539 |
html = re.sub( |
| 1540 |
re.compile(r"<style.*?</style>", re.I | re.S), |
| 1541 |
"<!-- STYLE removed -->", |
| 1542 |
html, |
| 1543 |
) |
| 1544 |
print(html) |
| 1545 |
if not silent: |
| 1546 |
wx.CallAfter( |
| 1547 |
HtmlInfoDialog, |
| 1548 |
parent, |
| 1549 |
msg=msg, |
| 1550 |
html=html, |
| 1551 |
ok=lang.getstr("ok"), |
| 1552 |
bitmap=get_icon(32, "dialog-error"), |
| 1553 |
log=False, |
| 1554 |
) |
| 1555 |
return False |
| 1556 |
return resp |
| 1557 |
|
| 1558 |
|
| 1559 |
def insert_ti_patches_omitting_RGB_duplicates(cgats1, cgats2_path, logfn=print): |
| 1560 |
"""Insert unique patches from the first TI file after the first patch of the second TI. |
| 1561 |
|
| 1562 |
Returns: |
| 1563 |
CGATS: Second TI as CGATS instance. |
| 1564 |
""" # noqa: E501 |
| 1565 |
cgats2 = CGATS(cgats2_path) |
| 1566 |
cgats1_data = cgats1.queryv1("DATA") |
| 1567 |
data = cgats2.queryv1("DATA") |
| 1568 |
data_format = cgats2.queryv1("DATA_FORMAT") |
| 1569 |
# Get only RGB data |
| 1570 |
data.parent.DATA_FORMAT = CGATS() |
| 1571 |
data.parent.DATA_FORMAT.key = "DATA_FORMAT" |
| 1572 |
data.parent.DATA_FORMAT.parent = data |
| 1573 |
data.parent.DATA_FORMAT.root = data.root |
| 1574 |
data.parent.DATA_FORMAT.type = b"DATA_FORMAT" |
| 1575 |
for i, label in enumerate(("RGB_R", "RGB_G", "RGB_B")): |
| 1576 |
data.parent.DATA_FORMAT[i] = label |
| 1577 |
cgats1_data.parent.DATA_FORMAT = data.parent.DATA_FORMAT |
| 1578 |
rgbdata = str(data) |
| 1579 |
# Restore DATA_FORMAT |
| 1580 |
data.parent.DATA_FORMAT = data_format |
| 1581 |
# Collect all preconditioning point datasets not in data |
| 1582 |
cgats1_data.vmaxlen = data.vmaxlen |
| 1583 |
cgats1_datasets = [] |
| 1584 |
for i in cgats1_data: |
| 1585 |
dataset = cgats1_data[i] |
| 1586 |
if str(dataset) not in rgbdata: |
| 1587 |
# Not a duplicate |
| 1588 |
cgats1_datasets.append(dataset) |
| 1589 |
if cgats1_datasets: |
| 1590 |
# Insert preconditioned point datasets after first patch |
| 1591 |
if logfn: |
| 1592 |
logfn( |
| 1593 |
f"{APPNAME}: Adding {len(cgats1_datasets):d} " |
| 1594 |
f"fixed points to {cgats2_path}" |
| 1595 |
) |
| 1596 |
data.moveby1(1, len(cgats1_datasets)) |
| 1597 |
for i, dataset in enumerate(cgats1_datasets): |
| 1598 |
dataset.key = i + 1 |
| 1599 |
dataset.parent = data |
| 1600 |
dataset.root = data.root |
| 1601 |
data[dataset.key] = dataset |
| 1602 |
return cgats2 |
| 1603 |
|
| 1604 |
|
| 1605 |
class EvalFalse: |
| 1606 |
"""Evaluate to False in boolean comparisons.""" |
| 1607 |
|
| 1608 |
def __init__(self, wrapped_object): |
| 1609 |
self._wrapped_object = wrapped_object |
| 1610 |
|
| 1611 |
def __getattribute__(self, name: str) -> Any: |
| 1612 |
"""Get attribute from the wrapped object. |
| 1613 |
|
| 1614 |
Args: |
| 1615 |
name (str): The name of the attribute to get. |
| 1616 |
|
| 1617 |
Returns: |
| 1618 |
Any: The attribute of the wrapped object. |
| 1619 |
""" |
| 1620 |
return getattr(object.__getattribute__(self, "_wrapped_object"), name) |
| 1621 |
|
| 1622 |
def __bool__(self) -> bool: |
| 1623 |
"""Return False for boolean comparisons.""" |
| 1624 |
return False |
| 1625 |
|
| 1626 |
|
| 1627 |
class DummyDialog: |
| 1628 |
"""Dummy dialog class for testing.""" |
| 1629 |
|
| 1630 |
def __init__(self, *args, **kwargs): |
| 1631 |
self.is_shown_on_screen = True |
| 1632 |
|
| 1633 |
def Close(self, force=False): |
| 1634 |
"""Simulate closing the dialog. |
| 1635 |
|
| 1636 |
Args: |
| 1637 |
force (bool): Whether to force close the dialog. Defaults to False. |
| 1638 |
""" |
| 1639 |
|
| 1640 |
def Destroy(self): |
| 1641 |
"""Simulate destroying the dialog.""" |
| 1642 |
|
| 1643 |
def EndModal(self, id=-1): # noqa: A002 |
| 1644 |
"""Simulate ending the modal dialog. |
| 1645 |
|
| 1646 |
Args: |
| 1647 |
id (int): The ID of the dialog. Defaults to -1. |
| 1648 |
""" |
| 1649 |
return id |
| 1650 |
|
| 1651 |
def Hide(self): |
| 1652 |
"""Simulate hiding the dialog.""" |
| 1653 |
|
| 1654 |
def IsShownOnScreen(self): |
| 1655 |
"""Check if the dialog is shown on screen.""" |
| 1656 |
return self.is_shown_on_screen |
| 1657 |
|
| 1658 |
def Show(self, show=True): |
| 1659 |
"""Simulate showing the dialog. |
| 1660 |
|
| 1661 |
Args: |
| 1662 |
show (bool): Whether to show the dialog. Defaults to True. |
| 1663 |
""" |
| 1664 |
self.is_shown_on_screen = show |
| 1665 |
|
| 1666 |
def ShowModal(self): |
| 1667 |
"""Simulate showing the dialog modally.""" |
| 1668 |
|
| 1669 |
|
| 1670 |
class FilteredStream: |
| 1671 |
"""Wrap a stream and filter all lines written to it.""" |
| 1672 |
|
| 1673 |
# Discard the whole line if it is empty after replacing patterns |
| 1674 |
discard = "" |
| 1675 |
|
| 1676 |
# If one of the triggers is contained in a line, skip the whole line |
| 1677 |
triggers: ClassVar[list] = [ |
| 1678 |
"Place instrument on test window", |
| 1679 |
"key to continue", |
| 1680 |
"key to retry", |
| 1681 |
"key to take a reading", |
| 1682 |
"] to read", |
| 1683 |
"' to set", |
| 1684 |
"' to report", |
| 1685 |
"' to toggle", |
| 1686 |
" or Q to ", |
| 1687 |
"place on the white calibration reference", |
| 1688 |
"or place on the calibration reference", |
| 1689 |
"read failed due to the sensor being in the wrong position", |
| 1690 |
"Ambient filter should be removed", |
| 1691 |
"The instrument can be removed from the screen", |
| 1692 |
*INST_CAL_MSGS, |
| 1693 |
] |
| 1694 |
|
| 1695 |
substitutions: ClassVar[dict] = { |
| 1696 |
r"\^\[": "", # ESC key on Linux/OSX |
| 1697 |
"patch ": "Patch ", |
| 1698 |
re.compile(r"Point \d+", re.I): "", |
| 1699 |
} |
| 1700 |
|
| 1701 |
# Strip these patterns from input before writing. Note that this only works |
| 1702 |
# on full lines (ending with linesep_in) |
| 1703 |
prestrip = "" |
| 1704 |
|
| 1705 |
def __init__( |
| 1706 |
self, |
| 1707 |
stream, |
| 1708 |
data_encoding=None, |
| 1709 |
file_encoding=None, |
| 1710 |
errors="replace", |
| 1711 |
discard=None, |
| 1712 |
linesep_in="\r\n", |
| 1713 |
linesep_out="\n", |
| 1714 |
substitutions=None, |
| 1715 |
triggers=None, |
| 1716 |
prestrip=None, |
| 1717 |
): |
| 1718 |
self.stream = stream |
| 1719 |
self.data_encoding = data_encoding |
| 1720 |
self.file_encoding = file_encoding |
| 1721 |
self.errors = errors |
| 1722 |
if discard is not None: |
| 1723 |
self.discard = discard |
| 1724 |
self.linesep_in = linesep_in |
| 1725 |
self.linesep_out = linesep_out |
| 1726 |
if substitutions is not None: |
| 1727 |
self.substitutions = substitutions |
| 1728 |
if triggers is not None: |
| 1729 |
self.triggers = triggers |
| 1730 |
if prestrip is not None: |
| 1731 |
self.prestrip = prestrip |
| 1732 |
self._buffer = "" |
| 1733 |
|
| 1734 |
def __getattr__(self, name: str) -> Any: |
| 1735 |
"""Get attribute from the wrapped stream. |
| 1736 |
|
| 1737 |
Args: |
| 1738 |
name (str): The name of the attribute to get. |
| 1739 |
|
| 1740 |
Returns: |
| 1741 |
Any: The attribute of the wrapped stream. |
| 1742 |
""" |
| 1743 |
return getattr(self.stream, name) |
| 1744 |
|
| 1745 |
def write(self, data): |
| 1746 |
"""Write data to stream, stripping all unwanted output. |
| 1747 |
|
| 1748 |
Incoming lines are expected to be delimited by linesep_in. |
| 1749 |
""" |
| 1750 |
if not data: |
| 1751 |
return |
| 1752 |
|
| 1753 |
if isinstance(data, bytes): |
| 1754 |
data = data.decode() |
| 1755 |
|
| 1756 |
if self.prestrip and (re.search(self.prestrip, data) or self._buffer): |
| 1757 |
if not data.endswith(self.linesep_in): |
| 1758 |
# Buffer all data until we see a line ending |
| 1759 |
self._buffer += data |
| 1760 |
return |
| 1761 |
if self._buffer: |
| 1762 |
# Assemble the full line from the buffer |
| 1763 |
data = self._buffer + data |
| 1764 |
self._buffer = "" |
| 1765 |
data = re.sub(self.prestrip, "", data) |
| 1766 |
|
| 1767 |
lines = [] |
| 1768 |
for line in data.split(self.linesep_in): |
| 1769 |
if line and not re.sub(self.discard, "", line): |
| 1770 |
line = "" |
| 1771 |
write = True |
| 1772 |
for trigger in self.triggers: |
| 1773 |
if trigger.lower() in line.lower(): |
| 1774 |
write = False |
| 1775 |
break |
| 1776 |
if write: |
| 1777 |
if self.data_encoding and not isinstance(line, str): |
| 1778 |
line = line.decode(self.data_encoding, self.errors) |
| 1779 |
for search in self.substitutions: |
| 1780 |
sub = self.substitutions[search] |
| 1781 |
line = re.sub(search, sub, line) |
| 1782 |
if self.file_encoding: |
| 1783 |
line = line.encode(self.file_encoding, self.errors) |
| 1784 |
lines.append(line) |
| 1785 |
if lines: |
| 1786 |
self.stream.write(self.linesep_out.join(lines)) |
| 1787 |
|
| 1788 |
|
| 1789 |
class Producer: |
| 1790 |
"""Generic producer. |
| 1791 |
|
| 1792 |
Args: |
| 1793 |
worker (Worker): The worker instance that will run the producer. |
| 1794 |
producer (callable): The function to be called by the worker. |
| 1795 |
continue_next (bool): If True, the worker will continue to the next task |
| 1796 |
even if the producer raises an exception. Defaults to False. |
| 1797 |
""" |
| 1798 |
|
| 1799 |
def __init__(self, worker, producer, continue_next=False): |
| 1800 |
self.worker = worker |
| 1801 |
self.producer = producer |
| 1802 |
self.continue_next = continue_next |
| 1803 |
|
| 1804 |
def __call__(self, *args, **kwargs): |
| 1805 |
"""Call the producer function with the given arguments. |
| 1806 |
|
| 1807 |
Args: |
| 1808 |
*args: Positional arguments to pass to the producer. |
| 1809 |
**kwargs: Keyword arguments to pass to the producer. |
| 1810 |
|
| 1811 |
Returns: |
| 1812 |
The result of the producer function. |
| 1813 |
""" |
| 1814 |
try: |
| 1815 |
result = self.producer(*args, **kwargs) |
| 1816 |
except Exception as exception: |
| 1817 |
if DEBUG: |
| 1818 |
messages = traceback.format_exception(exception) |
| 1819 |
print( |
| 1820 |
"[D] Worker raised an unhandled exception: \n" + "\n".join(messages) |
| 1821 |
) |
| 1822 |
raise |
| 1823 |
if ( |
| 1824 |
not self.continue_next |
| 1825 |
and self.worker._progress_wnd |
| 1826 |
and hasattr(self.worker.progress_wnd, "animbmp") |
| 1827 |
and self.worker.progress_wnd.progress_type in (0, 2) |
| 1828 |
): |
| 1829 |
# Allow time for animation fadeout |
| 1830 |
wx.CallAfter(self.worker.progress_wnd.stop_timer, False) |
| 1831 |
if self.worker.progress_wnd.progress_type == 0: |
| 1832 |
sleep(4) |
| 1833 |
else: |
| 1834 |
sleep(1) |
| 1835 |
return result |
| 1836 |
|
| 1837 |
|
| 1838 |
class StringWithLengthOverride(UserString): |
| 1839 |
"""Allow defined behavior in comparisons and when evaluating length.""" |
| 1840 |
|
| 1841 |
def __init__(self, seq, length=None): |
| 1842 |
UserString.__init__(self, seq) |
| 1843 |
if length is None: |
| 1844 |
length = len(seq) |
| 1845 |
self.length = length |
| 1846 |
|
| 1847 |
def __len__(self) -> int: |
| 1848 |
"""Return the length of the string. |
| 1849 |
|
| 1850 |
Returns: |
| 1851 |
int: The length of the string. |
| 1852 |
""" |
| 1853 |
return self.length |
| 1854 |
|
| 1855 |
|
| 1856 |
class Sudo: |
| 1857 |
"""Determine if a command can be run via sudo.""" |
| 1858 |
|
| 1859 |
def __init__(self): |
| 1860 |
self.availoptions = {} |
| 1861 |
self.sudo = which("sudo") |
| 1862 |
if self.sudo: |
| 1863 |
# Determine available sudo options |
| 1864 |
man = which("man") |
| 1865 |
if man: |
| 1866 |
manproc = sp.Popen([man, "sudo"], stdout=sp.PIPE, stderr=sp.PIPE) |
| 1867 |
# Strip formatting |
| 1868 |
stdout = re.sub(b".\x08", b"", manproc.communicate()[0]) |
| 1869 |
self.availoptions = { |
| 1870 |
"E": bool(re.search(rb"-E\W", stdout)), |
| 1871 |
"l [command]": bool(re.search(rb"-l\W(?:.*?\W)?command\W", stdout)), |
| 1872 |
"K": bool(re.search(rb"-K\W", stdout)), |
| 1873 |
"k": bool(re.search(rb"-k\W", stdout)), |
| 1874 |
} |
| 1875 |
if DEBUG: |
| 1876 |
print( |
| 1877 |
"[D] Available sudo options:", |
| 1878 |
", ".join( |
| 1879 |
[ |
| 1880 |
option |
| 1881 |
for option in list(self.availoptions.keys()) |
| 1882 |
if self.availoptions[option] |
| 1883 |
] |
| 1884 |
), |
| 1885 |
) |
| 1886 |
|
| 1887 |
def __len__(self) -> int: |
| 1888 |
"""Return 1 if sudo is available, otherwise 0. |
| 1889 |
|
| 1890 |
Returns: |
| 1891 |
int: 1 if sudo is available, otherwise 0. |
| 1892 |
""" |
| 1893 |
return int(bool(self.sudo)) |
| 1894 |
|
| 1895 |
def __str__(self) -> str: |
| 1896 |
"""Return the sudo command with options. |
| 1897 |
|
| 1898 |
Returns: |
| 1899 |
str: The sudo command with options. |
| 1900 |
""" |
| 1901 |
return str(self.sudo or "") |
| 1902 |
|
| 1903 |
def _expect_timeout(self, patterns, timeout=-1, child_timeout=1): |
| 1904 |
"""wexpect.spawn.expect with better timeout handling. |
| 1905 |
|
| 1906 |
The default expect can block up to timeout seconds if the child is already dead. |
| 1907 |
To prevent this, we run expect in a loop until a pattern is matched, timeout is |
| 1908 |
reached or an exception occurs. The max time an expect call will block if the |
| 1909 |
child is already dead can be set with the child_timeout parameter. |
| 1910 |
""" |
| 1911 |
if timeout == -1: |
| 1912 |
timeout = self.subprocess.timeout |
| 1913 |
patterns = list(patterns) |
| 1914 |
if wexpect.TIMEOUT not in patterns: |
| 1915 |
patterns.append(wexpect.TIMEOUT) |
| 1916 |
start = time() |
| 1917 |
while True: |
| 1918 |
result = self.subprocess.expect(patterns, timeout=child_timeout) |
| 1919 |
if ( |
| 1920 |
self.subprocess.after is not wexpect.TIMEOUT |
| 1921 |
or time() - start >= timeout |
| 1922 |
): |
| 1923 |
break |
| 1924 |
return result |
| 1925 |
|
| 1926 |
def _terminate(self): |
| 1927 |
"""Terminate running sudo subprocess.""" |
| 1928 |
self.subprocess.sendcontrol("C") |
| 1929 |
self._expect_timeout([wexpect.EOF], 10) |
| 1930 |
if self.subprocess.after is wexpect.TIMEOUT: |
| 1931 |
print("Warning: sudo timed out") |
| 1932 |
if not self.subprocess.terminate(force=True): |
| 1933 |
print("Warning: Couldn't terminate timed-out sudo subprocess") |
| 1934 |
else: |
| 1935 |
subprocess_before = self.subprocess.before.strip() |
| 1936 |
if isinstance(subprocess_before, bytes): |
| 1937 |
subprocess_before = subprocess_before.decode(ENC, "replace") |
| 1938 |
print(subprocess_before) |
| 1939 |
|
| 1940 |
def authenticate(self, args, title, parent=None): |
| 1941 |
"""Authenticate for a given command. |
| 1942 |
|
| 1943 |
The return value will be a tuple (auth_successful, password). |
| 1944 |
|
| 1945 |
auth_successful will be a custom class that will always have length 0 if |
| 1946 |
authentication was not successful or the command is not allowed (even |
| 1947 |
if the actual string length is non-zero), thus allowing for easy |
| 1948 |
boolean comparisons. |
| 1949 |
|
| 1950 |
""" |
| 1951 |
# Authentication using sudo is pretty convoluted if dealing with |
| 1952 |
# platform and configuration differences. Ask for a password by first |
| 1953 |
# clearing any cached credentials (sudo -K) so that sudo is guaranteed |
| 1954 |
# to ask for a password if a command is run through it, then we spawn |
| 1955 |
# sudo true (with true being the standard GNU utility that always |
| 1956 |
# has an exit status of 0) and expect the password prompt. The user |
| 1957 |
# is then given the opportunity to enter a password, which is then fed |
| 1958 |
# to sudo. If sudo exits with a status of 0, the password must have |
| 1959 |
# been accepted, but we still don't know for sure if our command is |
| 1960 |
# allowed, so we run sudo -l <command> to determine if it is |
| 1961 |
# indeed allowed. |
| 1962 |
pwd = "" |
| 1963 |
dlg = ConfirmDialog( |
| 1964 |
parent, |
| 1965 |
title=title, |
| 1966 |
msg=lang.getstr("dialog.enter_password"), |
| 1967 |
ok=lang.getstr("ok"), |
| 1968 |
cancel=lang.getstr("cancel"), |
| 1969 |
bitmap=get_icon(32, "lock"), |
| 1970 |
) |
| 1971 |
dlg.pwd_txt_ctrl = wx.TextCtrl( |
| 1972 |
dlg, -1, pwd, size=(320, -1), style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER |
| 1973 |
) |
| 1974 |
dlg.pwd_txt_ctrl.Bind(wx.EVT_TEXT_ENTER, lambda event: dlg.EndModal(wx.ID_OK)) |
| 1975 |
dlg.sizer3.Add( |
| 1976 |
dlg.pwd_txt_ctrl, |
| 1977 |
1, |
| 1978 |
# flag=wx.TOP | wx.ALIGN_LEFT, border=12) |
| 1979 |
flag=wx.TOP, |
| 1980 |
border=12, |
| 1981 |
) |
| 1982 |
dlg.ok.SetDefault() |
| 1983 |
dlg.sizer0.SetSizeHints(dlg) |
| 1984 |
dlg.sizer0.Layout() |
| 1985 |
# Remove cached credentials |
| 1986 |
self.kill() |
| 1987 |
sudo_args = ["-p", "Password:", "true"] |
| 1988 |
try: |
| 1989 |
p = self.subprocess = wexpect.spawn(safe_str(self.sudo), sudo_args) |
| 1990 |
except Exception as exception: |
| 1991 |
return ( |
| 1992 |
StringWithLengthOverride( |
| 1993 |
"Could not run {} {}: {}".format( |
| 1994 |
self.sudo, " ".join(sudo_args), exception |
| 1995 |
), |
| 1996 |
0, |
| 1997 |
), |
| 1998 |
pwd, |
| 1999 |
) |
| 2000 |
self._expect_timeout(["Password:", wexpect.EOF], 10) |
| 2001 |
# We need to call isalive() to set the exitstatus |
| 2002 |
while p.isalive() and p.after == "Password:": |
| 2003 |
# Ask for password |
| 2004 |
dlg.pwd_txt_ctrl.SetFocus() |
| 2005 |
result = dlg.ShowModal() |
| 2006 |
pwd = dlg.pwd_txt_ctrl.GetValue() |
| 2007 |
if result != wx.ID_OK: |
| 2008 |
self._terminate() |
| 2009 |
return False, pwd |
| 2010 |
p.send(pwd + os.linesep) |
| 2011 |
self._expect_timeout(["Password:", wexpect.EOF], 10) |
| 2012 |
if p.after == "Password:": |
| 2013 |
msg = lang.getstr("dialog.enter_password") |
| 2014 |
errstr = p.before.strip() |
| 2015 |
if errstr: |
| 2016 |
print(errstr) |
| 2017 |
msg = f"{errstr}\n\n{msg}" |
| 2018 |
dlg.message.SetLabel(msg) |
| 2019 |
dlg.message.Wrap(dlg.GetSize()[0] - 32 - 12 * 2) |
| 2020 |
dlg.pwd_txt_ctrl.SetValue("") |
| 2021 |
dlg.sizer0.SetSizeHints(dlg) |
| 2022 |
dlg.sizer0.Layout() |
| 2023 |
dlg.Destroy() |
| 2024 |
if p.after is wexpect.TIMEOUT: |
| 2025 |
print("Error: sudo timed out") |
| 2026 |
if not p.terminate(force=True): |
| 2027 |
print("Warning: Couldn't terminate timed-out sudo subprocess") |
| 2028 |
return StringWithLengthOverride("sudo timed out", 0), pwd |
| 2029 |
if p.exitstatus != 0: |
| 2030 |
return ( |
| 2031 |
StringWithLengthOverride( |
| 2032 |
p.before.strip().decode(ENC, "replace") |
| 2033 |
or (f"sudo exited prematurely with status {p.exitstatus}"), |
| 2034 |
0, |
| 2035 |
), |
| 2036 |
pwd, |
| 2037 |
) |
| 2038 |
# Password was accepted, check if command is allowed |
| 2039 |
return self.is_allowed(args, pwd), pwd |
| 2040 |
|
| 2041 |
def is_allowed(self, args=None, pwd=""): |
| 2042 |
"""Check if a command is allowed via sudo. |
| 2043 |
|
| 2044 |
Return either a string listing allowed and forbidden commands, or the |
| 2045 |
fully-qualified path of the command along with any arguments, or an error |
| 2046 |
message in case the command is not allowed, or False if the password was not |
| 2047 |
accepted. |
| 2048 |
|
| 2049 |
The returned error is a custom class that will always have length 0 |
| 2050 |
if the command is not allowed (even if the actual string length is |
| 2051 |
non-zero), thus allowing for easy boolean comparisons. |
| 2052 |
""" |
| 2053 |
sudo_args = ["-p", "Password:", "-l"] |
| 2054 |
# Set sudo args based on available options |
| 2055 |
if self.availoptions.get("l [command]") and args: |
| 2056 |
sudo_args += args |
| 2057 |
try: |
| 2058 |
p = self.subprocess = wexpect.spawn(safe_str(self.sudo), sudo_args) |
| 2059 |
except Exception as exception: |
| 2060 |
return StringWithLengthOverride( |
| 2061 |
"Could not run {} {}: {}".format( |
| 2062 |
self.sudo, " ".join(sudo_args), exception |
| 2063 |
), |
| 2064 |
0, |
| 2065 |
) |
| 2066 |
self._expect_timeout(["Password:", wexpect.EOF], 10) |
| 2067 |
# We need to call isalive() to set the exitstatus |
| 2068 |
while p.isalive() and p.after == "Password:": |
| 2069 |
p.send(pwd + os.linesep) |
| 2070 |
self._expect_timeout(["Password:", wexpect.EOF], 10) |
| 2071 |
if p.after == "Password:": |
| 2072 |
# Password was not accepted |
| 2073 |
self._terminate() |
| 2074 |
return StringWithLengthOverride(p.before.strip(), 0) |
| 2075 |
if p.after is wexpect.TIMEOUT: |
| 2076 |
print("Error: sudo timed out") |
| 2077 |
if not p.terminate(force=True): |
| 2078 |
print("Warning: Couldn't terminate timed-out sudo subprocess") |
| 2079 |
return StringWithLengthOverride("sudo timed out", 0) |
| 2080 |
if p.exitstatus != 0: |
| 2081 |
return StringWithLengthOverride( |
| 2082 |
p.before.strip() |
| 2083 |
or (f"sudo exited prematurely with status {p.exitstatus}"), |
| 2084 |
0, |
| 2085 |
) |
| 2086 |
return p.before.strip() |
| 2087 |
|
| 2088 |
def kill(self): |
| 2089 |
"""Remove cached credentials.""" |
| 2090 |
kill_arg = None |
| 2091 |
if self.availoptions.get("K"): |
| 2092 |
kill_arg = "-K" |
| 2093 |
elif self.availoptions.get("k"): |
| 2094 |
kill_arg = "-k" |
| 2095 |
if kill_arg: |
| 2096 |
sp.call([safe_str(self.sudo), kill_arg]) |
| 2097 |
|
| 2098 |
|
| 2099 |
class WPopen(sp.Popen): |
| 2100 |
"""A wrapper around subprocess.Popen to handle output and errors.""" |
| 2101 |
|
| 2102 |
def __init__(self, *args, **kwargs): |
| 2103 |
sp.Popen.__init__(self, *args, **kwargs) |
| 2104 |
self._seekpos = 0 |
| 2105 |
self._stdout = kwargs["stdout"] |
| 2106 |
self.after = None |
| 2107 |
self.before = None |
| 2108 |
self.exitstatus = None |
| 2109 |
self.logfile_read = None |
| 2110 |
self.match = None |
| 2111 |
self.maxlen = 80 |
| 2112 |
self.timeout = 30 |
| 2113 |
|
| 2114 |
def isalive(self): |
| 2115 |
"""Check if the process is still alive. |
| 2116 |
|
| 2117 |
Returns: |
| 2118 |
bool: True if the process is still running, False otherwise. |
| 2119 |
""" |
| 2120 |
self.exitstatus = self.poll() |
| 2121 |
return self.exitstatus is None |
| 2122 |
|
| 2123 |
def expect(self, patterns, timeout=-1): |
| 2124 |
"""Wait for one of the specified patterns in the process's stdout. |
| 2125 |
|
| 2126 |
Args: |
| 2127 |
patterns (list or str): A list of patterns to match against the |
| 2128 |
process's stdout, or a single pattern. |
| 2129 |
timeout (int): The maximum time to wait for a match, in seconds. |
| 2130 |
If -1, the default timeout is used. |
| 2131 |
|
| 2132 |
Returns: |
| 2133 |
str: The matched pattern if found, or None if no match is found |
| 2134 |
before the timeout. |
| 2135 |
""" |
| 2136 |
if not isinstance(patterns, list): |
| 2137 |
patterns = [patterns] |
| 2138 |
if timeout == -1: |
| 2139 |
timeout = self.timeout |
| 2140 |
if timeout is not None: |
| 2141 |
end = time() + timeout |
| 2142 |
while timeout is None or time() < end: |
| 2143 |
self._stdout.seek(self._seekpos) |
| 2144 |
buf = self._stdout.read() |
| 2145 |
self._seekpos += len(buf) |
| 2146 |
if not buf and not self.isalive(): |
| 2147 |
self.match = wexpect.EOF( |
| 2148 |
"End Of File (EOF) in expect() - dead child process" |
| 2149 |
) |
| 2150 |
if wexpect.EOF in patterns: |
| 2151 |
return self.match |
| 2152 |
raise self.match |
| 2153 |
if buf and self.logfile_read: |
| 2154 |
self.logfile_read.write(buf) |
| 2155 |
for pattern in patterns: |
| 2156 |
if isinstance(pattern, str) and pattern in buf: |
| 2157 |
offset = buf.find(pattern) |
| 2158 |
self.after = buf[offset:] |
| 2159 |
self.before = buf[:offset] |
| 2160 |
self.match = buf[offset : offset + len(pattern)] |
| 2161 |
return self.match |
| 2162 |
sleep(0.01) |
| 2163 |
if timeout is not None: |
| 2164 |
self.match = wexpect.TIMEOUT("Timeout exceeded in expect()") |
| 2165 |
if wexpect.TIMEOUT in patterns: |
| 2166 |
return self.match |
| 2167 |
raise self.match |
| 2168 |
return None |
| 2169 |
|
| 2170 |
def send(self, s): |
| 2171 |
"""Send a string to the process's stdin. |
| 2172 |
|
| 2173 |
Args: |
| 2174 |
s (str): The string to send. |
| 2175 |
""" |
| 2176 |
self.stdin.write(s) |
| 2177 |
self._stdout.seek(self._seekpos) |
| 2178 |
buf = self._stdout.read() |
| 2179 |
self._seekpos += len(buf) |
| 2180 |
if buf and self.logfile_read: |
| 2181 |
self.logfile_read.write(buf) |
| 2182 |
|
| 2183 |
def terminate(self, force=False): |
| 2184 |
"""Terminate the process, optionally forcing it. |
| 2185 |
|
| 2186 |
Args: |
| 2187 |
force (bool): If True, force termination of the process. |
| 2188 |
""" |
| 2189 |
sp.Popen.terminate(self) |
| 2190 |
|
| 2191 |
|
| 2192 |
_coregraphics = None |
| 2193 |
_corefoundation = None |
| 2194 |
|
| 2195 |
|
| 2196 |
def _get_coregraphics(): |
| 2197 |
"""Return the CoreGraphics CDLL (macOS only), or None.""" |
| 2198 |
global _coregraphics |
| 2199 |
if _coregraphics is None and sys.platform == "darwin": |
| 2200 |
try: |
| 2201 |
_coregraphics = ctypes.CDLL( |
| 2202 |
"/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics" |
| 2203 |
) |
| 2204 |
except OSError: |
| 2205 |
_coregraphics = False # Mark as tried-and-failed |
| 2206 |
return _coregraphics or None |
| 2207 |
|
| 2208 |
|
| 2209 |
def _get_corefoundation(): |
| 2210 |
"""Return the CoreFoundation CDLL (macOS only), or None.""" |
| 2211 |
global _corefoundation |
| 2212 |
if _corefoundation is None and sys.platform == "darwin": |
| 2213 |
try: |
| 2214 |
_corefoundation = ctypes.CDLL( |
| 2215 |
"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation" |
| 2216 |
) |
| 2217 |
except OSError: |
| 2218 |
_corefoundation = False # Mark as tried-and-failed |
| 2219 |
return _corefoundation or None |
| 2220 |
|
| 2221 |
|
| 2222 |
def _macos_active_display_ids(max_displays=16): |
| 2223 |
"""Return active CGDirectDisplayIDs in CoreGraphics enumeration order. |
| 2224 |
|
| 2225 |
This order matches ArgyllCMS' ``dispwin -d`` numbering (both come from |
| 2226 |
CGGetActiveDisplayList), so index i here is display i+1 for dispwin. |
| 2227 |
|
| 2228 |
Returns: |
| 2229 |
None | ctypes.CDLL, list[int]: The CoreGraphics CDLL (for reuse by the |
| 2230 |
caller) and the list of display IDs, or (None, []) if |
| 2231 |
CoreGraphics is unavailable. |
| 2232 |
""" |
| 2233 |
cg = _get_coregraphics() |
| 2234 |
if cg is None: |
| 2235 |
return None, [] |
| 2236 |
cg.CGGetActiveDisplayList.argtypes = [ |
| 2237 |
ctypes.c_uint32, |
| 2238 |
ctypes.POINTER(ctypes.c_uint32), |
| 2239 |
ctypes.POINTER(ctypes.c_uint32), |
| 2240 |
] |
| 2241 |
ids = (ctypes.c_uint32 * max_displays)() |
| 2242 |
count = ctypes.c_uint32(0) |
| 2243 |
if cg.CGGetActiveDisplayList(max_displays, ids, ctypes.byref(count)) != 0: |
| 2244 |
return cg, [] |
| 2245 |
return cg, list(ids[: count.value]) |
| 2246 |
|
| 2247 |
|
| 2248 |
def get_macos_videolut_maxima(max_displays=16): |
| 2249 |
"""Return the maximum VideoLUT output value for each active display (macOS). |
| 2250 |
|
| 2251 |
Used to detect a display whose VideoLUT has been clobbered to all-black |
| 2252 |
(issue #694): a black VideoLUT has a maximum output near 0.0, a normal one |
| 2253 |
near 1.0. The list is indexed in CoreGraphics active-display order, which |
| 2254 |
matches ArgyllCMS' ``dispwin -d`` numbering (both come from |
| 2255 |
CGGetActiveDisplayList). |
| 2256 |
|
| 2257 |
Returns: |
| 2258 |
list[None | float]: Per-display maxima (0.0 - 1.0), None for a display |
| 2259 |
that couldn't be read, or [] if CoreGraphics is unavailable. |
| 2260 |
""" |
| 2261 |
cg, ids = _macos_active_display_ids(max_displays) |
| 2262 |
if cg is None or not ids: |
| 2263 |
return [] |
| 2264 |
cg.CGDisplayGammaTableCapacity.restype = ctypes.c_uint32 |
| 2265 |
cg.CGDisplayGammaTableCapacity.argtypes = [ctypes.c_uint32] |
| 2266 |
cg.CGGetDisplayTransferByTable.argtypes = [ |
| 2267 |
ctypes.c_uint32, |
| 2268 |
ctypes.c_uint32, |
| 2269 |
ctypes.POINTER(ctypes.c_float), |
| 2270 |
ctypes.POINTER(ctypes.c_float), |
| 2271 |
ctypes.POINTER(ctypes.c_float), |
| 2272 |
ctypes.POINTER(ctypes.c_uint32), |
| 2273 |
] |
| 2274 |
maxima = [] |
| 2275 |
for did in ids: |
| 2276 |
cap = cg.CGDisplayGammaTableCapacity(did) or 256 |
| 2277 |
red = (ctypes.c_float * cap)() |
| 2278 |
green = (ctypes.c_float * cap)() |
| 2279 |
blue = (ctypes.c_float * cap)() |
| 2280 |
nent = ctypes.c_uint32(0) |
| 2281 |
if ( |
| 2282 |
cg.CGGetDisplayTransferByTable( |
| 2283 |
did, cap, red, green, blue, ctypes.byref(nent) |
| 2284 |
) |
| 2285 |
!= 0 |
| 2286 |
): |
| 2287 |
maxima.append(None) |
| 2288 |
continue |
| 2289 |
channel_max = 0.0 |
| 2290 |
for channel in (red, green, blue): |
| 2291 |
for j in range(nent.value): |
| 2292 |
if channel[j] > channel_max: |
| 2293 |
channel_max = channel[j] |
| 2294 |
maxima.append(channel_max) |
| 2295 |
return maxima |
| 2296 |
|
| 2297 |
|
| 2298 |
def get_macos_videolut_capacity(display_index, max_displays=16): |
| 2299 |
"""Return the VideoLUT entry count for one active macOS display. |
| 2300 |
|
| 2301 |
Args: |
| 2302 |
display_index (int): Zero-based display index (CoreGraphics/dispwin |
| 2303 |
order, see :func:`_macos_active_display_ids`). |
| 2304 |
|
| 2305 |
Returns: |
| 2306 |
None | int: The VideoLUT capacity, or None if it couldn't be read. |
| 2307 |
""" |
| 2308 |
cg, ids = _macos_active_display_ids(max_displays) |
| 2309 |
if cg is None or display_index >= len(ids): |
| 2310 |
return None |
| 2311 |
cg.CGDisplayGammaTableCapacity.restype = ctypes.c_uint32 |
| 2312 |
cg.CGDisplayGammaTableCapacity.argtypes = [ctypes.c_uint32] |
| 2313 |
return cg.CGDisplayGammaTableCapacity(ids[display_index]) or None |
| 2314 |
|
| 2315 |
|
| 2316 |
def set_macos_videolut(display_index, red, green, blue, max_displays=16): |
| 2317 |
"""Set one active macOS display's VideoLUT directly via CoreGraphics. |
| 2318 |
|
| 2319 |
Bypasses spawning a ``dispwin`` subprocess entirely. Argyll's dispwin has |
| 2320 |
to exit after every invocation, and macOS's own cleanup of a just-exited |
| 2321 |
process's transient VideoLUT claim has a bug where it can zero a |
| 2322 |
*different*, untouched display's gamma table (issue #824). Applying |
| 2323 |
corrected tables to every clobbered display from a single persistent |
| 2324 |
process, with no process exit in between, avoids that OS bug entirely - |
| 2325 |
confirmed experimentally on real multi-display hardware. |
| 2326 |
|
| 2327 |
Args: |
| 2328 |
display_index (int): Zero-based display index (CoreGraphics/dispwin |
| 2329 |
order, see :func:`_macos_active_display_ids`). |
| 2330 |
red, green, blue (Sequence[float]): Per-channel output values |
| 2331 |
(0.0 - 1.0), all the same length. |
| 2332 |
|
| 2333 |
Returns: |
| 2334 |
bool: True on success. |
| 2335 |
""" |
| 2336 |
cg, ids = _macos_active_display_ids(max_displays) |
| 2337 |
if cg is None or display_index >= len(ids): |
| 2338 |
return False |
| 2339 |
nent = len(red) |
| 2340 |
cg.CGSetDisplayTransferByTable.restype = ctypes.c_int32 |
| 2341 |
cg.CGSetDisplayTransferByTable.argtypes = [ |
| 2342 |
ctypes.c_uint32, |
| 2343 |
ctypes.c_uint32, |
| 2344 |
ctypes.POINTER(ctypes.c_float), |
| 2345 |
ctypes.POINTER(ctypes.c_float), |
| 2346 |
ctypes.POINTER(ctypes.c_float), |
| 2347 |
] |
| 2348 |
red_arr = (ctypes.c_float * nent)(*red) |
| 2349 |
green_arr = (ctypes.c_float * nent)(*green) |
| 2350 |
blue_arr = (ctypes.c_float * nent)(*blue) |
| 2351 |
return ( |
| 2352 |
cg.CGSetDisplayTransferByTable( |
| 2353 |
ids[display_index], nent, red_arr, green_arr, blue_arr |
| 2354 |
) |
| 2355 |
== 0 |
| 2356 |
) |
| 2357 |
|
| 2358 |
|
| 2359 |
def vcgt_values_to_videolut(vcgt_values, nent): |
| 2360 |
"""Interpolate vcgt channel points onto a VideoLUT of ``nent`` entries. |
| 2361 |
|
| 2362 |
Args: |
| 2363 |
vcgt_values (list[list[float, float]]): A single channel's vcgt |
| 2364 |
points as returned by |
| 2365 |
:meth:`DisplayCAL.icc_profile.VideoCardGammaType.get_values`, |
| 2366 |
i.e. ``[input_0_255, output_0_65535]`` pairs. |
| 2367 |
nent (int): Target VideoLUT entry count. |
| 2368 |
|
| 2369 |
Returns: |
| 2370 |
list[float]: ``nent`` output values (0.0 - 1.0), linearly |
| 2371 |
interpolated the same way ArgyllCMS' dispwin interpolates a |
| 2372 |
.cal file's entries onto a display's actual VideoLUT size. |
| 2373 |
""" |
| 2374 |
ncal = len(vcgt_values) |
| 2375 |
values = [point[1] / 65535.0 for point in vcgt_values] |
| 2376 |
if ncal < 2 or nent < 2: |
| 2377 |
return [values[-1] if values else 1.0] * nent |
| 2378 |
out = [] |
| 2379 |
for i in range(nent): |
| 2380 |
pos = (ncal - 1) * i / (nent - 1) |
| 2381 |
ix = min(int(pos), ncal - 2) |
| 2382 |
weight = pos - ix |
| 2383 |
out.append(values[ix] + weight * (values[ix + 1] - values[ix])) |
| 2384 |
return out |
| 2385 |
|
| 2386 |
|
| 2387 |
def get_macos_display_profile_data(display_index, max_displays=16): |
| 2388 |
"""Return the raw ICC profile bytes CoreGraphics currently has for a display. |
| 2389 |
|
| 2390 |
Uses ``CGDisplayCopyColorSpace()``/``CGColorSpaceCopyICCData()`` directly, |
| 2391 |
rather than DisplayCAL's usual :func:`DisplayCAL.icc_profile.get_display_profile` |
| 2392 |
(which queries the "Image Events" AppleScript scripting interface - this |
| 2393 |
has been confirmed to fail outright on current macOS, e.g. Tahoe, raising |
| 2394 |
"Can't get display profile of display N (-1728)"), and rather than |
| 2395 |
running a dispwin subprocess (which risks re-triggering issue #824). |
| 2396 |
|
| 2397 |
Args: |
| 2398 |
display_index (int): Zero-based display index (CoreGraphics/dispwin |
| 2399 |
order, see :func:`_macos_active_display_ids`). |
| 2400 |
|
| 2401 |
Returns: |
| 2402 |
None | bytes: The profile data, or None if it couldn't be read. |
| 2403 |
""" |
| 2404 |
cg, ids = _macos_active_display_ids(max_displays) |
| 2405 |
if cg is None or display_index >= len(ids): |
| 2406 |
return None |
| 2407 |
cf = _get_corefoundation() |
| 2408 |
if cf is None: |
| 2409 |
return None |
| 2410 |
cg.CGDisplayCopyColorSpace.restype = ctypes.c_void_p |
| 2411 |
cg.CGDisplayCopyColorSpace.argtypes = [ctypes.c_uint32] |
| 2412 |
cg.CGColorSpaceCopyICCData.restype = ctypes.c_void_p |
| 2413 |
cg.CGColorSpaceCopyICCData.argtypes = [ctypes.c_void_p] |
| 2414 |
cg.CGColorSpaceRelease.argtypes = [ctypes.c_void_p] |
| 2415 |
cf.CFDataGetLength.restype = ctypes.c_long |
| 2416 |
cf.CFDataGetLength.argtypes = [ctypes.c_void_p] |
| 2417 |
cf.CFDataGetBytePtr.restype = ctypes.c_void_p |
| 2418 |
cf.CFDataGetBytePtr.argtypes = [ctypes.c_void_p] |
| 2419 |
cf.CFRelease.argtypes = [ctypes.c_void_p] |
| 2420 |
|
| 2421 |
colorspace = cg.CGDisplayCopyColorSpace(ids[display_index]) |
| 2422 |
if not colorspace: |
| 2423 |
return None |
| 2424 |
try: |
| 2425 |
icc_data = cg.CGColorSpaceCopyICCData(colorspace) |
| 2426 |
if not icc_data: |
| 2427 |
return None |
| 2428 |
try: |
| 2429 |
length = cf.CFDataGetLength(icc_data) |
| 2430 |
ptr = cf.CFDataGetBytePtr(icc_data) |
| 2431 |
if not ptr or length <= 0: |
| 2432 |
return None |
| 2433 |
return ctypes.string_at(ptr, length) |
| 2434 |
finally: |
| 2435 |
cf.CFRelease(icc_data) |
| 2436 |
finally: |
| 2437 |
cg.CGColorSpaceRelease(colorspace) |
| 2438 |
|
| 2439 |
|
| 2440 |
def _get_macos_display_profile(display_index, log=None): |
| 2441 |
"""Return an ICCProfile for a display, preferring CoreGraphics over AppleScript. |
| 2442 |
|
| 2443 |
See :func:`get_macos_display_profile_data` for why. Falls back to |
| 2444 |
:func:`DisplayCAL.icc_profile.get_display_profile` if CoreGraphics |
| 2445 |
doesn't yield usable profile data. |
| 2446 |
|
| 2447 |
Returns: |
| 2448 |
None | ICCProfile: The display's current profile, or None. |
| 2449 |
""" |
| 2450 |
data = get_macos_display_profile_data(display_index) |
| 2451 |
if data: |
| 2452 |
try: |
| 2453 |
return ICCProfile(data) |
| 2454 |
except Exception as exception: |
| 2455 |
if log: |
| 2456 |
log(exception) |
| 2457 |
try: |
| 2458 |
return get_display_profile(display_index) |
| 2459 |
except Exception as exception: |
| 2460 |
if log: |
| 2461 |
log(exception) |
| 2462 |
return None |
| 2463 |
|
| 2464 |
|
| 2465 |
def reload_macos_videoluts(indices, log=None): |
| 2466 |
"""Re-apply calibration to macOS displays directly via CoreGraphics. |
| 2467 |
|
| 2468 |
Reads each display's currently active ICC profile (no subprocess) and |
| 2469 |
applies its vcgt calibration (or a linear ramp if it has none) to all |
| 2470 |
given displays back-to-back, from this single process. See |
| 2471 |
:func:`set_macos_videolut` for why avoiding a subprocess-per-display |
| 2472 |
matters (issue #824). |
| 2473 |
|
| 2474 |
Args: |
| 2475 |
indices (Iterable[int]): Zero-based display indices to reload. |
| 2476 |
log (None | Callable): Optional logging callable. |
| 2477 |
|
| 2478 |
Returns: |
| 2479 |
list[int]: Indices that were successfully reloaded. |
| 2480 |
""" |
| 2481 |
reloaded = [] |
| 2482 |
for i in indices: |
| 2483 |
nent = get_macos_videolut_capacity(i) |
| 2484 |
if not nent: |
| 2485 |
continue |
| 2486 |
profile = _get_macos_display_profile(i, log=log) |
| 2487 |
vcgt = profile.tags.get("vcgt") if profile else None |
| 2488 |
if vcgt: |
| 2489 |
r_points, g_points, b_points = vcgt.get_values()[:3] |
| 2490 |
red = vcgt_values_to_videolut(r_points, nent) |
| 2491 |
green = vcgt_values_to_videolut(g_points, nent) |
| 2492 |
blue = vcgt_values_to_videolut(b_points, nent) |
| 2493 |
else: |
| 2494 |
red = green = blue = [j / (nent - 1.0) for j in range(nent)] |
| 2495 |
if set_macos_videolut(i, red, green, blue): |
| 2496 |
reloaded.append(i) |
| 2497 |
elif log: |
| 2498 |
log(f"Failed to set VideoLUT for display {i + 1:d}") |
| 2499 |
return reloaded |
| 2500 |
|
| 2501 |
|
| 2502 |
def reload_black_videoluts( |
| 2503 |
dispwin, |
| 2504 |
threshold=0.05, |
| 2505 |
retries=4, |
| 2506 |
settle=0.3, |
| 2507 |
log=None, |
| 2508 |
_maxima_fn=None, |
| 2509 |
_run=None, |
| 2510 |
_sleep=None, |
| 2511 |
): |
| 2512 |
"""Re-load the VideoLUT of any macOS display that has gone black (issue #694). |
| 2513 |
|
| 2514 |
On macOS the OS (WindowServer) intermittently resets a display's VideoLUT to |
| 2515 |
all-black when an ArgyllCMS display tool exits, turning the screen black. |
| 2516 |
This detects that via CoreGraphics and re-loads the display's installed |
| 2517 |
calibration with ``dispwin -d{N} -L`` (exactly what un-blacks the screen), |
| 2518 |
retrying until it sticks (the re-load itself can occasionally be clobbered |
| 2519 |
again) or the retries run out. |
| 2520 |
|
| 2521 |
Args: |
| 2522 |
dispwin (str): Path to the dispwin executable. |
| 2523 |
threshold (float): VideoLUT max output below which a display is |
| 2524 |
considered black. |
| 2525 |
retries (int): Maximum number of detect/re-load passes. |
| 2526 |
settle (float): Seconds to wait between passes. |
| 2527 |
log (None | Callable): Optional logging callable. |
| 2528 |
_maxima_fn, _run, _sleep: Injection points for testing. |
| 2529 |
|
| 2530 |
Returns: |
| 2531 |
list[int]: Zero-based indices of displays that were re-loaded. |
| 2532 |
""" |
| 2533 |
if sys.platform != "darwin" or not dispwin: |
| 2534 |
return [] |
| 2535 |
maxima_fn = _maxima_fn or get_macos_videolut_maxima |
| 2536 |
run = _run or (lambda cmd: sp.call(cmd)) |
| 2537 |
sleep_fn = _sleep or sleep |
| 2538 |
reloaded = [] |
| 2539 |
for _ in range(max(1, int(retries))): |
| 2540 |
black = [ |
| 2541 |
i |
| 2542 |
for i, m in enumerate(maxima_fn()) |
| 2543 |
if m is not None and m < threshold |
| 2544 |
] |
| 2545 |
if not black: |
| 2546 |
break |
| 2547 |
for i in black: |
| 2548 |
if log: |
| 2549 |
log( |
| 2550 |
f"{APPNAME}: VideoLUT for display {i + 1:d} is black - " |
| 2551 |
"re-loading calibration (issue #694)" |
| 2552 |
) |
| 2553 |
run([dispwin, "-v", f"-d{i + 1:d}", "-L"]) |
| 2554 |
if i not in reloaded: |
| 2555 |
reloaded.append(i) |
| 2556 |
sleep_fn(settle) |
| 2557 |
return reloaded |
| 2558 |
|
| 2559 |
|
| 2560 |
class Worker(WorkerBase): |
| 2561 |
"""Worker class for ArgyllCMS. |
| 2562 |
|
| 2563 |
Args: |
| 2564 |
owner (wx.Frame, optional): The owner frame for dialogs. Defaults to |
| 2565 |
None. This is typically used to display dialogs or messages |
| 2566 |
related to the worker's operations. |
| 2567 |
""" |
| 2568 |
|
| 2569 |
def __init__(self, owner=None): |
| 2570 |
WorkerBase.__init__(self) |
| 2571 |
self.argyll_bin_dir = None |
| 2572 |
self.argyll_version = [0, 0, 0] |
| 2573 |
self.argyll_version_string = "0.0.0" |
| 2574 |
self._displays = [] |
| 2575 |
self.display_edid = [] |
| 2576 |
self.display_manufacturers = [] |
| 2577 |
self.display_names = [] |
| 2578 |
self.display_rects = [] |
| 2579 |
self.displays = [] |
| 2580 |
self.instruments = [] |
| 2581 |
self.lut_access = [] |
| 2582 |
self.paused = False |
| 2583 |
self._patterngenerator_wait = False |
| 2584 |
|
| 2585 |
self.send_buffer = None |
| 2586 |
self.partial_data = "" |
| 2587 |
self.owner = owner # owner should be a wxFrame or similar |
| 2588 |
if sys.platform == "win32": |
| 2589 |
self.pty_encoding = f"cp{windll.kernel32.GetACP():d}" |
| 2590 |
else: |
| 2591 |
self.pty_encoding = ENC |
| 2592 |
self.cmdrun = False |
| 2593 |
self.dispcal_create_fast_matrix_shaper = False |
| 2594 |
self.dispread_after_dispcal = False |
| 2595 |
self.finished = True |
| 2596 |
self.instrument_on_screen = False |
| 2597 |
self.interactive = False |
| 2598 |
self.spotread_just_do_instrument_calibration = False |
| 2599 |
self.lastcmdname = None |
| 2600 |
# Filter out warnings from OS components (e.g. shared libraries) |
| 2601 |
# E.g.: |
| 2602 |
# Nov 26 16:28:16 dispcal[1006] <Warning>: void CGSUpdateManager::log() const: conn 0x1ec57 token 0x3ffffffffffd0a # noqa: E501 |
| 2603 |
prestrip = re.compile( |
| 2604 |
r"\D+\s+\d+\s+\d+:\d+:\d+\s+\w+\[\d+]\s+<Warning>:[\S\s]*" |
| 2605 |
) |
| 2606 |
discard = [r"[\*\.]+|Current (?:RGB|XYZ)(?: +.*)?"] |
| 2607 |
self.lastmsg_discard = re.compile(r"|".join(discard)) |
| 2608 |
self._init_sounds(dummy=True) |
| 2609 |
self.options_colprof = [] |
| 2610 |
self.options_dispcal = [] |
| 2611 |
self.options_dispread = [] |
| 2612 |
self.options_targen = [] |
| 2613 |
self.pauseable = False |
| 2614 |
discard = [ |
| 2615 |
r"^Display type is .+", |
| 2616 |
r"^Doing (?:some initial|check) measurements", |
| 2617 |
r"^Adjust .+? Press space when done\.\s*", |
| 2618 |
r"^\s*(?:[/\\]\s+)?(?:Adjusted )?(Current", |
| 2619 |
r"Initial", |
| 2620 |
r"[Tt]arget) (?:Br(?:ightness)?", |
| 2621 |
r"50% Level", |
| 2622 |
r"white", |
| 2623 |
r"(?:Near )?[Bb]lack", |
| 2624 |
r"(?:advertised )?gamma", |
| 2625 |
r"RGB", |
| 2626 |
r"\d(?:\.\d+)?).*", |
| 2627 |
r"^Gamma curve .+", |
| 2628 |
r"^Display adjustment menu:", |
| 2629 |
r"^Press", |
| 2630 |
r"^\d\).+", |
| 2631 |
r"^(?:1%|Black|Red|Green|Blue|White|Grey)\s+=.+", |
| 2632 |
r"^\s*patch \d+ of \d+.*", |
| 2633 |
r"^\s*point \d+.*", |
| 2634 |
r"^\s*Added \d+/\d+", |
| 2635 |
# These need to be last because they're very generic! |
| 2636 |
r"[\*\.]+", |
| 2637 |
r"\s*\d*%?", |
| 2638 |
] |
| 2639 |
self.recent_discard = re.compile(r"|".join(discard), re.I) |
| 2640 |
self.resume = False |
| 2641 |
self.sudo = None |
| 2642 |
self.auth_timestamp = 0 |
| 2643 |
self.sessionlogfiles = {} |
| 2644 |
self.triggers = ["Password:"] |
| 2645 |
self.recent = FilteredStream( |
| 2646 |
LineCache(maxlines=3), |
| 2647 |
self.pty_encoding, |
| 2648 |
discard=self.recent_discard, |
| 2649 |
triggers=[*self.triggers, "stopped at user request"], |
| 2650 |
prestrip=prestrip, |
| 2651 |
) |
| 2652 |
self.lastmsg = FilteredStream( |
| 2653 |
LineCache(), |
| 2654 |
self.pty_encoding, |
| 2655 |
discard=self.lastmsg_discard, |
| 2656 |
triggers=self.triggers, |
| 2657 |
prestrip=prestrip, |
| 2658 |
) |
| 2659 |
self.clear_argyll_info() |
| 2660 |
self.set_argyll_version_from_string(getcfg("argyll.version"), False) |
| 2661 |
self.clear_cmd_output() |
| 2662 |
self._detecting_video_levels = False |
| 2663 |
self._detected_output_levels = False |
| 2664 |
self._patterngenerators = {} |
| 2665 |
self._progress_dlgs = {} |
| 2666 |
self._progress_wnd = None |
| 2667 |
self._pwdstr = "" |
| 2668 |
workers.append(self) |
| 2669 |
|
| 2670 |
def _init_sounds(self, dummy=False) -> None: |
| 2671 |
"""Initialize sounds for measurement and commit actions. |
| 2672 |
|
| 2673 |
Args: |
| 2674 |
dummy (bool): If True, use dummy sounds instead of actual sound |
| 2675 |
files. |
| 2676 |
""" |
| 2677 |
if dummy: |
| 2678 |
self.measurement_sound = audio.DummySound() |
| 2679 |
self.commit_sound = audio.DummySound() |
| 2680 |
else: |
| 2681 |
# Sounds when measuring |
| 2682 |
# Needs to be stereo! |
| 2683 |
self.measurement_sound = audio.Sound(get_data_path("beep.wav")) |
| 2684 |
self.commit_sound = audio.Sound(get_data_path("camera_shutter.wav")) |
| 2685 |
|
| 2686 |
def add_measurement_features( |
| 2687 |
self, |
| 2688 |
args, |
| 2689 |
display=True, |
| 2690 |
ignore_display_name=False, |
| 2691 |
allow_nondefault_observer=False, |
| 2692 |
ambient=False, |
| 2693 |
allow_video_levels=True, |
| 2694 |
quantize=False, |
| 2695 |
cmd=None, |
| 2696 |
): |
| 2697 |
"""Add common options and to dispcal, dispread and spotread arguments. |
| 2698 |
|
| 2699 |
Args: |
| 2700 |
args (list): The list of arguments to modify. |
| 2701 |
display (bool): Whether to add display-related arguments. |
| 2702 |
ignore_display_name (bool): Whether to ignore the display name |
| 2703 |
when adding display-related arguments. |
| 2704 |
allow_nondefault_observer (bool): Whether to allow non-default |
| 2705 |
observer settings. |
| 2706 |
ambient (bool): Whether to add ambient light measurement options. |
| 2707 |
allow_video_levels (bool): Whether to allow video levels |
| 2708 |
(e.g. for dispread). |
| 2709 |
quantize (bool): Whether to add quantization options. |
| 2710 |
cmd (str, optional): The command being run (e.g. "dispcal", |
| 2711 |
"dispread", "spotread"). If provided, it can be used to tailor |
| 2712 |
the arguments added based on the command type. |
| 2713 |
|
| 2714 |
Returns: |
| 2715 |
None: The function modifies the args list in place. |
| 2716 |
""" |
| 2717 |
if display and not get_arg("-d", args): |
| 2718 |
args.append("-d" + self.get_display()) |
| 2719 |
if display and allow_video_levels: |
| 2720 |
self.add_video_levels_arg(args) |
| 2721 |
if ( |
| 2722 |
display |
| 2723 |
and quantize |
| 2724 |
and not get_arg("-Z", args) |
| 2725 |
and getcfg("patterngenerator.quantize_bits") |
| 2726 |
): |
| 2727 |
# dispread only |
| 2728 |
args.append("-Z{:d}".format(getcfg("patterngenerator.quantize_bits"))) |
| 2729 |
if not get_arg("-c", args): |
| 2730 |
args.append("-c{}".format(getcfg("comport.number"))) |
| 2731 |
instrument_name = self.get_instrument_name() |
| 2732 |
measurement_mode = getcfg("measurement_mode") |
| 2733 |
if measurement_mode == "auto": |
| 2734 |
# Make changes in DisplayCAL.MainFrame.set_ccxx_measurement_mode too! |
| 2735 |
if instrument_name == "ColorHug": |
| 2736 |
measurement_mode = "R" |
| 2737 |
elif instrument_name == "ColorHug2": |
| 2738 |
measurement_mode = "F" |
| 2739 |
else: |
| 2740 |
measurement_mode = "l" |
| 2741 |
instrument_features = self.get_instrument_features() |
| 2742 |
if ( |
| 2743 |
not ambient |
| 2744 |
and measurement_mode |
| 2745 |
and not get_arg("-y", args) |
| 2746 |
and instrument_name != "specbos 1201" |
| 2747 |
): |
| 2748 |
# Always specify -y for colorimeters (won't be read from cal |
| 2749 |
# when updating) |
| 2750 |
# The specbos 1201 (unlike 1211) doesn't support measurement |
| 2751 |
# mode selection |
| 2752 |
if self.argyll_version >= [1, 5, 0]: |
| 2753 |
measurement_mode_map = instrument_features.get( |
| 2754 |
"measurement_mode_map", {} |
| 2755 |
) |
| 2756 |
measurement_mode = measurement_mode_map.get( |
| 2757 |
measurement_mode[0], measurement_mode |
| 2758 |
) |
| 2759 |
args.append("-y" + measurement_mode[0]) |
| 2760 |
if ( |
| 2761 |
getcfg("measurement_mode.projector") |
| 2762 |
and instrument_features.get("projector_mode") |
| 2763 |
and self.argyll_version >= [1, 1, 0] |
| 2764 |
and not get_arg("-p", args) |
| 2765 |
): |
| 2766 |
# Projector mode, Argyll >= 1.1.0 Beta |
| 2767 |
args.append("-p") |
| 2768 |
if instrument_features.get("adaptive_mode"): |
| 2769 |
if getcfg("measurement_mode.adaptive"): |
| 2770 |
if ( |
| 2771 |
( |
| 2772 |
self.argyll_version[0:3] > [1, 1, 0] |
| 2773 |
or ( |
| 2774 |
self.argyll_version[0:3] == [1, 1, 0] |
| 2775 |
and "Beta" not in self.argyll_version_string |
| 2776 |
and "RC1" not in self.argyll_version_string |
| 2777 |
and "RC2" not in self.argyll_version_string |
| 2778 |
) |
| 2779 |
) |
| 2780 |
and self.argyll_version[0:3] < [1, 5, 0] |
| 2781 |
and not get_arg("-V", args, True) |
| 2782 |
): |
| 2783 |
# Adaptive measurement mode, Argyll >= 1.1.0 RC3 |
| 2784 |
args.append("-V") |
| 2785 |
elif self.argyll_version[0:3] >= [1, 5, 0]: |
| 2786 |
# Disable adaptive measurement mode |
| 2787 |
args.append("-YA") |
| 2788 |
if ( |
| 2789 |
instrument_name in ("Spyder4", "Spyder5") |
| 2790 |
and self.argyll_version == [1, 7, 0] |
| 2791 |
and measurement_mode in ("f", "e") |
| 2792 |
and not get_arg("-YR:", args) |
| 2793 |
): |
| 2794 |
# Prevent 'Warning - Spyder: measuring refresh rate failed' |
| 2795 |
args.append("-YR:60") |
| 2796 |
non_argyll_prisma = ( |
| 2797 |
config.get_display_name() == "Prisma" |
| 2798 |
and not DEFAULTS["patterngenerator.prisma.argyll"] |
| 2799 |
) |
| 2800 |
if display and not (get_arg("-dweb", args) or get_arg("-dmadvr", args)): |
| 2801 |
if (self.argyll_version <= [1, 0, 4] and not get_arg("-p", args)) or ( |
| 2802 |
(self.argyll_version > [1, 0, 4] and not get_arg("-P", args)) |
| 2803 |
and f"-d{self.argyll_virtual_display}" not in args |
| 2804 |
): |
| 2805 |
if ( |
| 2806 |
config.get_display_name() == "Resolve" or non_argyll_prisma |
| 2807 |
) and not ignore_display_name: |
| 2808 |
# Move Argyll test window to lower right corner and make it |
| 2809 |
# very small |
| 2810 |
dimensions_measureframe = "1,1,0.01" |
| 2811 |
else: |
| 2812 |
if os.getenv("XDG_SESSION_TYPE") == "wayland": |
| 2813 |
# The following is a workaround for Wayland not exposing the |
| 2814 |
# absolute screen positions of a window. |
| 2815 |
dimensions_measureframe = "0.5,0.5,1.5" |
| 2816 |
else: |
| 2817 |
dimensions_measureframe = getcfg("dimensions.measureframe") |
| 2818 |
if get_arg("-dcc", args): |
| 2819 |
# Rescale for Chromecast default patch size of 10% |
| 2820 |
dimensions_measureframe = config.get_measureframe_dimensions( |
| 2821 |
dimensions_measureframe, 10 |
| 2822 |
) |
| 2823 |
args.append(f"-P{dimensions_measureframe}") |
| 2824 |
farg = get_arg("-F", args, True) |
| 2825 |
if ( |
| 2826 |
config.get_display_name() == "Resolve" or non_argyll_prisma |
| 2827 |
) and not ignore_display_name: |
| 2828 |
if farg: |
| 2829 |
# Remove -F (darken background) as we relay colors to |
| 2830 |
# pattern generator |
| 2831 |
args = args[: farg[0]] + args[farg[0] + 1 :] |
| 2832 |
elif getcfg("measure.darken_background") and not farg: |
| 2833 |
args.append("-F") |
| 2834 |
if ( |
| 2835 |
getcfg("measurement_mode.highres") |
| 2836 |
and instrument_features.get("highres_mode") |
| 2837 |
and not get_arg("-H", args, True) |
| 2838 |
): |
| 2839 |
args.append("-H") |
| 2840 |
if ( |
| 2841 |
allow_nondefault_observer |
| 2842 |
and self.instrument_can_use_nondefault_observer() |
| 2843 |
and getcfg("observer") != DEFAULTS["observer"] |
| 2844 |
and not get_arg("-Q", args) |
| 2845 |
): |
| 2846 |
args.append("-Q" + getcfg("observer")) |
| 2847 |
if ( |
| 2848 |
not ambient |
| 2849 |
and self.instrument_can_use_ccxx() |
| 2850 |
and not is_ccxx_testchart() |
| 2851 |
and not get_arg("-X", args) |
| 2852 |
): |
| 2853 |
# Use colorimeter correction? |
| 2854 |
ccmx = getcfg("colorimeter_correction_matrix_file").split(":", 1) |
| 2855 |
ccmx = ccmx[1] if len(ccmx) > 1 and ccmx[1] else None |
| 2856 |
if ccmx and ( |
| 2857 |
not ccmx.lower().endswith(".ccss") or self.instrument_supports_ccss() |
| 2858 |
): |
| 2859 |
result = check_file_isfile(ccmx) |
| 2860 |
if isinstance(result, Exception): |
| 2861 |
return result |
| 2862 |
try: |
| 2863 |
cgats = CGATS(ccmx) |
| 2864 |
except (OSError, CGATSError) as exception: |
| 2865 |
return exception |
| 2866 |
else: |
| 2867 |
ccxx_instrument_from_cgats = cgats.queryv1("INSTRUMENT") or b"" |
| 2868 |
ccxx_instrument = get_canonical_instrument_name( |
| 2869 |
ccxx_instrument_from_cgats, |
| 2870 |
{ |
| 2871 |
"DTP94-LCD mode": "DTP94", |
| 2872 |
"eye-one display": "i1 Display", |
| 2873 |
"Spyder 2 LCD": "Spyder2", |
| 2874 |
"Spyder 3": "Spyder3", |
| 2875 |
}, |
| 2876 |
) |
| 2877 |
if isinstance(ccxx_instrument, bytes): |
| 2878 |
ccxx_instrument = ccxx_instrument.decode("utf-8") |
| 2879 |
if ( |
| 2880 |
ccxx_instrument |
| 2881 |
and instrument_name.lower().replace(" ", "") |
| 2882 |
in ccxx_instrument.lower().replace(" ", "") |
| 2883 |
) or ccmx.lower().endswith(".ccss"): |
| 2884 |
tempdir = self.create_tempdir() |
| 2885 |
if isinstance(tempdir, Exception): |
| 2886 |
return tempdir |
| 2887 |
ccmxcopy = os.path.join(tempdir, os.path.basename(ccmx)) |
| 2888 |
if not os.path.isfile(ccmxcopy): |
| 2889 |
if 0 in cgats and cgats[0].type.strip() == b"CCMX": |
| 2890 |
# Add display base ID if missing |
| 2891 |
cbid_added = self.check_add_display_type_base_id(cgats) |
| 2892 |
else: |
| 2893 |
cbid_added = False |
| 2894 |
try: |
| 2895 |
# Copy ccmx to profile dir |
| 2896 |
if cbid_added: |
| 2897 |
# Write updated CCMX |
| 2898 |
cgats.write(ccmxcopy) |
| 2899 |
else: |
| 2900 |
# Copy original |
| 2901 |
shutil.copyfile(ccmx, ccmxcopy) |
| 2902 |
except Exception as exception: |
| 2903 |
return Error( |
| 2904 |
lang.getstr("error.copy_failed", (ccmx, ccmxcopy)) |
| 2905 |
+ "\n\n" |
| 2906 |
+ str(exception) |
| 2907 |
) |
| 2908 |
result = check_file_isfile(ccmxcopy) |
| 2909 |
if isinstance(result, Exception): |
| 2910 |
return result |
| 2911 |
args.append("-X") |
| 2912 |
args.append(os.path.basename(ccmxcopy)) |
| 2913 |
if ( |
| 2914 |
display |
| 2915 |
and ( |
| 2916 |
getcfg("drift_compensation.blacklevel") |
| 2917 |
or getcfg("drift_compensation.whitelevel") |
| 2918 |
) |
| 2919 |
and self.argyll_version >= [1, 3, 0] |
| 2920 |
and not get_arg("-I", args) |
| 2921 |
): |
| 2922 |
args.append("-I") |
| 2923 |
if getcfg("drift_compensation.blacklevel"): |
| 2924 |
args[-1] += "b" |
| 2925 |
if getcfg("drift_compensation.whitelevel"): |
| 2926 |
args[-1] += "w" |
| 2927 |
# TTBD/FIXME: Skipping of sensor calibration can't be done in |
| 2928 |
# emissive mode (see Argyll source spectro/ss.c, around line 40) |
| 2929 |
# (is this still the case though?) |
| 2930 |
# Note we implicitly skip sensor calibration if already done during |
| 2931 |
# output levels detection or if using spotread, but only for colorimeters |
| 2932 |
if ( |
| 2933 |
( |
| 2934 |
getcfg("allow_skip_sensor_cal") |
| 2935 |
or ( |
| 2936 |
not instrument_features.get("spectral") |
| 2937 |
and ( |
| 2938 |
self._detected_output_levels |
| 2939 |
or (self.dispread_after_dispcal and self.resume) |
| 2940 |
or cmd == get_argyll_util("spotread") |
| 2941 |
) |
| 2942 |
and not self._detecting_video_levels |
| 2943 |
) |
| 2944 |
) |
| 2945 |
and instrument_features.get("skip_sensor_cal") |
| 2946 |
and self.argyll_version >= [1, 1, 0] |
| 2947 |
and not get_arg("-N", args, True) |
| 2948 |
and not self.spotread_just_do_instrument_calibration |
| 2949 |
): |
| 2950 |
args.append("-N") |
| 2951 |
return True |
| 2952 |
|
| 2953 |
def add_video_levels_arg(self, args): |
| 2954 |
"""Add -E option to args if video levels are used. |
| 2955 |
|
| 2956 |
Args: |
| 2957 |
args (list): The list of arguments to which the -E option will be |
| 2958 |
added. |
| 2959 |
""" |
| 2960 |
if ( |
| 2961 |
config.get_display_name() not in ("madVR", "Resolve", "Prisma") |
| 2962 |
and getcfg("patterngenerator.use_video_levels") |
| 2963 |
and self.argyll_version >= [1, 6] |
| 2964 |
and self.get_display() != self.argyll_virtual_display |
| 2965 |
): |
| 2966 |
# For madVR and dummy display, -E is invalid |
| 2967 |
args.append("-E") |
| 2968 |
|
| 2969 |
def authenticate(self, cmd, title=APPNAME, parent=None): |
| 2970 |
"""Athenticate (using sudo) for a given command. |
| 2971 |
|
| 2972 |
The return value will either be True (authentication successful and |
| 2973 |
command allowed), False (in case of the user cancelling the password |
| 2974 |
dialog), None (Windows or running as root) or an error. |
| 2975 |
|
| 2976 |
Args: |
| 2977 |
cmd (str): The command to authenticate for. |
| 2978 |
title (str): The title of the authentication dialog. |
| 2979 |
parent (wx.Window, optional): The parent window for the dialog. |
| 2980 |
|
| 2981 |
Returns: |
| 2982 |
bool or None or Error: True if authentication was successful and |
| 2983 |
the command is allowed, False if the user cancelled the dialog, |
| 2984 |
None if running on Windows or as root, or an Error if the |
| 2985 |
command is not allowed or an error occurred during |
| 2986 |
authentication. |
| 2987 |
""" |
| 2988 |
if sys.platform == "win32" or os.geteuid() == 0: |
| 2989 |
return None |
| 2990 |
self.auth_timestamp = 0 |
| 2991 |
ocmd = cmd |
| 2992 |
if cmd and not os.path.isabs(cmd): |
| 2993 |
cmd = get_argyll_util(ocmd) |
| 2994 |
if not cmd: |
| 2995 |
cmd = which(ocmd) |
| 2996 |
if not cmd or not os.path.isfile(cmd): |
| 2997 |
return Error(lang.getstr("file.missing", ocmd)) |
| 2998 |
_disabler = BetterWindowDisabler() |
| 2999 |
result = True |
| 3000 |
if not self.sudo: |
| 3001 |
self.sudo = Sudo() |
| 3002 |
if not self.sudo: |
| 3003 |
result = Error(lang.getstr("file.missing", "sudo")) |
| 3004 |
if result is True: |
| 3005 |
pwd = self.pwd |
| 3006 |
args = [cmd, "-?"] |
| 3007 |
if not pwd or not self.sudo.is_allowed(args, pwd): |
| 3008 |
# If no password was previously available, or if the requested |
| 3009 |
# command cannot be run via sudo regardless of password (we check |
| 3010 |
# this with sudo -l <command>), we ask for a password. |
| 3011 |
print(lang.getstr("auth")) |
| 3012 |
progress_dlg = self._progress_wnd or getattr( |
| 3013 |
wx.GetApp(), "progress_dlg", None |
| 3014 |
) |
| 3015 |
if parent is None: |
| 3016 |
if progress_dlg and progress_dlg.IsShownOnScreen(): |
| 3017 |
parent = progress_dlg |
| 3018 |
else: |
| 3019 |
parent = self.owner |
| 3020 |
result, pwd = self.sudo.authenticate(args, title, parent) |
| 3021 |
if result: |
| 3022 |
self.pwd = pwd |
| 3023 |
result = True |
| 3024 |
elif result is False: |
| 3025 |
print(lang.getstr("aborted")) |
| 3026 |
else: |
| 3027 |
result = Error(result) |
| 3028 |
if result is True: |
| 3029 |
self.auth_timestamp = time() |
| 3030 |
del _disabler |
| 3031 |
return result |
| 3032 |
|
| 3033 |
def blend_profile_blackpoint( |
| 3034 |
self, |
| 3035 |
profile1, |
| 3036 |
profile2, |
| 3037 |
XYZbp=None, |
| 3038 |
outoffset=0.0, |
| 3039 |
gamma=2.4, |
| 3040 |
gamma_type="B", |
| 3041 |
size=None, |
| 3042 |
apply_trc=True, |
| 3043 |
white_cdm2=100, |
| 3044 |
minmll=0, |
| 3045 |
maxmll=10000, |
| 3046 |
use_alternate_master_white_clip=True, |
| 3047 |
ambient_cdm2=5, |
| 3048 |
content_rgb_space="DCI P3", |
| 3049 |
hdr_chroma_compression=False, |
| 3050 |
hdr_sat=0.5, |
| 3051 |
hdr_hue=0.5, |
| 3052 |
hdr_target_profile=None, |
| 3053 |
) -> None: |
| 3054 |
"""Apply BT.1886-like tone response to profile1 using profile2 blackpoint. |
| 3055 |
|
| 3056 |
`profile1` has to be a matrix profile. The function modifies `profile1` |
| 3057 |
in place. |
| 3058 |
|
| 3059 |
Args: |
| 3060 |
profile1 (Profile): The profile to apply the blackpoint to. |
| 3061 |
profile2 (Profile): The profile to get the blackpoint from. |
| 3062 |
XYZbp (tuple, optional): The blackpoint in XYZ coordinates. If not |
| 3063 |
provided, it will be read from profile2. |
| 3064 |
outoffset (float, optional): The output offset to apply. Defaults to 0.0. |
| 3065 |
gamma (float or str, optional): The gamma value or type to apply. |
| 3066 |
Defaults to 2.4. |
| 3067 |
gamma_type (str, optional): The gamma type to apply. Defaults to "B". |
| 3068 |
size (tuple, optional): The size of the output profile. Defaults to None. |
| 3069 |
apply_trc (bool, optional): Whether to apply the TRC. Defaults to True. |
| 3070 |
white_cdm2 (float, optional): The white luminance in cd/m². |
| 3071 |
Defaults to 100. |
| 3072 |
minmll (float, optional): The minimum mastering display luminance |
| 3073 |
level in cd/m². Defaults to 0. |
| 3074 |
maxmll (float, optional): The maximum mastering display luminance |
| 3075 |
level in cd/m². Defaults to 10000. |
| 3076 |
use_alternate_master_white_clip (bool, optional): Whether to use |
| 3077 |
the alternate master white clip. Defaults to True. |
| 3078 |
ambient_cdm2 (float, optional): The ambient luminance in cd/m². |
| 3079 |
Defaults to 5. |
| 3080 |
content_rgb_space (str, optional): The RGB space of the content. |
| 3081 |
Defaults to "DCI P3". |
| 3082 |
hdr_chroma_compression (bool, optional): Whether to apply HDR chroma |
| 3083 |
compression. Defaults to False. |
| 3084 |
hdr_sat (float, optional): The saturation for HDR chroma compression. |
| 3085 |
Defaults to 0.5. |
| 3086 |
hdr_hue (float, optional): The hue for HDR chroma compression. |
| 3087 |
Defaults to 0.5. |
| 3088 |
hdr_target_profile (Profile, optional): The target profile for HDR |
| 3089 |
chroma compression. Defaults to None. |
| 3090 |
""" |
| 3091 |
odata = self.xicclu(profile2, (0, 0, 0), pcs="x") |
| 3092 |
if len(odata) != 1 or len(odata[0]) != 3: |
| 3093 |
raise ValueError(f"Blackpoint is invalid: {odata}") |
| 3094 |
oXYZbp = odata[0] |
| 3095 |
if not XYZbp: |
| 3096 |
XYZbp = oXYZbp |
| 3097 |
smpte2084 = gamma in ("smpte2084.hardclip", "smpte2084.rolloffclip") |
| 3098 |
hlg = gamma == "hlg" |
| 3099 |
hdr = smpte2084 or hlg |
| 3100 |
lumi = profile2.tags.get("lumi", XYZType()) |
| 3101 |
if not lumi.Y: |
| 3102 |
lumi.Y = 100.0 |
| 3103 |
profile_black_cdm2 = XYZbp[1] * lumi.Y |
| 3104 |
if smpte2084: |
| 3105 |
# SMPTE ST.2084 (PQ) |
| 3106 |
if gamma != "smpte2084.rolloffclip": |
| 3107 |
maxmll = white_cdm2 |
| 3108 |
self.log( |
| 3109 |
os.path.basename(profile1.filename) |
| 3110 |
+ " → " |
| 3111 |
+ lang.getstr("trc." + gamma) |
| 3112 |
+ ( |
| 3113 |
" {:0.0f} cd/m² (mastering {}-{:0.0f} cd/m²)".format( |
| 3114 |
white_cdm2, stripzeros(f"{minmll:.4f}"), maxmll |
| 3115 |
) |
| 3116 |
) |
| 3117 |
) |
| 3118 |
elif hlg: |
| 3119 |
# Hybrid Log-Gamma (HLG) |
| 3120 |
outoffset = 1.0 |
| 3121 |
self.log( |
| 3122 |
os.path.basename(profile1.filename) |
| 3123 |
+ " → " |
| 3124 |
+ lang.getstr("trc." + gamma) |
| 3125 |
+ ( |
| 3126 |
" {:0.0f} cd/m² (ambient {} cd/m²)".format( |
| 3127 |
lumi.Y, stripzeros(f"{ambient_cdm2:.2f}") |
| 3128 |
) |
| 3129 |
) |
| 3130 |
) |
| 3131 |
elif apply_trc: |
| 3132 |
self.log( |
| 3133 |
"Applying BT.1886-like TRC to " + os.path.basename(profile1.filename) |
| 3134 |
) |
| 3135 |
else: |
| 3136 |
self.log( |
| 3137 |
"Applying BT.1886-like black offset to " |
| 3138 |
+ os.path.basename(profile1.filename) |
| 3139 |
) |
| 3140 |
self.log( |
| 3141 |
"Black XYZ (normalized 0..100) = {:.6f} {:.6f} {:.6f}".format( |
| 3142 |
*[v * 100 for v in XYZbp] |
| 3143 |
) |
| 3144 |
) |
| 3145 |
self.log( |
| 3146 |
"Black Lab = {:.6f} {:.6f} {:.6f}".format( |
| 3147 |
*colormath.XYZ2Lab(*[v * 100 for v in XYZbp]) |
| 3148 |
) |
| 3149 |
) |
| 3150 |
self.log(f"Output offset = {outoffset:.2%}") |
| 3151 |
if hdr: |
| 3152 |
odesc = profile1.getDescription() |
| 3153 |
desc = re.sub( |
| 3154 |
r"\s*(?:color profile|primaries with \S+ transfer function)$", "", odesc |
| 3155 |
) |
| 3156 |
if smpte2084: |
| 3157 |
# SMPTE ST.2084 (PQ) |
| 3158 |
black_cdm2 = profile_black_cdm2 * (1 - outoffset) |
| 3159 |
if XYZbp[1]: |
| 3160 |
XYZbp_cdm2 = [v / XYZbp[1] * black_cdm2 for v in XYZbp] |
| 3161 |
else: |
| 3162 |
XYZbp_cdm2 = [0, 0, 0] |
| 3163 |
profile1.set_smpte2084_trc( |
| 3164 |
XYZbp_cdm2, |
| 3165 |
white_cdm2, |
| 3166 |
minmll, |
| 3167 |
maxmll, |
| 3168 |
use_alternate_master_white_clip, |
| 3169 |
rolloff=True, |
| 3170 |
blend_blackpoint=False, |
| 3171 |
) |
| 3172 |
desc += ( |
| 3173 |
" " |
| 3174 |
+ lang.getstr("trc." + gamma) |
| 3175 |
+ ( |
| 3176 |
" {}-{:0.0f} cd/m² (mastering {}-{:0.0f} cd/m²)".format( |
| 3177 |
stripzeros(f"{profile_black_cdm2:.4f}"), |
| 3178 |
white_cdm2, |
| 3179 |
stripzeros(f"{minmll:.4f}"), |
| 3180 |
maxmll, |
| 3181 |
) |
| 3182 |
) |
| 3183 |
) |
| 3184 |
elif hlg: |
| 3185 |
# Hybrid Log-Gamma (HLG) |
| 3186 |
black_cdm2 = 0 # Black offset will be applied separate for HLG |
| 3187 |
white_cdm2 = lumi.Y |
| 3188 |
profile1.set_hlg_trc((0, 0, 0), white_cdm2, 1.2, ambient_cdm2) |
| 3189 |
desc += ( |
| 3190 |
" " |
| 3191 |
+ lang.getstr("trc." + gamma) |
| 3192 |
+ ( |
| 3193 |
" {}-{:0.0f} cd/m² (ambient {} cd/m²)".format( |
| 3194 |
stripzeros(f"{profile_black_cdm2:.4f}"), |
| 3195 |
white_cdm2, |
| 3196 |
stripzeros(f"{ambient_cdm2:.2f}"), |
| 3197 |
) |
| 3198 |
) |
| 3199 |
) |
| 3200 |
profile1.setDescription(desc) |
| 3201 |
if gamma == "smpte2084.rolloffclip" or hlg: |
| 3202 |
rgb_space = profile1.get_rgb_space() |
| 3203 |
if not rgb_space: |
| 3204 |
raise Error( |
| 3205 |
odesc |
| 3206 |
+ ": " |
| 3207 |
+ lang.getstr( |
| 3208 |
"profile.unsupported", |
| 3209 |
( |
| 3210 |
lang.getstr("unknown"), |
| 3211 |
profile1.colorSpace.decode("utf-8"), |
| 3212 |
), |
| 3213 |
) |
| 3214 |
) |
| 3215 |
rgb_space[0] = 1.0 # Set gamma to 1.0 (not actually used) |
| 3216 |
rgb_space = colormath.get_rgb_space(rgb_space) |
| 3217 |
self.recent.write(desc + "\n") |
| 3218 |
linebuffered_logfiles = [] |
| 3219 |
if sys.stdout and hasattr(sys.stdout, "isatty") and sys.stdout.isatty(): |
| 3220 |
linebuffered_logfiles.append(print) |
| 3221 |
else: |
| 3222 |
linebuffered_logfiles.append(LOG) |
| 3223 |
if self.sessionlogfile: |
| 3224 |
linebuffered_logfiles.append(self.sessionlogfile) |
| 3225 |
logfiles = Files( |
| 3226 |
[ |
| 3227 |
LineBufferedStream( |
| 3228 |
FilteredStream( |
| 3229 |
Files(linebuffered_logfiles), |
| 3230 |
ENC, |
| 3231 |
discard="", |
| 3232 |
linesep_in="\n", |
| 3233 |
triggers=[], |
| 3234 |
) |
| 3235 |
), |
| 3236 |
self.recent, |
| 3237 |
self.lastmsg, |
| 3238 |
] |
| 3239 |
) |
| 3240 |
if hdr_chroma_compression: |
| 3241 |
xf = Xicclu( |
| 3242 |
hdr_target_profile, "r", direction="f", pcs="x", worker=self |
| 3243 |
) |
| 3244 |
xb = XiccluMP( |
| 3245 |
hdr_target_profile, |
| 3246 |
"r", |
| 3247 |
direction="if", |
| 3248 |
pcs="x", |
| 3249 |
use_cam_clipping=True, |
| 3250 |
worker=self, |
| 3251 |
logfile=logfiles, |
| 3252 |
) |
| 3253 |
if content_rgb_space: |
| 3254 |
content_rgb_space = colormath.get_rgb_space(content_rgb_space) |
| 3255 |
for i, color in enumerate(("white", "red", "green", "blue")): |
| 3256 |
if i == 0: |
| 3257 |
xyY = colormath.XYZ2xyY(*content_rgb_space[1]) |
| 3258 |
else: |
| 3259 |
xyY = content_rgb_space[2:][i - 1] |
| 3260 |
for j, coord in enumerate("xy"): |
| 3261 |
v = xyY[j] |
| 3262 |
self.log( |
| 3263 |
"{} {} {} {:6.4f}".format( |
| 3264 |
lang.getstr("3dlut.content.colorspace"), |
| 3265 |
lang.getstr(color), |
| 3266 |
coord, |
| 3267 |
v, |
| 3268 |
) |
| 3269 |
) |
| 3270 |
else: |
| 3271 |
xf = None |
| 3272 |
xb = None |
| 3273 |
if smpte2084: |
| 3274 |
hdr_format = "PQ" |
| 3275 |
elif hlg: |
| 3276 |
hdr_format = "HLG" |
| 3277 |
cat = profile1.guess_cat() or "Bradford" |
| 3278 |
self.log("Using chromatic adaptation transform matrix:", cat) |
| 3279 |
profile = create_synthetic_hdr_clut_profile( |
| 3280 |
hdr_format, |
| 3281 |
rgb_space, |
| 3282 |
desc, |
| 3283 |
black_cdm2, |
| 3284 |
white_cdm2, |
| 3285 |
minmll, # Not used for HLG |
| 3286 |
maxmll, # Not used for HLG |
| 3287 |
use_alternate_master_white_clip, # Not used for HLG |
| 3288 |
system_gamma=1.2, # Not used for PQ |
| 3289 |
ambient_cdm2=ambient_cdm2, # Not used for PQ |
| 3290 |
maxsignal=1.0, # Not used for PQ |
| 3291 |
content_rgb_space=content_rgb_space, |
| 3292 |
sat=hdr_sat, |
| 3293 |
hue=hdr_hue, |
| 3294 |
forward_xicclu=xf, |
| 3295 |
backward_xicclu=xb, |
| 3296 |
worker=self, |
| 3297 |
logfile=logfiles, |
| 3298 |
cat=cat, |
| 3299 |
) |
| 3300 |
profile1.tags.A2B0 = profile.tags.A2B0 |
| 3301 |
profile1.tags.DBG0 = profile.tags.DBG0 |
| 3302 |
profile1.tags.DBG1 = profile.tags.DBG1 |
| 3303 |
profile1.tags.DBG2 = profile.tags.DBG2 |
| 3304 |
profile1.tags.kTRC = profile.tags.kTRC |
| 3305 |
elif apply_trc: |
| 3306 |
# Apply BT.1886-like TRC |
| 3307 |
if gamma_type in ("b", "g"): |
| 3308 |
# Get technical gamma needed to achieve effective gamma |
| 3309 |
self.log(f"Effective gamma = {gamma:.2f}") |
| 3310 |
tgamma = colormath.xicc_tech_gamma(gamma, XYZbp[1], outoffset) |
| 3311 |
else: |
| 3312 |
tgamma = gamma |
| 3313 |
self.log(f"Technical gamma = {tgamma:.2f}") |
| 3314 |
profile1.set_bt1886_trc(XYZbp, outoffset, gamma, gamma_type, size) |
| 3315 |
if not apply_trc or hdr or XYZbp is not oXYZbp: |
| 3316 |
# Apply black offset |
| 3317 |
logfiles = self.get_logfiles() |
| 3318 |
logfiles.write( |
| 3319 |
"Applying black offset (normalized 0..100) " |
| 3320 |
"{:.6f} {:.6f} {:.6f}...\n".format(*[v * 100 for v in oXYZbp]) |
| 3321 |
) |
| 3322 |
profile1.apply_black_offset( |
| 3323 |
oXYZbp, |
| 3324 |
logfile=logfiles, |
| 3325 |
thread_abort=self.thread_abort, |
| 3326 |
abortmessage=lang.getstr("aborted"), |
| 3327 |
) |
| 3328 |
|
| 3329 |
def calibrate_instrument_producer(self): |
| 3330 |
"""Calibrate the instrument using spotread. |
| 3331 |
|
| 3332 |
Returns: |
| 3333 |
str or Error: The result of the calibration command, or an error if |
| 3334 |
the command could not be executed or the instrument is not |
| 3335 |
found. |
| 3336 |
""" |
| 3337 |
cmd, args = get_argyll_util("spotread"), ["-v", "-e"] |
| 3338 |
if cmd: |
| 3339 |
self.spotread_just_do_instrument_calibration = True |
| 3340 |
result = self.add_measurement_features(args, display=False) |
| 3341 |
if isinstance(result, Exception): |
| 3342 |
self.spotread_just_do_instrument_calibration = False |
| 3343 |
return result |
| 3344 |
result = self.exec_cmd(cmd, args, skip_scripts=True) |
| 3345 |
self.spotread_just_do_instrument_calibration = False |
| 3346 |
return result |
| 3347 |
return Error(lang.getstr("argyll.util.not_found", "spotread")) |
| 3348 |
|
| 3349 |
def instrument_can_use_ccxx( |
| 3350 |
self, check_measurement_mode=True, instrument_name=None |
| 3351 |
): |
| 3352 |
"""Check if the instrument can use CCMX/CCSS in the current measurement mode. |
| 3353 |
|
| 3354 |
Args: |
| 3355 |
check_measurement_mode (bool): If True, check the current measurement mode. |
| 3356 |
instrument_name (str, optional): The name of the instrument to check. |
| 3357 |
|
| 3358 |
Returns: |
| 3359 |
bool: True if the instrument can use a CCMX or CCSS correction, |
| 3360 |
False otherwise. |
| 3361 |
""" |
| 3362 |
# Special cases: |
| 3363 |
# Spectrometer (not needed), |
| 3364 |
# ColorHug (only sensible in factory or raw measurement mode), |
| 3365 |
# ColorMunki Smile (only generic LCD CCFL measurement mode), |
| 3366 |
# Colorimétre HCFR (only raw measurement mode), |
| 3367 |
# DTP94 (only LCD, refresh and generic measurement modes) |
| 3368 |
# Spyder4/5 (only generic LCD and refresh measurement modes) |
| 3369 |
# K-10 (only factory measurement mode) |
| 3370 |
|
| 3371 |
# IMPORTANT: Make changes aswell in the following locations: |
| 3372 |
# - DisplayCAL.MainFrame.create_colorimeter_correction_handler |
| 3373 |
# - DisplayCAL.MainFrame.get_ccxx_measurement_modes |
| 3374 |
# - DisplayCAL.MainFrame.set_ccxx_measurement_mode |
| 3375 |
# - DisplayCAL.MainFrame.update_colorimeter_correction_matrix_ctrl_items |
| 3376 |
# - worker.Worker.check_add_display_type_base_id |
| 3377 |
if not instrument_name: |
| 3378 |
instrument_name = self.get_instrument_name() |
| 3379 |
return ( |
| 3380 |
self.argyll_version >= [1, 3, 0] |
| 3381 |
and bool(instrument_name) |
| 3382 |
and not self.get_instrument_features(instrument_name).get("spectral") |
| 3383 |
and ( |
| 3384 |
not check_measurement_mode |
| 3385 |
or getcfg("measurement_mode") == "auto" |
| 3386 |
or ( |
| 3387 |
( |
| 3388 |
instrument_name not in ("ColorHug", "ColorHug2") |
| 3389 |
or getcfg("measurement_mode") in ("F", "R") |
| 3390 |
) |
| 3391 |
and ( |
| 3392 |
instrument_name != "ColorMunki Smile" |
| 3393 |
or getcfg("measurement_mode") == "f" |
| 3394 |
) |
| 3395 |
and ( |
| 3396 |
instrument_name != "Colorimtre HCFR" |
| 3397 |
or getcfg("measurement_mode") == "R" # Missing é is NOT a typo |
| 3398 |
) |
| 3399 |
and ( |
| 3400 |
instrument_name != "DTP94" |
| 3401 |
or getcfg("measurement_mode") in ("l", "c", "g") |
| 3402 |
) |
| 3403 |
and ( |
| 3404 |
instrument_name not in ("Spyder4", "Spyder5") |
| 3405 |
or getcfg("measurement_mode") in ("l", "c") |
| 3406 |
) |
| 3407 |
and ( |
| 3408 |
instrument_name not in ("SpyderX", "SpyderX2", "Spyder 2024") |
| 3409 |
or getcfg("measurement_mode") == "l" |
| 3410 |
) |
| 3411 |
and (instrument_name != "K-10" or getcfg("measurement_mode") == "F") |
| 3412 |
) |
| 3413 |
) |
| 3414 |
) |
| 3415 |
|
| 3416 |
def instrument_can_use_nondefault_observer(self, instrument_name=None): |
| 3417 |
"""Return boolean whether the instrument can use a non-default observer. |
| 3418 |
|
| 3419 |
Args: |
| 3420 |
instrument_name (str, optional): The name of the instrument to check. |
| 3421 |
|
| 3422 |
Returns: |
| 3423 |
bool: True if the instrument can use a non-default observer, False |
| 3424 |
otherwise. |
| 3425 |
""" |
| 3426 |
if not instrument_name: |
| 3427 |
instrument_name = self.get_instrument_name() |
| 3428 |
return bool( |
| 3429 |
self.get_instrument_features(instrument_name).get("spectral") |
| 3430 |
or self.instrument_supports_ccss(instrument_name) |
| 3431 |
) |
| 3432 |
|
| 3433 |
@property |
| 3434 |
def progress_wnd(self): |
| 3435 |
"""Return the main progress window. |
| 3436 |
|
| 3437 |
Returns: |
| 3438 |
wx.Dialog: The main progress dialog window, or None if it is not |
| 3439 |
set. |
| 3440 |
""" |
| 3441 |
if not self._progress_wnd and ( |
| 3442 |
getattr(self, "progress_start_timer", None) |
| 3443 |
and self.progress_start_timer.IsRunning() |
| 3444 |
): |
| 3445 |
if current_thread() != main_thread(): |
| 3446 |
raise RuntimeError("GUI access in non-main thread!") |
| 3447 |
# Instantiate the progress dialog instantly on access |
| 3448 |
self.progress_start_timer.Notify() |
| 3449 |
self.progress_start_timer.Stop() |
| 3450 |
return self._progress_wnd |
| 3451 |
|
| 3452 |
@progress_wnd.setter |
| 3453 |
def progress_wnd(self, progress_wnd): |
| 3454 |
"""Set the main progress window. |
| 3455 |
|
| 3456 |
Args: |
| 3457 |
progress_wnd (wx.Dialog): The progress dialog window to set. |
| 3458 |
""" |
| 3459 |
self._progress_wnd = progress_wnd |
| 3460 |
|
| 3461 |
@property |
| 3462 |
def progress_wnds(self): |
| 3463 |
"""Return a list of all progress windows. |
| 3464 |
|
| 3465 |
This includes the main progress dialog and any additional dialogs |
| 3466 |
created for subprocesses or other tasks. If a terminal window is |
| 3467 |
present, it is also included. |
| 3468 |
|
| 3469 |
Returns: |
| 3470 |
list: A list of progress dialog windows. |
| 3471 |
""" |
| 3472 |
progress_wnds = list(self._progress_dlgs.values()) |
| 3473 |
if hasattr(self, "terminal"): |
| 3474 |
progress_wnds.append(self.terminal) |
| 3475 |
return progress_wnds |
| 3476 |
|
| 3477 |
@property |
| 3478 |
def pwd(self): |
| 3479 |
"""Return the password for sudo authentication. |
| 3480 |
|
| 3481 |
Returns: |
| 3482 |
str: The decoded password string. |
| 3483 |
""" |
| 3484 |
return codecs.decode( |
| 3485 |
self._pwdstr[10:] |
| 3486 |
.ljust(int(math.ceil(len(self._pwdstr[10:]) / 4.0) * 4), "=") |
| 3487 |
.encode(), |
| 3488 |
"base64", |
| 3489 |
).decode("utf-8") |
| 3490 |
|
| 3491 |
@pwd.setter |
| 3492 |
def pwd(self, pwd): |
| 3493 |
"""Set the password for sudo authentication. |
| 3494 |
|
| 3495 |
Args: |
| 3496 |
pwd (str): The password to set. |
| 3497 |
""" |
| 3498 |
encoded_user_name = codecs.encode( |
| 3499 |
md5(getpass.getuser().encode()).hexdigest().encode(), # noqa: S324 |
| 3500 |
"base64", |
| 3501 |
)[:5].decode("utf-8") |
| 3502 |
encoded_pwd = ( |
| 3503 |
codecs.encode(pwd.encode(), "base64").decode("utf-8").rstrip("=\n") |
| 3504 |
) |
| 3505 |
self._pwdstr = f"/tmp/{encoded_user_name}{encoded_pwd}" # noqa: S108 |
| 3506 |
|
| 3507 |
def check_add_display_type_base_id(self, cgats, cfgname="measurement_mode"): |
| 3508 |
"""Add DISPLAY_TYPE_BASE_ID to CCMX. |
| 3509 |
|
| 3510 |
Args: |
| 3511 |
cgats (CGATS): The CGATS object to modify. |
| 3512 |
cfgname (str): The configuration name to check for the display type. |
| 3513 |
|
| 3514 |
Returns: |
| 3515 |
bool: True if DISPLAY_TYPE_BASE_ID was added, False if it was |
| 3516 |
already present. If the DISPLAY_TYPE_BASE_ID is not present, it |
| 3517 |
will be added based on the display type from the configuration. |
| 3518 |
""" |
| 3519 |
if cgats.queryv1("DISPLAY_TYPE_BASE_ID"): |
| 3520 |
return False |
| 3521 |
# c, l (most colorimeters) |
| 3522 |
# R (ColorHug and Colorimétre HCFR) |
| 3523 |
# F (ColorHug) |
| 3524 |
# f (ColorMunki Smile) |
| 3525 |
# g (DTP94) |
| 3526 |
|
| 3527 |
# IMPORTANT: Make changes aswell in the following locations: |
| 3528 |
# - DisplayCAL.MainFrame.create_colorimeter_correction_handler |
| 3529 |
# - DisplayCAL.MainFrame.get_ccxx_measurement_modes |
| 3530 |
# - DisplayCAL.MainFrame.set_ccxx_measurement_modes |
| 3531 |
# - DisplayCAL.MainFrame.update_colorimeter_correction_matrix_ctrl_items |
| 3532 |
# - worker.Worker.instrument_can_use_ccxx |
| 3533 |
cgats[0].add_keyword( |
| 3534 |
"DISPLAY_TYPE_BASE_ID", |
| 3535 |
{"c": 2, "l": 1, "R": 2, "F": 1, "f": 1, "g": 3}.get(getcfg(cfgname), 1), |
| 3536 |
) |
| 3537 |
print(f"Added DISPLAY_TYPE_BASE_ID {cgats[0].DISPLAY_TYPE_BASE_ID!r}") |
| 3538 |
return True |
| 3539 |
|
| 3540 |
def check_display_conf_oy_compat(self, display_no): |
| 3541 |
"""Check the screen configuration for oyranos-monitor compatibility. |
| 3542 |
|
| 3543 |
oyranos-monitor works off screen coordinates, so it will not handle |
| 3544 |
overlapping screens (like separate X screens, which will usually |
| 3545 |
have the same x, y coordinates)! |
| 3546 |
So, oyranos-monitor can only be used if: |
| 3547 |
- The wx.Display count is > 1 which means NOT separate X screens |
| 3548 |
OR if we use the 1st screen |
| 3549 |
- The screens don't overlap |
| 3550 |
|
| 3551 |
""" |
| 3552 |
if wx.Display.GetCount() <= 1 and display_no != 1: |
| 3553 |
return False |
| 3554 |
oyranos = True |
| 3555 |
for display_rect_1 in self.display_rects: |
| 3556 |
for display_rect_2 in self.display_rects: |
| 3557 |
if display_rect_1 is not display_rect_2 and display_rect_1.Intersects( |
| 3558 |
display_rect_2 |
| 3559 |
): |
| 3560 |
oyranos = False |
| 3561 |
break |
| 3562 |
if not oyranos: |
| 3563 |
break |
| 3564 |
return oyranos |
| 3565 |
|
| 3566 |
def check_is_single_measurement(self, txt): |
| 3567 |
"""Check if we are doing a single measurement.""" |
| 3568 |
if ( |
| 3569 |
"ambient light measuring" in txt.lower() |
| 3570 |
or "Will use emissive mode instead" in txt |
| 3571 |
) and not getattr(self, "is_ambient_measurement", False): |
| 3572 |
self.is_ambient_measurement = True |
| 3573 |
self.is_single_measurement = True |
| 3574 |
if ( |
| 3575 |
getattr(self, "is_single_measurement", False) |
| 3576 |
and self.instrument_place_on_spot_msg |
| 3577 |
): |
| 3578 |
self.is_single_measurement = False |
| 3579 |
self.do_single_measurement() |
| 3580 |
self.is_ambient_measurement = False |
| 3581 |
|
| 3582 |
def do_single_measurement(self): |
| 3583 |
"""Perform a single measurement, e.g. ambient light measurement.""" |
| 3584 |
if getattr(self, "subprocess_abort", False) or getattr( |
| 3585 |
self, "thread_abort", False |
| 3586 |
): |
| 3587 |
# If we are aborting, ignore request |
| 3588 |
return None |
| 3589 |
self.progress_wnd.Pulse(" " * 4) |
| 3590 |
if self.is_ambient_measurement: |
| 3591 |
self.is_ambient_measurement = False |
| 3592 |
dlg = ConfirmDialog( |
| 3593 |
self.progress_wnd, |
| 3594 |
msg=lang.getstr("instrument.measure_ambient"), |
| 3595 |
ok=lang.getstr("ok"), |
| 3596 |
cancel=lang.getstr("cancel"), |
| 3597 |
bitmap=get_icon(32, "dialog-information"), |
| 3598 |
) |
| 3599 |
self.progress_wnd.dlg = dlg |
| 3600 |
dlg_result = dlg.ShowModal() |
| 3601 |
dlg.Destroy() |
| 3602 |
if self.finished: |
| 3603 |
return None |
| 3604 |
if dlg_result != wx.ID_OK: |
| 3605 |
self.abort_subprocess() |
| 3606 |
return False |
| 3607 |
if self.safe_send(" "): |
| 3608 |
self.progress_wnd.Pulse(lang.getstr("please_wait")) |
| 3609 |
return None |
| 3610 |
|
| 3611 |
def check_instrument_calibration(self, txt): |
| 3612 |
"""Check if instrument needs calibration from Argyll CMS output. |
| 3613 |
|
| 3614 |
Args: |
| 3615 |
txt (str): The output text from Argyll CMS to check for calibration |
| 3616 |
messages. |
| 3617 |
""" |
| 3618 |
if self.instrument_calibration_complete: |
| 3619 |
return |
| 3620 |
if "calibration complete" in txt.lower(): |
| 3621 |
self.log(f"{APPNAME}: Detected instrument calibration complete message") |
| 3622 |
self.instrument_calibration_complete = True |
| 3623 |
self._last_calibration_msg = None |
| 3624 |
else: |
| 3625 |
for calmsg in INST_CAL_MSGS: |
| 3626 |
if calmsg not in txt and "calibration failed" not in txt.lower(): |
| 3627 |
continue |
| 3628 |
failed = "calibration failed" in txt.lower() |
| 3629 |
if failed: |
| 3630 |
self._last_calibration_msg = None |
| 3631 |
if ( |
| 3632 |
calmsg == self._last_calibration_msg |
| 3633 |
and not failed |
| 3634 |
): |
| 3635 |
# Same calibration prompt seen again after already sending a |
| 3636 |
# keypress (e.g. ArgyllCMS 3.4.1 race condition with ColorMunki |
| 3637 |
# where the prompt echoes before the device completes its single |
| 3638 |
# calibration step). Auto-retry silently to avoid an infinite |
| 3639 |
# dialog loop. |
| 3640 |
self.log( |
| 3641 |
f"{APPNAME}: Duplicate calibration prompt detected, " |
| 3642 |
"auto-retrying without dialog" |
| 3643 |
) |
| 3644 |
self.safe_send(" ") |
| 3645 |
else: |
| 3646 |
self.log(f"{APPNAME}: Detected instrument calibration message") |
| 3647 |
self._last_calibration_msg = calmsg |
| 3648 |
self.do_instrument_calibration(failed) |
| 3649 |
break |
| 3650 |
|
| 3651 |
def check_instrument_calibration_file(self): |
| 3652 |
"""Check if the instrument calibration file is valid. |
| 3653 |
|
| 3654 |
This is done by checking the SpyderX calibration file for black |
| 3655 |
calibration offsets, which should not be higher than 15. If the offsets |
| 3656 |
are higher, we assume that the user has left the instrument on screen, |
| 3657 |
which is not allowed, and we remove the calibration file and return |
| 3658 |
False. |
| 3659 |
|
| 3660 |
If the file is not present, we return True, as this means that the |
| 3661 |
instrument calibration is not done yet, or that the user has removed |
| 3662 |
the instrument from the screen. |
| 3663 |
|
| 3664 |
If the instrument is not a SpyderX, we return True, as we don't have to |
| 3665 |
check the calibration file. |
| 3666 |
|
| 3667 |
Returns: |
| 3668 |
bool: True if the calibration file is valid or not present, |
| 3669 |
False if the calibration file is present but invalid. |
| 3670 |
""" |
| 3671 |
# XXX: Check instrument calibration for SpyderX. For some reason, |
| 3672 |
# users tend to leave the instrument on screen despite being told |
| 3673 |
# otherwise... |
| 3674 |
if not self._detected_instrument or "SpyderX" not in self._detected_instrument: |
| 3675 |
return True |
| 3676 |
if sys.platform == "win32": |
| 3677 |
cachepath = os.path.join(defaultpaths.APPDATA, "Cache") |
| 3678 |
else: |
| 3679 |
cachepath = defaultpaths.CACHE |
| 3680 |
spydx_cal_fn = os.path.join( |
| 3681 |
cachepath, |
| 3682 |
"ArgyllCMS", |
| 3683 |
f".spydX_{self._detected_instrument_serial}.cal", |
| 3684 |
) |
| 3685 |
if not os.path.isfile(spydx_cal_fn): |
| 3686 |
return True |
| 3687 |
# Argyll sensor cal file format offsets and lengths depend on |
| 3688 |
# the size of various C data types as seen by Argyll. |
| 3689 |
# We can determine the needed offset and length of the cal info |
| 3690 |
# (C 'int') by subtracting the length of the NULL-terminated |
| 3691 |
# serial string and size of time_t from the file size, then |
| 3692 |
# dividing by the number of C 'int's in the file. |
| 3693 |
# File structure for SpyderX cal: |
| 3694 |
# Argyll version (C 'int') |
| 3695 |
# Size of spydX (2x C 'int') |
| 3696 |
# NULL-terminated serial string (variable length) |
| 3697 |
# Black cal done (C 'int') |
| 3698 |
# Date & time (time_t) |
| 3699 |
# Calibration info (3x C 'int') |
| 3700 |
# Checksum (C 'int') |
| 3701 |
serial0 = self._detected_instrument_serial + "\0" |
| 3702 |
numints = 8 |
| 3703 |
spydx_cal_size = os.stat(spydx_cal_fn).st_size |
| 3704 |
spydx_cal_int_bytes = 4 # C 'int' |
| 3705 |
# time_t might be 8 or 4 bytes, 0 is sentinel |
| 3706 |
for time_t_size in (8, 4, 0): |
| 3707 |
if ( |
| 3708 |
spydx_cal_size - len(serial0) - time_t_size |
| 3709 |
) == spydx_cal_int_bytes * numints: |
| 3710 |
break |
| 3711 |
if not time_t_size: |
| 3712 |
self.log( |
| 3713 |
f"{APPNAME}: Warning - could not determine SpyderX " |
| 3714 |
"sensor cal file format" |
| 3715 |
) |
| 3716 |
self.exec_cmd_returnvalue = Error( |
| 3717 |
"Could not determine SpyderX sensor cal file format" |
| 3718 |
) |
| 3719 |
self.abort_subprocess() |
| 3720 |
return False |
| 3721 |
self.log(f"{APPNAME}: SpyderX cal time_t size =", time_t_size) |
| 3722 |
try: |
| 3723 |
with open(spydx_cal_fn, "rb") as spydx_cal: |
| 3724 |
# Seek to cal entries offset |
| 3725 |
spydx_cal.seek(spydx_cal_int_bytes * 4 + len(serial0) + time_t_size) |
| 3726 |
# Read three entries black cal |
| 3727 |
spydx_bcal = spydx_cal.read(spydx_cal_int_bytes * 3) |
| 3728 |
except OSError as exception: |
| 3729 |
self.log( |
| 3730 |
f"{APPNAME}: Warning - could not read SpyderX sensor cal:", |
| 3731 |
exception, |
| 3732 |
) |
| 3733 |
self.exec_cmd_returnvalue = Error( |
| 3734 |
f"Could not read SpyderX sensor cal: {safe_str(exception)}" |
| 3735 |
) |
| 3736 |
self.abort_subprocess() |
| 3737 |
return False |
| 3738 |
else: |
| 3739 |
if len(spydx_bcal) < spydx_cal_int_bytes * 3: |
| 3740 |
self.log( |
| 3741 |
f"{APPNAME}: Warning - SpyderX " |
| 3742 |
"sensor cal has unexpected length: " |
| 3743 |
f"{len(spydx_bcal)} != {spydx_cal_int_bytes * 3:d}" |
| 3744 |
) |
| 3745 |
self.exec_cmd_returnvalue = Error( |
| 3746 |
"SpyderX sensor cal " |
| 3747 |
"has unexpected " |
| 3748 |
f"length: {len(spydx_bcal)} != {spydx_cal_int_bytes * 3:d}" |
| 3749 |
) |
| 3750 |
self.abort_subprocess() |
| 3751 |
return False |
| 3752 |
fmt = {2: "<HHH", 4: "<III", 8: "<QQQ"}[spydx_cal_int_bytes] |
| 3753 |
spydx_bcal = struct.unpack(fmt, spydx_bcal) |
| 3754 |
self.log( |
| 3755 |
f"{APPNAME}: SpyderX sensor cal " |
| 3756 |
f"{spydx_bcal[0]:d} {spydx_bcal[1]:d} {spydx_bcal[2]:d}" |
| 3757 |
) |
| 3758 |
if max(spydx_bcal) > 15: |
| 3759 |
# Black cal offsets too high - user error? |
| 3760 |
self.exec_cmd_returnvalue = Error( |
| 3761 |
lang.getstr("error.spyderx.black_cal_offsets_too_high") |
| 3762 |
) |
| 3763 |
self.abort_subprocess() |
| 3764 |
# Nuke the cal file |
| 3765 |
try: |
| 3766 |
os.remove(spydx_cal_fn) |
| 3767 |
except OSError: |
| 3768 |
self.log( |
| 3769 |
f"{APPNAME}: Warning - Could not remove " |
| 3770 |
"SpyderX sensor cal file", |
| 3771 |
spydx_cal_fn, |
| 3772 |
) |
| 3773 |
return False |
| 3774 |
return True |
| 3775 |
|
| 3776 |
def check_instrument_place_on_screen(self, txt): |
| 3777 |
"""Check if instrument should be placed on screen. |
| 3778 |
|
| 3779 |
This is done by looking at Argyll CMS command output. |
| 3780 |
|
| 3781 |
Args: |
| 3782 |
txt (str): The output text from the Argyll CMS command. |
| 3783 |
""" |
| 3784 |
self.instrument_place_on_spot_msg = False |
| 3785 |
if "place instrument on test window" in txt.lower(): |
| 3786 |
self.instrument_place_on_screen_msg = True |
| 3787 |
elif "place instrument on spot" in txt.lower(): |
| 3788 |
self.instrument_place_on_spot_msg = True |
| 3789 |
if ( |
| 3790 |
self.instrument_place_on_screen_msg or self.instrument_place_on_spot_msg |
| 3791 |
) and not self.check_instrument_calibration_file(): |
| 3792 |
return |
| 3793 |
if ( |
| 3794 |
self.instrument_place_on_screen_msg and "key to continue" in txt.lower() |
| 3795 |
) or ( |
| 3796 |
self.instrument_calibration_complete |
| 3797 |
and self.instrument_place_on_spot_msg |
| 3798 |
and self.progress_wnd is getattr(self, "terminal", None) |
| 3799 |
): |
| 3800 |
self.log(f"{APPNAME}: Detected instrument placement (screen/spot) message") |
| 3801 |
self.instrument_place_on_screen_msg = False |
| 3802 |
if ( |
| 3803 |
self.cmdname == get_argyll_utilname("dispcal") |
| 3804 |
and sys.platform == "darwin" |
| 3805 |
): |
| 3806 |
# On the Mac dispcal's test window |
| 3807 |
# hides the cursor and steals focus |
| 3808 |
start_new_thread(mac_app_activate, (1, wx.GetApp().AppName)) |
| 3809 |
# IMPORTANT: When making changes to the instrument on screen |
| 3810 |
# detection, also apply them to appropriate part in Worker.exec_cmd |
| 3811 |
if self.instrument_calibration_complete or ( |
| 3812 |
( |
| 3813 |
config.is_untethered_display() |
| 3814 |
or getcfg("measure.darken_background") |
| 3815 |
or self.madtpg_fullscreen is False |
| 3816 |
) |
| 3817 |
and ( |
| 3818 |
not self.dispread_after_dispcal |
| 3819 |
or self.cmdname == get_argyll_utilname("dispcal") |
| 3820 |
or self._detecting_video_levels |
| 3821 |
) |
| 3822 |
and not self.instrument_on_screen |
| 3823 |
): |
| 3824 |
# Show a dialog asking user to place the instrument on the |
| 3825 |
# screen if the instrument calibration was completed, |
| 3826 |
# or if we measure a remote ("Web") display, |
| 3827 |
# or if we use a black background during measurements, |
| 3828 |
# but in case of the latter two only if dispread is not |
| 3829 |
# run directly after dispcal |
| 3830 |
self.instrument_calibration_complete = False |
| 3831 |
self.instrument_place_on_screen() |
| 3832 |
elif self.isalive(): |
| 3833 |
# Delay to work-around a problem with i1D2 and Argyll 1.7 |
| 3834 |
# to 1.8.3 under Mac OS X 10.11 El Capitan where skipping |
| 3835 |
# interactive display adjustment would botch the first |
| 3836 |
# reading (black) |
| 3837 |
wx.CallLater(1500, self.instrument_on_screen_continue) |
| 3838 |
elif self.instrument_place_on_spot_msg: |
| 3839 |
self.log(f"{APPNAME}: Assuming instrument on screen") |
| 3840 |
self.instrument_on_screen = True |
| 3841 |
|
| 3842 |
def instrument_on_screen_continue(self): |
| 3843 |
"""Continue after instrument on screen message.""" |
| 3844 |
self.log(f"{APPNAME}: Skipping place instrument on screen message...") |
| 3845 |
self.safe_send(" ") |
| 3846 |
self.pauseable_now = True |
| 3847 |
self.instrument_on_screen = True |
| 3848 |
|
| 3849 |
def check_instrument_sensor_position(self, txt): |
| 3850 |
"""Check instrument sensor position by looking at Argyll CMS command output. |
| 3851 |
|
| 3852 |
Args: |
| 3853 |
txt (str): The output text from the Argyll CMS command. |
| 3854 |
""" |
| 3855 |
if "read failed due to the sensor being in the wrong position" in txt.lower(): |
| 3856 |
self.instrument_sensor_position_msg = True |
| 3857 |
if self.instrument_sensor_position_msg and " or q to " in txt.lower(): |
| 3858 |
self.log(f"{APPNAME}: Detected read failed due to wrong sensor position") |
| 3859 |
self.instrument_sensor_position_msg = False |
| 3860 |
self.instrument_reposition_sensor() |
| 3861 |
|
| 3862 |
def check_retry_measurement(self, txt): |
| 3863 |
"""Check if measurement should be retried based on Argyll CMS output. |
| 3864 |
|
| 3865 |
Args: |
| 3866 |
txt (str): The output text from the Argyll CMS command. |
| 3867 |
""" |
| 3868 |
if ( |
| 3869 |
"key to retry:" in txt |
| 3870 |
and "read stopped at user request!" not in self.recent.read() |
| 3871 |
and ( |
| 3872 |
"Sample read failed due to misread" in self.recent.read() |
| 3873 |
or "Sample read failed due to communication problem" |
| 3874 |
in self.recent.read() |
| 3875 |
) |
| 3876 |
and not self.subprocess_abort |
| 3877 |
): |
| 3878 |
self.retrycount += 1 |
| 3879 |
self.log(f"{APPNAME}: Retrying ({self.retrycount})...") |
| 3880 |
self.recent.write(f"\r\n{APPNAME}: Retrying ({self.retrycount})...") |
| 3881 |
self.safe_send(" ") |
| 3882 |
|
| 3883 |
def check_spotread_result(self, txt): |
| 3884 |
"""Check if spotread returned a result. |
| 3885 |
|
| 3886 |
Args: |
| 3887 |
txt (str): The output text from the Argyll CMS command. |
| 3888 |
""" |
| 3889 |
if ( |
| 3890 |
self.cmdname == get_argyll_utilname("spotread") |
| 3891 |
and ( |
| 3892 |
self.progress_wnd is not getattr(self, "terminal", None) |
| 3893 |
or getattr(self.terminal, "Name", None) == "VisualWhitepointEditor" |
| 3894 |
) |
| 3895 |
and ( |
| 3896 |
"Result is XYZ:" in txt |
| 3897 |
or "Result is Y:" in txt |
| 3898 |
or ( |
| 3899 |
self.instrument_calibration_complete |
| 3900 |
and self.spotread_just_do_instrument_calibration |
| 3901 |
) |
| 3902 |
) |
| 3903 |
): |
| 3904 |
# Single spotread reading, we are done |
| 3905 |
wx.CallLater(1000, self.quit_terminate_cmd) |
| 3906 |
|
| 3907 |
def get_skip_video_levels_detection(self): |
| 3908 |
"""Return True if we should skip video levels detection. |
| 3909 |
|
| 3910 |
Returns: |
| 3911 |
bool: True if video levels detection should be skipped, False if it |
| 3912 |
should not be skipped. |
| 3913 |
""" |
| 3914 |
display_name = config.get_display_name(None, True) |
| 3915 |
return ( |
| 3916 |
self._detected_output_levels |
| 3917 |
or not getcfg("patterngenerator.detect_video_levels") |
| 3918 |
# Web @ localhost uses Argyll's built-in web server (-dweb:<port>). |
| 3919 |
# Video level detection would require a separate dispread session, |
| 3920 |
# which tears down/restarts that server before interactive adjust. |
| 3921 |
# Skip auto-detection here to keep a single continuous web session. |
| 3922 |
or display_name == "Web @ localhost" |
| 3923 |
or display_name == "Untethered" |
| 3924 |
or is_ccxx_testchart() |
| 3925 |
) |
| 3926 |
|
| 3927 |
def detect_video_levels(self): |
| 3928 |
"""Detect wether we need video (16..235) or data (0..255) levels. |
| 3929 |
|
| 3930 |
Returns: |
| 3931 |
bool: True if video levels were detected, False if data levels were |
| 3932 |
detected, |
| 3933 |
""" |
| 3934 |
if self.get_skip_video_levels_detection(): |
| 3935 |
if config.get_display_name(None, True) == "Web @ localhost" and not getattr( |
| 3936 |
self, "_web_video_levels_skip_logged", False |
| 3937 |
): |
| 3938 |
self.log( |
| 3939 |
"Skipping output levels detection for Web @ localhost " |
| 3940 |
"to keep a continuous web session." |
| 3941 |
) |
| 3942 |
self._web_video_levels_skip_logged = True |
| 3943 |
return True |
| 3944 |
self._detecting_video_levels = True |
| 3945 |
try: |
| 3946 |
while True: |
| 3947 |
result = self._detect_video_levels() |
| 3948 |
if result is not None: |
| 3949 |
return result |
| 3950 |
finally: |
| 3951 |
self._detecting_video_levels = False |
| 3952 |
|
| 3953 |
def _detect_video_levels(self): |
| 3954 |
"""Detect black clipping due to incorrect levels. |
| 3955 |
|
| 3956 |
Returns: |
| 3957 |
bool: True if video levels were detected, False if data levels were |
| 3958 |
detected, |
| 3959 |
Exception: If an error occurred during detection. |
| 3960 |
""" |
| 3961 |
self.log("Detecting output levels range...") |
| 3962 |
tempdir = self.create_tempdir() |
| 3963 |
if isinstance(tempdir, Exception): |
| 3964 |
return tempdir |
| 3965 |
ti1_path = os.path.join(tempdir, "0_16.ti1") |
| 3966 |
try: |
| 3967 |
with open(ti1_path, "wb") as ti1: |
| 3968 |
ti1.write( |
| 3969 |
b"""CTI1 |
| 3970 |
|
| 3971 |
DESCRIPTOR "Argyll Calibration Target chart information 1" |
| 3972 |
ORIGINATOR "Argyll targen" |
| 3973 |
CREATED "Thu Apr 20 12:22:05 2017" |
| 3974 |
APPROX_WHITE_POINT "95.045781 100.000003 108.905751" |
| 3975 |
COLOR_REP "RGB" |
| 3976 |
|
| 3977 |
NUMBER_OF_FIELDS 7 |
| 3978 |
BEGIN_DATA_FORMAT |
| 3979 |
SAMPLE_ID RGB_R RGB_G RGB_B XYZ_X XYZ_Y XYZ_Z |
| 3980 |
END_DATA_FORMAT |
| 3981 |
|
| 3982 |
NUMBER_OF_SETS 3 |
| 3983 |
BEGIN_DATA |
| 3984 |
1 100.00 100.00 100.00 95.046 100.00 108.91 |
| 3985 |
2 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 |
| 3986 |
3 6.2500 6.2500 6.2500 0.2132 0.2241 0.2443 |
| 3987 |
END_DATA |
| 3988 |
""" |
| 3989 |
) |
| 3990 |
except Exception as exception: |
| 3991 |
return exception |
| 3992 |
setcfg("patterngenerator.use_video_levels", 0) |
| 3993 |
result = self.measure_ti1( |
| 3994 |
ti1_path, get_data_path("linear.cal"), allow_video_levels=False |
| 3995 |
) |
| 3996 |
if result is None: |
| 3997 |
return False |
| 3998 |
if isinstance(result, Exception) or not result: |
| 3999 |
return result |
| 4000 |
ti3_path = os.path.join(tempdir, "0_16.ti3") |
| 4001 |
try: |
| 4002 |
ti3 = CGATS(ti3_path) |
| 4003 |
except (OSError, CGATSError) as exception: |
| 4004 |
return exception |
| 4005 |
try: |
| 4006 |
verify_ti1_rgb_xyz(ti3) |
| 4007 |
except CGATSError as exception: |
| 4008 |
return exception |
| 4009 |
luminance_XYZ_cdm2 = ti3.queryv1("LUMINANCE_XYZ_CDM2") |
| 4010 |
if not luminance_XYZ_cdm2: |
| 4011 |
return Error( |
| 4012 |
lang.getstr( |
| 4013 |
"error.testchart.missing_fields", (ti3_path, "LUMINANCE_XYZ_CDM2") |
| 4014 |
) |
| 4015 |
) |
| 4016 |
try: |
| 4017 |
Y_cdm2 = float(luminance_XYZ_cdm2.split()[1]) |
| 4018 |
except (IndexError, ValueError): |
| 4019 |
return Error(lang.getstr("error.testchart.invalid", ti3_path)) |
| 4020 |
if Y_cdm2 <= 0 or math.isnan(Y_cdm2): |
| 4021 |
return Error(lang.getstr("error.luminance.invalid")) |
| 4022 |
black_0 = ti3[0].DATA[1] |
| 4023 |
black_16 = ti3[0].DATA[2] |
| 4024 |
if black_0 and black_16: |
| 4025 |
self.log( |
| 4026 |
"RGB level 0 is {:.6f} cd/m2".format(black_0["XYZ_Y"] / 100.0 * Y_cdm2) |
| 4027 |
) |
| 4028 |
self.log( |
| 4029 |
"RGB level 16 is {:.6f} cd/m2".format( |
| 4030 |
black_16["XYZ_Y"] / 100.0 * Y_cdm2 |
| 4031 |
) |
| 4032 |
) |
| 4033 |
# Check delta cd/m2 to determine if data or video levels |
| 4034 |
# We need to take the display white luminance into account |
| 4035 |
threshold = 0.02 / Y_cdm2 * 100 # Threshold 0.02 cd/m2 |
| 4036 |
assume_video_levels = black_16["XYZ_Y"] - black_0["XYZ_Y"] < threshold |
| 4037 |
if assume_video_levels: |
| 4038 |
if config.get_display_name() == "madVR": |
| 4039 |
# This is an error |
| 4040 |
return Error(lang.getstr("madvr.wrong_levels_detected")) |
| 4041 |
if not config.is_virtual_display(): |
| 4042 |
# Could be a misconfiguration of display or graphics driver. |
| 4043 |
# Make the user aware. |
| 4044 |
self._detected_levels_issue_confirm_wait = True |
| 4045 |
wx.CallAfter(self.detected_levels_issue_confirm) |
| 4046 |
# Wait for call to return |
| 4047 |
while ( |
| 4048 |
self._detected_levels_issue_confirm_wait |
| 4049 |
and not self.subprocess_abort |
| 4050 |
): |
| 4051 |
sleep(0.05) |
| 4052 |
if self._use_detected_video_levels is False: |
| 4053 |
return False |
| 4054 |
if self._use_detected_video_levels is None: |
| 4055 |
# Retry |
| 4056 |
return None |
| 4057 |
self.log("Using limited range output levels") |
| 4058 |
else: |
| 4059 |
self.log("Assuming full range output levels") |
| 4060 |
setcfg("patterngenerator.use_video_levels", int(assume_video_levels)) |
| 4061 |
if not config.is_patterngenerator() and sys.platform == "darwin": |
| 4062 |
# macOS video levels encoding seems to only work right on |
| 4063 |
# some machines if not using videoLUT to do the scaling |
| 4064 |
setcfg_cond(assume_video_levels, "calibration.use_video_lut", 0) |
| 4065 |
self._detected_output_levels = True |
| 4066 |
else: |
| 4067 |
return Error( |
| 4068 |
lang.getstr( |
| 4069 |
"error.testchart.missing_fields", |
| 4070 |
(ti3_path, ", ".join(list(black_0.keys()))), |
| 4071 |
) |
| 4072 |
) |
| 4073 |
return True |
| 4074 |
|
| 4075 |
def detected_levels_issue_confirm(self): |
| 4076 |
"""Show a confirmation dialog to the user if a levels issue was detected.""" |
| 4077 |
dlg = ConfirmDialog( |
| 4078 |
None, |
| 4079 |
msg=lang.getstr("display.levels_issue_detected"), |
| 4080 |
ok=lang.getstr("retry"), |
| 4081 |
alt=lang.getstr("fix_output_levels_using_vcgt"), |
| 4082 |
wrap=100, |
| 4083 |
) |
| 4084 |
result = dlg.ShowModal() |
| 4085 |
dlg.Destroy() |
| 4086 |
if result == wx.ID_OK: |
| 4087 |
# Retry |
| 4088 |
self._use_detected_video_levels = None |
| 4089 |
elif result == wx.ID_CANCEL: |
| 4090 |
self._use_detected_video_levels = False |
| 4091 |
else: |
| 4092 |
# Fix output levels using calibration |
| 4093 |
self._use_detected_video_levels = True |
| 4094 |
self._detected_levels_issue_confirm_wait = False |
| 4095 |
|
| 4096 |
def do_instrument_calibration(self, failed=False): |
| 4097 |
"""Ask user to initiate sensor calibration and execute. |
| 4098 |
|
| 4099 |
Give an option to cancel. |
| 4100 |
|
| 4101 |
Args: |
| 4102 |
failed (bool): If True, the calibration failed and the user should |
| 4103 |
be informed about it. If False, the calibration was successful |
| 4104 |
and the user should be prompted to calibrate the instrument. |
| 4105 |
|
| 4106 |
Returns: |
| 4107 |
None | bool: None if the calibration was initiated, False if the |
| 4108 |
user canceled |
| 4109 |
""" |
| 4110 |
if getattr(self, "subprocess_abort", False) or getattr( |
| 4111 |
self, "thread_abort", False |
| 4112 |
): |
| 4113 |
# If we are aborting, ignore request |
| 4114 |
return None |
| 4115 |
self.instrument_on_screen = False |
| 4116 |
self.log(f"{APPNAME}: Prompting to calibrate instrument") |
| 4117 |
self.progress_wnd.Pulse(" " * 4) |
| 4118 |
if failed: |
| 4119 |
msg = lang.getstr("failure") |
| 4120 |
elif self.get_instrument_name() == "ColorMunki": |
| 4121 |
msg = lang.getstr("instrument.calibrate.colormunki") |
| 4122 |
else: |
| 4123 |
# Detect type of calibration (emissive dark or reflective) |
| 4124 |
# by looking for serial number of calibration tile |
| 4125 |
# Argyll up to 1.8.3: 'Serial no.' |
| 4126 |
# Argyll 1.9.x: 'S/N' |
| 4127 |
serial = re.search(r"(?:Serial no.|S/N) (\S+)", self.recent.read(), re.I) |
| 4128 |
if serial: |
| 4129 |
# Reflective calibration, white reference tile required |
| 4130 |
# (e.g. i1 Pro hires mode) |
| 4131 |
msg = lang.getstr("instrument.calibrate.reflective", serial.group(1)) |
| 4132 |
elif self._detected_instrument and "SpyderX" in self._detected_instrument: |
| 4133 |
msg = lang.getstr("instrument.calibrate.spyderx") |
| 4134 |
else: |
| 4135 |
# Emissive dark calibration |
| 4136 |
msg = lang.getstr("instrument.calibrate") |
| 4137 |
if self.use_madvr: |
| 4138 |
fullscreen = self.madtpg.is_fullscreen() |
| 4139 |
self.madtpg_show_osd( |
| 4140 |
msg, sys.platform == "win32" and self.single_real_display() |
| 4141 |
) |
| 4142 |
dlg = ConfirmDialog( |
| 4143 |
self.progress_wnd, |
| 4144 |
msg="{}\n\n{}".format( |
| 4145 |
msg, |
| 4146 |
( |
| 4147 |
( |
| 4148 |
self._detected_instrument |
| 4149 |
and "{}{}".format( |
| 4150 |
self._detected_instrument, |
| 4151 |
( |
| 4152 |
self._detected_instrument_serial |
| 4153 |
and " ({} {})".format( |
| 4154 |
lang.getstr("serial_number"), |
| 4155 |
self._detected_instrument_serial, |
| 4156 |
) |
| 4157 |
) |
| 4158 |
or "", |
| 4159 |
) |
| 4160 |
) |
| 4161 |
or self.get_instrument_name() |
| 4162 |
), |
| 4163 |
), |
| 4164 |
ok=lang.getstr("ok"), |
| 4165 |
cancel=lang.getstr("cancel"), |
| 4166 |
bitmap=get_icon(32, "dialog-information"), |
| 4167 |
) |
| 4168 |
self.progress_wnd.dlg = dlg |
| 4169 |
dlg_result = dlg.ShowModal() |
| 4170 |
dlg.Destroy() |
| 4171 |
if self.finished: |
| 4172 |
self.log( |
| 4173 |
f"{APPNAME}: Ignoring instrument calibration prompt (worker " |
| 4174 |
"thread finished)" |
| 4175 |
) |
| 4176 |
return None |
| 4177 |
if dlg_result != wx.ID_OK: |
| 4178 |
self.log(f"{APPNAME}: Canceled instrument calibration prompt") |
| 4179 |
self._last_calibration_msg = None |
| 4180 |
self.abort_subprocess() |
| 4181 |
return False |
| 4182 |
self.log(f"{APPNAME}: About to calibrate instrument") |
| 4183 |
self.progress_wnd.Pulse(lang.getstr("please_wait")) |
| 4184 |
if self.safe_send(" "): |
| 4185 |
self.progress_wnd.Pulse(lang.getstr("instrument.calibrating")) |
| 4186 |
if self.use_madvr: |
| 4187 |
if sys.platform == "win32": |
| 4188 |
self.madtpg.set_osd_text("\u25b6") # "Play" symbol |
| 4189 |
self.madtpg_restore_settings(False, fullscreen) |
| 4190 |
return None |
| 4191 |
|
| 4192 |
def abort_all(self, confirm=False): |
| 4193 |
"""Abort all worker threads and subprocesses. |
| 4194 |
|
| 4195 |
Args: |
| 4196 |
confirm (bool): If True, show a confirmation dialog before |
| 4197 |
aborting. |
| 4198 |
|
| 4199 |
Returns: |
| 4200 |
bool: True if at least one worker was aborted, False otherwise. |
| 4201 |
""" |
| 4202 |
aborted = False |
| 4203 |
for worker in workers: |
| 4204 |
if not getattr(worker, "finished", True): |
| 4205 |
worker.abort_subprocess(confirm) |
| 4206 |
aborted = True |
| 4207 |
return aborted |
| 4208 |
|
| 4209 |
def abort_subprocess(self, confirm=False): |
| 4210 |
"""Abort the current subprocess or thread. |
| 4211 |
|
| 4212 |
Args: |
| 4213 |
confirm (bool): If True, show a confirmation dialog before |
| 4214 |
aborting. |
| 4215 |
""" |
| 4216 |
if getattr(self, "abort_requested", False): |
| 4217 |
return |
| 4218 |
self.abort_requested = True |
| 4219 |
if confirm and getattr(self, "progress_wnd", None): |
| 4220 |
prev_dlg = getattr(self.progress_wnd, "dlg", None) |
| 4221 |
if ( |
| 4222 |
prev_dlg |
| 4223 |
and prev_dlg.IsShownOnScreen() |
| 4224 |
and not isinstance(prev_dlg, DummyDialog) |
| 4225 |
): |
| 4226 |
self.abort_requested = False |
| 4227 |
return |
| 4228 |
pause = not getattr(self.progress_wnd, "paused", False) and hasattr( |
| 4229 |
self.progress_wnd, "pause_continue_handler" |
| 4230 |
) |
| 4231 |
if pause: |
| 4232 |
self.progress_wnd.pause_continue_handler(True) |
| 4233 |
self.pause_continue() |
| 4234 |
dlg = ConfirmDialog( |
| 4235 |
self.progress_wnd, |
| 4236 |
msg=lang.getstr("dialog.confirm_cancel"), |
| 4237 |
ok=lang.getstr("yes"), |
| 4238 |
cancel=lang.getstr("no"), |
| 4239 |
bitmap=get_icon(32, "dialog-warning"), |
| 4240 |
) |
| 4241 |
self.progress_wnd.dlg = dlg |
| 4242 |
dlg_result = dlg.ShowModal() |
| 4243 |
if isinstance(prev_dlg, DummyDialog): |
| 4244 |
self.progress_wnd.dlg = prev_dlg |
| 4245 |
dlg.Destroy() |
| 4246 |
if dlg_result != wx.ID_OK: |
| 4247 |
if pause: |
| 4248 |
self.progress_wnd.Resume() |
| 4249 |
else: |
| 4250 |
self.progress_wnd.keepGoing = True |
| 4251 |
if hasattr(self.progress_wnd, "cancel"): |
| 4252 |
self.progress_wnd.cancel.Enable() |
| 4253 |
self.abort_requested = False |
| 4254 |
return |
| 4255 |
self.patch_count = 0 |
| 4256 |
self.subprocess_abort = True |
| 4257 |
self.thread_abort = True |
| 4258 |
if self.use_patterngenerator or self.use_madnet_tpg: |
| 4259 |
abortfilename = os.path.join(self.tempdir, ".abort") |
| 4260 |
open(abortfilename, "w").close() |
| 4261 |
delayedresult.startWorker(self.quit_terminate_consumer, self.quit_terminate_cmd) |
| 4262 |
|
| 4263 |
def quit_terminate_consumer(self, delayedResult): |
| 4264 |
"""Consumer for delayed result of subprocess termination. |
| 4265 |
|
| 4266 |
Args: |
| 4267 |
delayedResult: Delayed result object containing the result of the |
| 4268 |
subprocess termination. |
| 4269 |
""" |
| 4270 |
try: |
| 4271 |
result = delayedResult.get() |
| 4272 |
except Exception as exception: |
| 4273 |
if hasattr(exception, "originalTraceback"): |
| 4274 |
self.log(exception.originalTraceback, fn=LOG) |
| 4275 |
else: |
| 4276 |
self.log(traceback.format_exc(), fn=LOG) |
| 4277 |
result = UnloggedError(safe_str(exception)) |
| 4278 |
if isinstance(result, Exception): |
| 4279 |
show_result_dialog(result, getattr(self, "progress_wnd", None)) |
| 4280 |
result = False |
| 4281 |
self.subprocess_abort = False |
| 4282 |
if not result: |
| 4283 |
self.thread_abort = False |
| 4284 |
self.abort_requested = False |
| 4285 |
if getattr(self, "progress_wnd", None): |
| 4286 |
self.progress_wnd.Resume() |
| 4287 |
|
| 4288 |
def instrument_place_on_screen(self) -> None | bool: |
| 4289 |
"""Prompt user to place the instrument on the screen. |
| 4290 |
|
| 4291 |
Returns: |
| 4292 |
None: if the user canceled the dialog. |
| 4293 |
bool: True if the user confirmed the dialog. |
| 4294 |
""" |
| 4295 |
if getattr(self, "subprocess_abort", False) or getattr( |
| 4296 |
self, "thread_abort", False |
| 4297 |
): |
| 4298 |
# If we are aborting, ignore request |
| 4299 |
return None |
| 4300 |
self.log(f"{APPNAME}: Prompting to place instrument on screen") |
| 4301 |
self.progress_wnd.Pulse(" " * 4) |
| 4302 |
if self.use_madvr: |
| 4303 |
fullscreen = self.madtpg.is_fullscreen() |
| 4304 |
self.madtpg_show_osd( |
| 4305 |
lang.getstr("instrument.place_on_screen"), |
| 4306 |
sys.platform == "win32" and self.single_real_display(), |
| 4307 |
) |
| 4308 |
dlg = ConfirmDialog( |
| 4309 |
self.progress_wnd, |
| 4310 |
msg="{}\n\n{}".format( |
| 4311 |
lang.getstr("instrument.place_on_screen"), |
| 4312 |
( |
| 4313 |
( |
| 4314 |
self._detected_instrument |
| 4315 |
and "{}{}".format( |
| 4316 |
self._detected_instrument, |
| 4317 |
( |
| 4318 |
self._detected_instrument_serial |
| 4319 |
and " ({} {})".format( |
| 4320 |
lang.getstr("serial_number"), |
| 4321 |
self._detected_instrument_serial, |
| 4322 |
) |
| 4323 |
) |
| 4324 |
or "", |
| 4325 |
) |
| 4326 |
) |
| 4327 |
or self.get_instrument_name() |
| 4328 |
), |
| 4329 |
), |
| 4330 |
ok=lang.getstr("ok"), |
| 4331 |
cancel=lang.getstr("cancel"), |
| 4332 |
bitmap=get_icon(32, "dialog-information"), |
| 4333 |
) |
| 4334 |
self.progress_wnd.dlg = dlg |
| 4335 |
dlg_result = dlg.ShowModal() |
| 4336 |
dlg.Destroy() |
| 4337 |
if self.finished: |
| 4338 |
self.log( |
| 4339 |
f"{APPNAME}: Ignoring instrument placement prompt (worker thread " |
| 4340 |
"finished)" |
| 4341 |
) |
| 4342 |
return None |
| 4343 |
if dlg_result != wx.ID_OK: |
| 4344 |
self.log(f"{APPNAME}: Canceled instrument placement prompt") |
| 4345 |
self.abort_subprocess() |
| 4346 |
return False |
| 4347 |
self.instrument_on_screen = True |
| 4348 |
self.log(f"{APPNAME}: Instrument on screen") |
| 4349 |
if not isinstance(self.progress_wnd, (UntetheredFrame, DisplayUniformityFrame)): |
| 4350 |
self.safe_send(" ") |
| 4351 |
self.pauseable_now = True |
| 4352 |
if self.use_madvr: |
| 4353 |
if sys.platform == "win32": |
| 4354 |
self.madtpg.set_osd_text("\u25b6") # "Play" symbol |
| 4355 |
self.madtpg_restore_settings(False, fullscreen) |
| 4356 |
return None |
| 4357 |
|
| 4358 |
def instrument_reposition_sensor(self): |
| 4359 |
"""Show a dialog asking user to reposition the instrument sensor. |
| 4360 |
|
| 4361 |
Returns: |
| 4362 |
None: if the user canceled the dialog. |
| 4363 |
bool: True if the user confirmed the dialog. |
| 4364 |
""" |
| 4365 |
if getattr(self, "subprocess_abort", False) or getattr( |
| 4366 |
self, "thread_abort", False |
| 4367 |
): |
| 4368 |
# If we are aborting, ignore request |
| 4369 |
return None |
| 4370 |
self.log(f"{APPNAME}: Prompting to reposition instrument sensor") |
| 4371 |
self.progress_wnd.Pulse(" " * 4) |
| 4372 |
fullscreen = False |
| 4373 |
if self.use_madvr: |
| 4374 |
fullscreen = self.madtpg.is_fullscreen() |
| 4375 |
self.madtpg_show_osd( |
| 4376 |
lang.getstr("instrument.reposition_sensor"), |
| 4377 |
sys.platform == "win32" and self.single_real_display(), |
| 4378 |
) |
| 4379 |
dlg = ConfirmDialog( |
| 4380 |
self.progress_wnd, |
| 4381 |
msg=lang.getstr("instrument.reposition_sensor"), |
| 4382 |
ok=lang.getstr("ok"), |
| 4383 |
cancel=lang.getstr("cancel"), |
| 4384 |
bitmap=get_icon(32, "dialog-warning"), |
| 4385 |
) |
| 4386 |
self.progress_wnd.dlg = dlg |
| 4387 |
dlg_result = dlg.ShowModal() |
| 4388 |
dlg.Destroy() |
| 4389 |
if self.finished: |
| 4390 |
self.log( |
| 4391 |
f"{APPNAME}: Ignoring instrument sensor repositioning prompt (worker " |
| 4392 |
"thread finished)" |
| 4393 |
) |
| 4394 |
return None |
| 4395 |
if dlg_result != wx.ID_OK: |
| 4396 |
self.log(f"{APPNAME}: Canceled instrument sensor repositioning prompt") |
| 4397 |
self.abort_subprocess() |
| 4398 |
return False |
| 4399 |
self.safe_send(" ") |
| 4400 |
if self.use_madvr: |
| 4401 |
if sys.platform == "win32": |
| 4402 |
self.madtpg.set_osd_text("\u25b6") # "Play" symbol |
| 4403 |
self.madtpg_restore_settings(False, fullscreen) |
| 4404 |
return None |
| 4405 |
|
| 4406 |
def clear_argyll_info(self): |
| 4407 |
"""Clear Argyll CMS version, detected displays and instruments.""" |
| 4408 |
self.argyll_bin_dir = None |
| 4409 |
self.argyll_version = [0, 0, 0] |
| 4410 |
self.argyll_version_string = "0.0.0" |
| 4411 |
self._displays = [] |
| 4412 |
self.display_edid = [] |
| 4413 |
self.display_manufacturers = [] |
| 4414 |
self.display_names = [] |
| 4415 |
self.display_rects = [] |
| 4416 |
self.displays = [] |
| 4417 |
self.instruments = [] |
| 4418 |
self.lut_access = [] |
| 4419 |
self.reset_argyll_enum() |
| 4420 |
|
| 4421 |
def reset_argyll_enum(self): |
| 4422 |
"""Reset auto-detected (during display/instrument enumeration) properties.""" |
| 4423 |
self.measurement_modes = {} |
| 4424 |
self.argyll_virtual_display = None |
| 4425 |
|
| 4426 |
def clear_cmd_output(self): |
| 4427 |
"""Clear any output from the last run command.""" |
| 4428 |
self.cmd = None |
| 4429 |
self.cmdname = None |
| 4430 |
self.retcode = -1 |
| 4431 |
self.output = [] |
| 4432 |
self.errors = [] |
| 4433 |
self.recent.clear() |
| 4434 |
self.retrycount = 0 |
| 4435 |
self.lastmsg.clear() |
| 4436 |
self.repeat = False |
| 4437 |
self.send_buffer = None |
| 4438 |
# Log interaction with Argyll tools |
| 4439 |
if not hasattr(self, "logger") or ( |
| 4440 |
isinstance(self.logger, DummyLogger) |
| 4441 |
and self.owner |
| 4442 |
and self.owner.Name == "mainframe" |
| 4443 |
): |
| 4444 |
if not self.owner or self.owner.Name != "mainframe": |
| 4445 |
self.logger = DummyLogger() |
| 4446 |
else: |
| 4447 |
self.logger = get_file_logger("interact") |
| 4448 |
if hasattr(self, "thread") and self.thread.is_alive() and self.interactive: |
| 4449 |
self.logger.info("-" * 80) |
| 4450 |
self.sessionlogfile = None |
| 4451 |
self.madtpg_bw_lvl = None |
| 4452 |
self.madtpg_fullscreen = None |
| 4453 |
self.use_madvr = False |
| 4454 |
self.use_madnet_tpg = False |
| 4455 |
self.use_patterngenerator = False |
| 4456 |
self.patch_sequence = False |
| 4457 |
self.patch_count = 0 |
| 4458 |
self.patterngenerator_sent_count = 0 |
| 4459 |
self.exec_cmd_returnvalue = None |
| 4460 |
self.tmpfiles = {} |
| 4461 |
self.buffer = [] |
| 4462 |
self._detected_instrument = None |
| 4463 |
self._detected_instrument_serial = None |
| 4464 |
|
| 4465 |
def lut3d_get_filename( |
| 4466 |
self, path=None, include_input_profile=True, include_ext=True |
| 4467 |
): |
| 4468 |
"""Generate a filename for the 3D LUT based on current settings. |
| 4469 |
|
| 4470 |
Args: |
| 4471 |
path (str): Optional base path for the LUT filename. |
| 4472 |
include_input_profile (bool): Whether to include the input profile |
| 4473 |
name in the filename. |
| 4474 |
include_ext (bool): Whether to include the file extension in the |
| 4475 |
filename. |
| 4476 |
|
| 4477 |
Returns: |
| 4478 |
str: The generated filename for the 3D LUT. |
| 4479 |
""" |
| 4480 |
# 3D LUT filename with crcr32 hash before extension - up to DCG 2.9.0.7 |
| 4481 |
profile_save_path = os.path.splitext( |
| 4482 |
path or getcfg("calibration.file") or DEFAULTS["calibration.file"] |
| 4483 |
)[0] |
| 4484 |
lut3d = [ |
| 4485 |
(getcfg("3dlut.gamap.use_b2a") and "gg") or "G", |
| 4486 |
"i{}".format(getcfg("3dlut.rendering_intent")), |
| 4487 |
"r{:d}".format(getcfg("3dlut.size")), |
| 4488 |
"e{}".format(getcfg("3dlut.encoding.input")), |
| 4489 |
"E{}".format(getcfg("3dlut.encoding.output")), |
| 4490 |
"I{}:{}:{}".format( |
| 4491 |
getcfg("3dlut.trc_gamma_type"), |
| 4492 |
getcfg("3dlut.trc_output_offset"), |
| 4493 |
getcfg("3dlut.trc_gamma"), |
| 4494 |
), |
| 4495 |
] |
| 4496 |
if getcfg("3dlut.format") == "3dl": |
| 4497 |
lut3d.append(str(getcfg("3dlut.bitdepth.input"))) |
| 4498 |
if getcfg("3dlut.format") in ("3dl", "png", "ReShade"): |
| 4499 |
lut3d.append(str(getcfg("3dlut.bitdepth.output"))) |
| 4500 |
if include_ext: |
| 4501 |
lut3d_ext = getcfg("3dlut.format") |
| 4502 |
if lut3d_ext == "eeColor": |
| 4503 |
lut3d_ext = "txt" |
| 4504 |
elif lut3d_ext == "madVR": |
| 4505 |
lut3d_ext = "3dlut" |
| 4506 |
elif lut3d_ext == "ReShade": |
| 4507 |
lut3d_ext = "png" |
| 4508 |
elif lut3d_ext == "icc": |
| 4509 |
lut3d_ext = PROFILE_EXT[1:] |
| 4510 |
else: |
| 4511 |
lut3d_ext = "" |
| 4512 |
if include_input_profile: |
| 4513 |
input_profname = os.path.splitext( |
| 4514 |
os.path.basename(getcfg("3dlut.input.profile")) |
| 4515 |
)[0] |
| 4516 |
else: |
| 4517 |
input_profname = "" |
| 4518 |
lut3d_path = ".".join( |
| 4519 |
[ |
| 4520 |
_f |
| 4521 |
for _f in [ |
| 4522 |
profile_save_path, |
| 4523 |
input_profname, |
| 4524 |
"{:X}".format(zlib.crc32("-".join(lut3d).encode()) & 0xFFFFFFFF), |
| 4525 |
lut3d_ext, |
| 4526 |
] |
| 4527 |
if _f |
| 4528 |
] |
| 4529 |
) |
| 4530 |
if not include_input_profile or not os.path.isfile(lut3d_path): |
| 4531 |
# 3D LUT filename with plain options before extension - DCG 2.9.0.8+ |
| 4532 |
enc_in = lut3d[3][1:] |
| 4533 |
enc_out = lut3d[4][1:] |
| 4534 |
encoding = enc_in |
| 4535 |
if enc_in != enc_out: |
| 4536 |
encoding += enc_out |
| 4537 |
cal_exclude = "" if getcfg("3dlut.output.profile.apply_cal") else "e" |
| 4538 |
if getcfg("3dlut.trc").startswith("smpte2084"): |
| 4539 |
lut3dp = [str(getcfg("3dlut.trc_output_offset")) + ",2084"] |
| 4540 |
if ( |
| 4541 |
getcfg("3dlut.hdr_peak_luminance") < 10000 |
| 4542 |
or getcfg("3dlut.trc") == "smpte2084.rolloffclip" |
| 4543 |
or getcfg("3dlut.hdr_minmll") |
| 4544 |
or getcfg("3dlut.hdr_maxmll") < 10000 |
| 4545 |
): |
| 4546 |
lut3dp.append("@{:0.0f}".format(getcfg("3dlut.hdr_peak_luminance"))) |
| 4547 |
if getcfg("3dlut.trc") == "smpte2084.hardclip": |
| 4548 |
lut3dp.append("h") |
| 4549 |
else: |
| 4550 |
lut3dp.append("s") |
| 4551 |
# Alternate clip - softer |
| 4552 |
if getcfg("3dlut.hdr_maxmll_alt_clip"): |
| 4553 |
lut3dp.append("s") |
| 4554 |
if getcfg("3dlut.hdr_minmll"): |
| 4555 |
lut3dp.append("{:.4f}".format(getcfg("3dlut.hdr_minmll"))) |
| 4556 |
if ( |
| 4557 |
getcfg("3dlut.hdr_minmll") |
| 4558 |
and getcfg("3dlut.hdr_maxmll") < 10000 |
| 4559 |
): |
| 4560 |
lut3dp.append("-") |
| 4561 |
if getcfg("3dlut.hdr_maxmll") < 10000: |
| 4562 |
lut3dp.append("{:0.0f}".format(getcfg("3dlut.hdr_maxmll"))) |
| 4563 |
if getcfg("3dlut.trc") == "smpte2084.rolloffclip": |
| 4564 |
# Hue and chroma preservation |
| 4565 |
if getcfg("3dlut.hdr_sat") != 0.5: |
| 4566 |
lut3dp.append("s{:.1f}".format(getcfg("3dlut.hdr_sat"))) |
| 4567 |
if getcfg("3dlut.hdr_hue") != 1.0: |
| 4568 |
lut3dp.append("h{:.1f}".format(getcfg("3dlut.hdr_hue"))) |
| 4569 |
elif getcfg("3dlut.trc") == "hlg": |
| 4570 |
lut3dp = ["HLG"] |
| 4571 |
if getcfg("3dlut.hdr_ambient_luminance") != 5: |
| 4572 |
ambient = stripzeros(getcfg("3dlut.hdr_ambient_luminance")) |
| 4573 |
lut3dp.append(f"@{ambient}") |
| 4574 |
elif getcfg("3dlut.apply_trc"): |
| 4575 |
lut3dp = [ |
| 4576 |
lut3d[5][1].replace("b", "bb") + lut3d[5][3:].replace(":", ",") |
| 4577 |
] # TRC |
| 4578 |
else: |
| 4579 |
# Use src profile TRC unmodified |
| 4580 |
lut3dp = [] |
| 4581 |
lut3dp.extend( |
| 4582 |
[ |
| 4583 |
cal_exclude, |
| 4584 |
lut3d[0], # Gamut mapping mode |
| 4585 |
lut3d[1][1:], # Rendering intent |
| 4586 |
encoding, |
| 4587 |
lut3d[2][1:], |
| 4588 |
] |
| 4589 |
) # Resolution |
| 4590 |
bitdepth_in = None |
| 4591 |
bitdepth_out = None |
| 4592 |
if len(lut3d) > 6: |
| 4593 |
bitdepth_in = lut3d[6] # Input bitdepth |
| 4594 |
if len(lut3d) > 7: |
| 4595 |
bitdepth_out = lut3d[7] # Output bitdepth |
| 4596 |
if bitdepth_in or bitdepth_out: |
| 4597 |
bitdepth = bitdepth_in |
| 4598 |
if bitdepth_out and bitdepth_in != bitdepth_out: |
| 4599 |
bitdepth += bitdepth_out |
| 4600 |
lut3dp.append(bitdepth) |
| 4601 |
lut3d_path = ".".join( |
| 4602 |
[ |
| 4603 |
_f |
| 4604 |
for _f in [ |
| 4605 |
profile_save_path, |
| 4606 |
input_profname, |
| 4607 |
"".join(lut3dp), |
| 4608 |
lut3d_ext, |
| 4609 |
] |
| 4610 |
if _f |
| 4611 |
] |
| 4612 |
) |
| 4613 |
return lut3d_path |
| 4614 |
|
| 4615 |
def create_3dlut( |
| 4616 |
self, |
| 4617 |
profile_in, |
| 4618 |
path, |
| 4619 |
profile_abst=None, |
| 4620 |
profile_out=None, |
| 4621 |
apply_cal=True, |
| 4622 |
intent="r", |
| 4623 |
file_format="cube", |
| 4624 |
size=17, |
| 4625 |
input_bits=10, |
| 4626 |
output_bits=12, |
| 4627 |
maxval=None, |
| 4628 |
input_encoding="n", |
| 4629 |
output_encoding="n", |
| 4630 |
trc_gamma=None, |
| 4631 |
trc_gamma_type="B", |
| 4632 |
trc_output_offset=0.0, |
| 4633 |
save_link_icc=True, |
| 4634 |
apply_black_offset=True, |
| 4635 |
use_b2a=False, |
| 4636 |
white_cdm2=100, |
| 4637 |
minmll=0, |
| 4638 |
maxmll=10000, |
| 4639 |
use_alternate_master_white_clip=True, |
| 4640 |
hdr_sat=0.5, |
| 4641 |
hdr_hue=0.5, |
| 4642 |
ambient_cdm2=5, |
| 4643 |
content_rgb_space="DCI P3", |
| 4644 |
hdr_display=False, |
| 4645 |
XYZwp=None, |
| 4646 |
): |
| 4647 |
"""Create a 3D LUT from one (device link) or two (device) profiles. |
| 4648 |
|
| 4649 |
Optionally incorporating an abstract profile. |
| 4650 |
""" |
| 4651 |
# .cube: http://doc.iridas.com/index.php?title=LUT_Formats |
| 4652 |
# .3dl: http://www.kodak.com/US/plugins/acrobat/en/motion/products/look/UserGuide.pdf |
| 4653 |
# http://download.autodesk.com/us/systemdocs/pdf/lustre_color_management_user_guide.pdf |
| 4654 |
# .spi3d: https://github.com/imageworks/OpenColorIO/blob/master/src/core/FileFormatSpi3D.cpp |
| 4655 |
# .mga: http://pogle.pandora-int.com/download/manual/lut3d_format.html |
| 4656 |
|
| 4657 |
print("-" * 80) |
| 4658 |
print(lang.getstr("3dlut.create")) |
| 4659 |
|
| 4660 |
for profile in (profile_in, profile_out): |
| 4661 |
if ( |
| 4662 |
profile.profileClass not in (b"mntr", b"link", b"scnr", b"spac") |
| 4663 |
or profile.colorSpace != b"RGB" |
| 4664 |
): |
| 4665 |
raise NotImplementedError( |
| 4666 |
lang.getstr( |
| 4667 |
"profile.unsupported", |
| 4668 |
( |
| 4669 |
profile.profileClass.decode("utf-8"), |
| 4670 |
profile.colorSpace.decode("utf-8"), |
| 4671 |
), |
| 4672 |
) |
| 4673 |
) |
| 4674 |
if profile_in.profileClass == b"link": |
| 4675 |
break |
| 4676 |
|
| 4677 |
# Setup temp dir |
| 4678 |
cwd = self.create_tempdir() |
| 4679 |
if isinstance(cwd, Exception): |
| 4680 |
raise cwd |
| 4681 |
|
| 4682 |
result = None |
| 4683 |
|
| 4684 |
path = os.path.split(path) |
| 4685 |
path = os.path.join( |
| 4686 |
path[0], make_argyll_compatible_path(path[1], is_name=True) |
| 4687 |
) |
| 4688 |
filename, ext = os.path.splitext(path) |
| 4689 |
name = os.path.basename(filename) |
| 4690 |
|
| 4691 |
if profile_in.profileClass == b"link": |
| 4692 |
link_basename = os.path.basename(profile_in.filename) |
| 4693 |
link_filename = os.path.join(cwd, link_basename) |
| 4694 |
profile_in.write(link_filename) |
| 4695 |
else: |
| 4696 |
collink = get_argyll_util("collink") |
| 4697 |
if not collink: |
| 4698 |
raise Error(lang.getstr("argyll.util.not_found", "collink")) |
| 4699 |
|
| 4700 |
extra_args = parse_argument_string(getcfg("extra_args.collink")) |
| 4701 |
|
| 4702 |
smpte2084 = trc_gamma in ("smpte2084.hardclip", "smpte2084.rolloffclip") |
| 4703 |
hlg = trc_gamma == "hlg" |
| 4704 |
hdr = smpte2084 or hlg |
| 4705 |
|
| 4706 |
profile_in_basename = make_argyll_compatible_path( |
| 4707 |
os.path.basename(profile_in.filename), is_name=True |
| 4708 |
) |
| 4709 |
|
| 4710 |
# XXX: collink creates dark blotch in yellow with perceptual intent |
| 4711 |
# when using HDR PQ tonemapping - force to colorimetric and rely on |
| 4712 |
# our own perceptual mapping |
| 4713 |
if hdr and not hlg: |
| 4714 |
if intent == "p": |
| 4715 |
intent = "r" |
| 4716 |
elif intent == "pa": |
| 4717 |
intent = "aw" |
| 4718 |
|
| 4719 |
hdr_use_src_gamut = ( |
| 4720 |
hdr |
| 4721 |
and profile_in_basename == "Rec2020.icm" |
| 4722 |
and intent in ("la", "lp", "p", "pa", "ms", "s", "aa") |
| 4723 |
and not get_arg("-G", extra_args) |
| 4724 |
and not get_arg("-g", extra_args) |
| 4725 |
) |
| 4726 |
|
| 4727 |
if hdr and not hdr_use_src_gamut and not use_b2a: |
| 4728 |
# Always use B2A instead of inverse forward table (faster and |
| 4729 |
# better result if B2A table has enough effective resolution) |
| 4730 |
# for HDR with colorimetric intents |
| 4731 |
# Check B2A resolution and regenerate on-the-fly if too low |
| 4732 |
# and created by ArgyllCMS |
| 4733 |
b2a = profile_out.tags.get("B2A1", profile_out.tags.get("B2A0")) |
| 4734 |
a2b = profile_out.tags.get("A2B1", profile_out.tags.get("A2B0")) |
| 4735 |
if ( |
| 4736 |
not b2a |
| 4737 |
or ( |
| 4738 |
isinstance(b2a, LUT16Type) |
| 4739 |
and b2a.clut_grid_steps < 17 |
| 4740 |
and profile_out.creator == "argl" |
| 4741 |
) |
| 4742 |
) and a2b: |
| 4743 |
clutres = getcfg("profile.b2a.hires.size") |
| 4744 |
b2aresult = self.update_profile_B2A(profile_out, clutres=clutres) |
| 4745 |
if isinstance(b2aresult, Exception): |
| 4746 |
raise b2aresult |
| 4747 |
profile_out.write() |
| 4748 |
if "B2A1" in profile_out.tags or "B2A0" in profile_out.tags: |
| 4749 |
use_b2a = True |
| 4750 |
|
| 4751 |
# Argyll applycal can't deal with single gamma TRC tags |
| 4752 |
# or TRC tags with less than 256 entries |
| 4753 |
_applycal_bug_workaround(profile_out) |
| 4754 |
|
| 4755 |
# Prepare building a device link |
| 4756 |
link_basename = name + PROFILE_EXT |
| 4757 |
link_filename = os.path.join(cwd, link_basename) |
| 4758 |
|
| 4759 |
profile_out_basename = make_argyll_compatible_path( |
| 4760 |
os.path.basename(profile_out.filename), is_name=True |
| 4761 |
) |
| 4762 |
if profile_in_basename == profile_out_basename: |
| 4763 |
(profile_out_filename, profile_out_ext) = os.path.splitext( |
| 4764 |
profile_out_basename |
| 4765 |
) |
| 4766 |
profile_out_basename = f"{profile_out_filename} (2){profile_out_ext}" |
| 4767 |
profile_out.filename = os.path.join(cwd, profile_out_basename) |
| 4768 |
profile_out.write() |
| 4769 |
profile_out_cal_path = os.path.splitext(profile_out.filename)[0] + ".cal" |
| 4770 |
|
| 4771 |
manufacturer = profile_out.getDeviceManufacturerDescription() |
| 4772 |
model = profile_out.getDeviceModelDescription() |
| 4773 |
device_manufacturer = profile_out.device["manufacturer"] |
| 4774 |
device_model = profile_out.device["model"] |
| 4775 |
mmod = profile_out.tags.get("mmod") |
| 4776 |
|
| 4777 |
self.set_sessionlogfile(None, name, cwd) |
| 4778 |
|
| 4779 |
collink_version_string = get_argyll_version_string("collink") |
| 4780 |
collink_version = parse_argyll_version_string(collink_version_string) |
| 4781 |
use_collink_bt1886 = trc_gamma and not hdr |
| 4782 |
|
| 4783 |
# The display profile may not reflect the measured black point. |
| 4784 |
# Get it from the embedded TI3 instead if zero from lookup. |
| 4785 |
odata = self.xicclu(profile_out, (0, 0, 0), pcs="x") |
| 4786 |
if len(odata) != 1 or len(odata[0]) != 3: |
| 4787 |
raise ValueError(f"Blackpoint is invalid: {odata}") |
| 4788 |
XYZbp = odata[0] |
| 4789 |
if not XYZbp[1] and isinstance(profile_out.tags.get("targ"), Text): |
| 4790 |
XYZbp = profile_out.get_chardata_bkpt() |
| 4791 |
if XYZbp: |
| 4792 |
XYZbp = [ |
| 4793 |
v * XYZbp[1] for v in list(profile_out.tags.wtpt.pcs.values()) |
| 4794 |
] |
| 4795 |
self.log( |
| 4796 |
"Using black Y from destination profile characterization " |
| 4797 |
f"data (normalized 0..100): {XYZbp[1] * 100:.6f}" |
| 4798 |
) |
| 4799 |
use_collink_bt1886 = False |
| 4800 |
elif XYZbp[1]: |
| 4801 |
# Use display profile blackpoint |
| 4802 |
XYZbp = None |
| 4803 |
|
| 4804 |
# Using xicclu instead of collink is more accurate on and near |
| 4805 |
# the gray axis (in some cases, i.e. HDR and cLUT res < 65, |
| 4806 |
# significantly so) |
| 4807 |
use_xicclu = ( |
| 4808 |
(EXPERIMENTAL or hdr) |
| 4809 |
and not profile_abst |
| 4810 |
and intent in ("a", "aw", "r") |
| 4811 |
and input_encoding in ("n", "t", "T") |
| 4812 |
and output_encoding in ("n", "t") |
| 4813 |
) |
| 4814 |
|
| 4815 |
# Apply calibration? |
| 4816 |
if apply_cal: |
| 4817 |
extract_cal_from_profile(profile_out, profile_out_cal_path) |
| 4818 |
|
| 4819 |
if self.argyll_version < [1, 6] or use_xicclu: |
| 4820 |
# Can't apply the calibration with old collink versions - |
| 4821 |
# apply the calibration to the 'out' profile prior to |
| 4822 |
# device linking instead |
| 4823 |
applycal = get_argyll_util("applycal") |
| 4824 |
if not applycal: |
| 4825 |
raise Error(lang.getstr("argyll.util.not_found", "applycal")) |
| 4826 |
self.log(lang.getstr("apply_cal")) |
| 4827 |
result = self.exec_cmd( |
| 4828 |
applycal, |
| 4829 |
[ |
| 4830 |
"-v", |
| 4831 |
profile_out_cal_path, |
| 4832 |
profile_out_basename, |
| 4833 |
profile_out.filename, |
| 4834 |
], |
| 4835 |
capture_output=True, |
| 4836 |
skip_scripts=True, |
| 4837 |
sessionlogfile=self.sessionlogfile, |
| 4838 |
) |
| 4839 |
if isinstance(result, Exception) and not getcfg("dry_run"): |
| 4840 |
raise result |
| 4841 |
if not result: |
| 4842 |
raise Error( |
| 4843 |
"\n\n".join( |
| 4844 |
[lang.getstr("apply_cal.error"), "\n".join(self.errors)] |
| 4845 |
) |
| 4846 |
) |
| 4847 |
profile_out = ICCProfile(profile_out.filename) |
| 4848 |
|
| 4849 |
in_rgb_space = profile_in.get_rgb_space() |
| 4850 |
if in_rgb_space: |
| 4851 |
in_colors = colormath.get_rgb_space_primaries_wp_xy(in_rgb_space) |
| 4852 |
if file_format == "madVR": |
| 4853 |
# Use a D65 white for the 3D LUT Input_Primaries as |
| 4854 |
# madVR can only deal correctly with D65 |
| 4855 |
# Use the same D65 xy values as written by madVR |
| 4856 |
# 3D LUT install API (ASTM E308-01) |
| 4857 |
in_colors[6:] = [0.31273, 0.32902] |
| 4858 |
else: |
| 4859 |
in_colors = [] |
| 4860 |
|
| 4861 |
if hdr_use_src_gamut: |
| 4862 |
content_rgb_space = colormath.get_rgb_space(content_rgb_space) |
| 4863 |
# Always force content RGB space whitepoint to D65 so |
| 4864 |
# default RGB to ICtCp matrix gives Ct=Cp=0 for R=G=B |
| 4865 |
# when tone mapping |
| 4866 |
content_rgb_space = list(content_rgb_space) |
| 4867 |
content_rgb_space[1] = colormath.get_whitepoint("D65") |
| 4868 |
content_colors = colormath.get_rgb_space_primaries_wp_xy( |
| 4869 |
content_rgb_space |
| 4870 |
) |
| 4871 |
|
| 4872 |
if hdr_use_src_gamut and content_colors[:6] != in_colors[:6]: |
| 4873 |
# Use source gamut to preserve more saturation. |
| 4874 |
# Assume content colorspace (i.e. DCI P3) encoded within |
| 4875 |
# container colorspace (i.e. Rec. 2020) |
| 4876 |
|
| 4877 |
# Get source profile |
| 4878 |
crx, cry = content_rgb_space[2:][0][:2] |
| 4879 |
cgx, cgy = content_rgb_space[2:][1][:2] |
| 4880 |
cbx, cby = content_rgb_space[2:][2][:2] |
| 4881 |
cwx, cwy = colormath.XYZ2xyY(*content_rgb_space[1])[:2] |
| 4882 |
rgb_space_name = ( |
| 4883 |
colormath.find_primaries_wp_xy_rgb_space_name(content_colors) |
| 4884 |
or "Custom" |
| 4885 |
) |
| 4886 |
cat = profile_in.guess_cat() or "Bradford" |
| 4887 |
self.log( |
| 4888 |
"Using chromatic adaptation transform matrix from " |
| 4889 |
"input profile for content colorspace:", |
| 4890 |
cat, |
| 4891 |
) |
| 4892 |
profile_src = ICCProfile.from_chromaticities( |
| 4893 |
crx, |
| 4894 |
cry, |
| 4895 |
cgx, |
| 4896 |
cgy, |
| 4897 |
cbx, |
| 4898 |
cby, |
| 4899 |
cwx, |
| 4900 |
cwy, |
| 4901 |
2.2, |
| 4902 |
rgb_space_name, |
| 4903 |
"", |
| 4904 |
cat=cat, |
| 4905 |
) |
| 4906 |
fd, profile_src.filename = tempfile.mkstemp( |
| 4907 |
PROFILE_EXT, f"{rgb_space_name}-", dir=cwd |
| 4908 |
) |
| 4909 |
stream = os.fdopen(fd, "wb") |
| 4910 |
profile_src.write(stream) |
| 4911 |
stream.close() |
| 4912 |
else: |
| 4913 |
profile_src = profile_out |
| 4914 |
|
| 4915 |
# Deal with applying TRC |
| 4916 |
if trc_gamma: |
| 4917 |
if ( |
| 4918 |
use_collink_bt1886 |
| 4919 |
and not use_xicclu |
| 4920 |
and (collink_version >= [1, 7] or not trc_output_offset) |
| 4921 |
): |
| 4922 |
# Make sure the profile has the expected Rec. 709 TRC |
| 4923 |
# for BT.1886 |
| 4924 |
self.log( |
| 4925 |
f"{APPNAME}: Applying Rec. 709 TRC to " |
| 4926 |
f"{os.path.basename(profile_in.filename)}" |
| 4927 |
) |
| 4928 |
for channel in ["r", "g", "b"]: |
| 4929 |
if f"{channel}TRC" in profile_in.tags: |
| 4930 |
profile_in.tags[f"{channel}TRC"].set_trc(-709) |
| 4931 |
else: |
| 4932 |
# For HDR or Argyll < 1.7 beta, alter profile TRC |
| 4933 |
# Argyll CMS prior to 1.7 beta development code 2014-07-10 |
| 4934 |
# does not support output offset, alter the source profile |
| 4935 |
# instead (note that accuracy is limited due to 16-bit |
| 4936 |
# encoding used in ICC profile, collink 1.7 can use full |
| 4937 |
# floating point processing and will be more precise) |
| 4938 |
self.blend_profile_blackpoint( |
| 4939 |
profile_in, |
| 4940 |
profile_out, |
| 4941 |
XYZbp, |
| 4942 |
trc_output_offset, |
| 4943 |
trc_gamma, |
| 4944 |
trc_gamma_type, |
| 4945 |
white_cdm2=white_cdm2, |
| 4946 |
minmll=minmll, |
| 4947 |
maxmll=maxmll, |
| 4948 |
use_alternate_master_white_clip=use_alternate_master_white_clip, |
| 4949 |
ambient_cdm2=ambient_cdm2, |
| 4950 |
content_rgb_space=content_rgb_space, |
| 4951 |
hdr_chroma_compression=not hdr_use_src_gamut |
| 4952 |
or content_colors[:6] != in_colors[:6], |
| 4953 |
hdr_sat=hdr_sat, |
| 4954 |
hdr_hue=hdr_hue, |
| 4955 |
hdr_target_profile=profile_src, |
| 4956 |
) |
| 4957 |
elif apply_black_offset: |
| 4958 |
# Apply only the black point blending portion of BT.1886 mapping |
| 4959 |
self.blend_profile_blackpoint( |
| 4960 |
profile_in, profile_out, XYZbp, 1.0, apply_trc=False |
| 4961 |
) |
| 4962 |
|
| 4963 |
# Deal with whitepoint |
| 4964 |
profile_in_wtpt_XYZ = list(profile_in.tags.wtpt.ir.values()) |
| 4965 |
if XYZwp: |
| 4966 |
# Quantize to ICC s15Fixed16Number encoding |
| 4967 |
XYZwp = [s15Fixed16Number(s15Fixed16Number_tohex(v)) for v in XYZwp] |
| 4968 |
else: |
| 4969 |
XYZwp = profile_in_wtpt_XYZ |
| 4970 |
if XYZwp != profile_in_wtpt_XYZ: |
| 4971 |
self.log( |
| 4972 |
"Using whitepoint chromaticity {:.4f} {:.4f} for input".format( |
| 4973 |
*colormath.XYZ2xyY(*XYZwp)[:2] |
| 4974 |
) |
| 4975 |
) |
| 4976 |
( |
| 4977 |
profile_in.tags.wtpt.X, |
| 4978 |
profile_in.tags.wtpt.Y, |
| 4979 |
profile_in.tags.wtpt.Z, |
| 4980 |
) = XYZwp |
| 4981 |
|
| 4982 |
profile_in.filename = os.path.join(cwd, profile_in_basename) |
| 4983 |
profile_in.write() |
| 4984 |
|
| 4985 |
if hdr_use_src_gamut and content_colors[:6] != in_colors[:6] and False: |
| 4986 |
# XXX: Old code - could be removed? |
| 4987 |
# Use source gamut to preserve more saturation. |
| 4988 |
# Assume content colorspace (i.e. DCI P3) encoded within |
| 4989 |
# container colorspace (i.e. Rec. 2020) |
| 4990 |
|
| 4991 |
tools = {} |
| 4992 |
for toolname in ( # "iccgamut", |
| 4993 |
# "timage", |
| 4994 |
"cctiff", |
| 4995 |
"tiffgamut", |
| 4996 |
): |
| 4997 |
tools[toolname] = get_argyll_util(toolname) |
| 4998 |
if not tools[toolname]: |
| 4999 |
raise Error(lang.getstr("argyll.util.not_found", toolname)) |
| 5000 |
|
| 5001 |
# Apply HDR TRC to source |
| 5002 |
self.blend_profile_blackpoint( |
| 5003 |
profile_src, |
| 5004 |
profile_out, |
| 5005 |
XYZbp, |
| 5006 |
trc_output_offset, |
| 5007 |
trc_gamma, |
| 5008 |
trc_gamma_type, |
| 5009 |
white_cdm2=white_cdm2, |
| 5010 |
minmll=minmll, |
| 5011 |
maxmll=maxmll, |
| 5012 |
use_alternate_master_white_clip=use_alternate_master_white_clip, |
| 5013 |
ambient_cdm2=ambient_cdm2, |
| 5014 |
hdr_chroma_compression=False, |
| 5015 |
hdr_sat=hdr_sat, |
| 5016 |
hdr_hue=hdr_hue, |
| 5017 |
) |
| 5018 |
|
| 5019 |
profile_src.write() |
| 5020 |
|
| 5021 |
# Create link from source to destination profile |
| 5022 |
gam_link_filename = tempfile.mktemp(PROFILE_EXT, "gam-link-", dir=cwd) # noqa: S306 |
| 5023 |
result = self.exec_cmd( |
| 5024 |
collink, |
| 5025 |
[ |
| 5026 |
"-v", |
| 5027 |
"-G", |
| 5028 |
"-ir", |
| 5029 |
profile_src.filename, |
| 5030 |
profile_in_basename, |
| 5031 |
gam_link_filename, |
| 5032 |
], |
| 5033 |
capture_output=True, |
| 5034 |
skip_scripts=True, |
| 5035 |
sessionlogfile=self.sessionlogfile, |
| 5036 |
) |
| 5037 |
if isinstance(result, Exception) and not getcfg("dry_run"): |
| 5038 |
raise result |
| 5039 |
if not result: |
| 5040 |
raise Error( |
| 5041 |
"\n".join(self.errors) |
| 5042 |
or "{} {}".format(collink, lang.getstr("error")) |
| 5043 |
) |
| 5044 |
|
| 5045 |
# Create RGB image |
| 5046 |
# gam_in_tiff = tempfile.mktemp(".tif", "gam-in-", dir=cwd) |
| 5047 |
# result = self.exec_cmd(tools["timage"], ["-x", gam_in_tiff], |
| 5048 |
# capture_output=True, |
| 5049 |
# skip_scripts=True, |
| 5050 |
# sessionlogfile=self.sessionlogfile) |
| 5051 |
# if isinstance(result, Exception) and not getcfg("dry_run"): |
| 5052 |
# raise result |
| 5053 |
# elif not result: |
| 5054 |
# raise Error("\n".join(self.errors) or lang.getstr("error")) |
| 5055 |
fd, gam_in_tiff = tempfile.mkstemp(".tif", "gam-in-", dir=cwd) |
| 5056 |
stream = os.fdopen(fd, "wb") |
| 5057 |
imfile.write_rgb_clut(stream, 65, file_format="TIFF") |
| 5058 |
stream.close() |
| 5059 |
|
| 5060 |
# Convert RGB image from source to destination to get source |
| 5061 |
# encoded within destination. |
| 5062 |
gam_out_tiff = tempfile.mktemp(".tif", "gam-out-", dir=cwd) # noqa: S306 |
| 5063 |
result = self.exec_cmd( |
| 5064 |
tools["cctiff"], |
| 5065 |
["-p", gam_link_filename, gam_in_tiff, gam_out_tiff], |
| 5066 |
capture_output=True, |
| 5067 |
skip_scripts=True, |
| 5068 |
sessionlogfile=self.sessionlogfile, |
| 5069 |
) |
| 5070 |
if isinstance(result, Exception) and not getcfg("dry_run"): |
| 5071 |
raise result |
| 5072 |
if not result: |
| 5073 |
raise Error( |
| 5074 |
"\n".join(self.errors) |
| 5075 |
or "{} {}".format(tools["cctiff"], lang.getstr("error")) |
| 5076 |
) |
| 5077 |
|
| 5078 |
# Create gamut surface from image |
| 5079 |
# gam_filename = os.path.splitext(profile_src.filename)[0] + ".gam" |
| 5080 |
# result = self.exec_cmd(tools["iccgamut"], ["-ir", "-pj", |
| 5081 |
# profile_src.filename], |
| 5082 |
# capture_output=True, |
| 5083 |
# skip_scripts=True, |
| 5084 |
# sessionlogfile=self.sessionlogfile) |
| 5085 |
gam_filename = os.path.splitext(gam_out_tiff)[0] + ".gam" |
| 5086 |
result = self.exec_cmd( |
| 5087 |
tools["tiffgamut"], |
| 5088 |
["-ir", "-pj", profile_in.filename, gam_out_tiff], |
| 5089 |
capture_output=True, |
| 5090 |
skip_scripts=True, |
| 5091 |
sessionlogfile=self.sessionlogfile, |
| 5092 |
) |
| 5093 |
if isinstance(result, Exception) and not getcfg("dry_run"): |
| 5094 |
raise result |
| 5095 |
if not result: |
| 5096 |
raise Error( |
| 5097 |
"\n".join(self.errors) |
| 5098 |
or "{} {}".format(tools["tiffgamut"], lang.getstr("error")) |
| 5099 |
) |
| 5100 |
else: |
| 5101 |
gam_filename = None |
| 5102 |
|
| 5103 |
# Now build the device link |
| 5104 |
args = [ |
| 5105 |
"-v", |
| 5106 |
"-qh", |
| 5107 |
"-g" if use_b2a else "-G", |
| 5108 |
f"-i{intent}", |
| 5109 |
f"-r{size:d}", |
| 5110 |
"-n", |
| 5111 |
] |
| 5112 |
if gam_filename: |
| 5113 |
# Use source gamut |
| 5114 |
args.insert(3, gam_filename) |
| 5115 |
if profile_abst: |
| 5116 |
profile_abst.write(os.path.join(cwd, "abstract.icc")) |
| 5117 |
args.extend(["-p", "abstract.icc"]) |
| 5118 |
if self.argyll_version >= [1, 6]: |
| 5119 |
if file_format == "madVR": |
| 5120 |
args.append("-3m") |
| 5121 |
elif file_format == "eeColor" and not TEST: |
| 5122 |
args.append("-3e") |
| 5123 |
elif file_format == "cube" and collink_version >= [1, 7] and not TEST: |
| 5124 |
args.append("-3c") |
| 5125 |
args.append(f"-e{input_encoding}") |
| 5126 |
args.append(f"-E{output_encoding}") |
| 5127 |
if collink_version >= [1, 7]: |
| 5128 |
args.append("-b") # Use RGB->RGB forced black point hack |
| 5129 |
if use_collink_bt1886 and trc_gamma_type in ("b", "B"): |
| 5130 |
if collink_version >= [1, 7]: |
| 5131 |
args.append( |
| 5132 |
f"-I{trc_gamma_type}:{trc_output_offset}:{trc_gamma}" |
| 5133 |
) |
| 5134 |
elif not trc_output_offset: |
| 5135 |
args.append(f"-I{trc_gamma_type}:{trc_gamma}") |
| 5136 |
if apply_cal: |
| 5137 |
# Apply the calibration when building our device link |
| 5138 |
# i.e. use collink -a parameter (apply calibration curves |
| 5139 |
# to link output and append linear) |
| 5140 |
args.extend(["-a", os.path.basename(profile_out_cal_path)]) |
| 5141 |
if extra_args: |
| 5142 |
args += extra_args |
| 5143 |
|
| 5144 |
# cLUT Input value tweaks to make Video encoded black land on |
| 5145 |
# 65 res grid nodes, which should help 33 and 17 res cLUTs too |
| 5146 |
def cLUT65_to_VidRGB(v): |
| 5147 |
if size not in (17, 33, 65): |
| 5148 |
return v |
| 5149 |
return colormath.cLUT65_to_VidRGB(v) |
| 5150 |
|
| 5151 |
def VidRGB_to_cLUT65(v): |
| 5152 |
if size not in (17, 33, 65): |
| 5153 |
return v |
| 5154 |
return colormath.VidRGB_to_cLUT65(v) |
| 5155 |
|
| 5156 |
logfiles = self.get_logfiles() |
| 5157 |
|
| 5158 |
xts = time() |
| 5159 |
if use_xicclu: |
| 5160 |
# Create device link using xicclu |
| 5161 |
is_argyll_lut_format = file_format == "icc" |
| 5162 |
|
| 5163 |
def clipVidRGB(RGB, black_hack=True): |
| 5164 |
"""Clip a value to the RGB Video range 16..235 RGB. |
| 5165 |
|
| 5166 |
Clip the incoming value RGB[] in place. |
| 5167 |
Return a bit mask of the channels that have/would clip, |
| 5168 |
scale all non-black values to avoid positive clipping and |
| 5169 |
return the restoring scale factor (> 1.0) if this has occurred, |
| 5170 |
return the full value in the clip direction in full[], |
| 5171 |
and return the uncliped value in unclipped[]. |
| 5172 |
|
| 5173 |
""" |
| 5174 |
clipmask = 0 |
| 5175 |
scale = 1.0 |
| 5176 |
full = [None] * 3 |
| 5177 |
unclipped = list(RGB) |
| 5178 |
|
| 5179 |
# Locate the channel with the largest value |
| 5180 |
mx = max(RGB) |
| 5181 |
# One channel positively clipping |
| 5182 |
if mx > 235.0 / 255.0: |
| 5183 |
scale = ((235.0 - 16.0) / 255.0) / (mx - (16.0 / 255.0)) |
| 5184 |
|
| 5185 |
# Scale all non-black value down towards black, |
| 5186 |
# to avoid clipping |
| 5187 |
for i, v in enumerate(RGB): |
| 5188 |
# Note if channel would clip in itself |
| 5189 |
if v > 235.0 / 255.0: |
| 5190 |
full[i] = 1.0 |
| 5191 |
clipmask |= 1 << i |
| 5192 |
if v > 16.0 / 255.0: |
| 5193 |
RGB[i] = (v - 16.0 / 255.0) * scale + 16.0 / 255.0 |
| 5194 |
|
| 5195 |
# See if any values negatively clip |
| 5196 |
for i, v in enumerate(RGB): |
| 5197 |
cond = v <= 16.0 / 255.0 if black_hack else v < 16.0 / 255.0 |
| 5198 |
if cond: |
| 5199 |
RGB[i] = 16.0 / 255.0 |
| 5200 |
full[i] = 0.0 |
| 5201 |
clipmask |= 1 << i |
| 5202 |
|
| 5203 |
scale = 1.0 / scale |
| 5204 |
|
| 5205 |
return clipmask, scale, full, unclipped, RGB |
| 5206 |
|
| 5207 |
logfiles.write("Generating input values...\n") |
| 5208 |
clip = {} |
| 5209 |
seen = {} # Seen RGB input values |
| 5210 |
seenkeys = {} |
| 5211 |
RGB_src_in = [] |
| 5212 |
maxind = size - 1.0 |
| 5213 |
level_16 = VidRGB_to_cLUT65(16.0 / 255) * maxind |
| 5214 |
level_235 = VidRGB_to_cLUT65(235.0 / 255) * maxind |
| 5215 |
prevperc = 0 |
| 5216 |
cliphack = False # Clip TV levels BtB/WtW in for full range out? |
| 5217 |
for a in range(size): |
| 5218 |
for b in range(size): |
| 5219 |
for c in range(size): |
| 5220 |
if self.thread_abort: |
| 5221 |
raise Info(lang.getstr("aborted")) |
| 5222 |
abc = (a, b, c) |
| 5223 |
RGB = [v / maxind for v in abc] |
| 5224 |
if input_encoding in ("t", "T"): |
| 5225 |
# TV levels in |
| 5226 |
if ( |
| 5227 |
cliphack |
| 5228 |
and output_encoding == "n" |
| 5229 |
and ( |
| 5230 |
min(abc) < level_16 |
| 5231 |
or max(abc) > math.ceil(level_235) |
| 5232 |
) |
| 5233 |
): |
| 5234 |
# Don't lookup out of range values |
| 5235 |
continue |
| 5236 |
RGB = [cLUT65_to_VidRGB(v) for v in RGB] |
| 5237 |
clip[abc] = clipVidRGB(RGB) |
| 5238 |
if a == b == c and a in ( |
| 5239 |
math.ceil(level_16), |
| 5240 |
math.ceil(level_235), |
| 5241 |
): |
| 5242 |
self.log( |
| 5243 |
"Input RGB (0..255) {:f} {:f} {:f}".format( |
| 5244 |
*[v * 255 for v in RGB] |
| 5245 |
) |
| 5246 |
) |
| 5247 |
# Convert 16..235 to 0..255 for xicclu |
| 5248 |
RGB = [ |
| 5249 |
colormath.convert_range( |
| 5250 |
v, 16.0 / 255, 235.0 / 255, 0, 1 |
| 5251 |
) |
| 5252 |
for v in RGB |
| 5253 |
] |
| 5254 |
RGB = [min(max(v, 0), 1) * 255 for v in RGB] |
| 5255 |
seenkey = tuple(round(v * 257) for v in RGB) |
| 5256 |
seenkeys[abc] = seenkey |
| 5257 |
if seenkey in seen: |
| 5258 |
continue |
| 5259 |
seen[seenkey] = True |
| 5260 |
RGB_src_in.append(RGB) |
| 5261 |
perc = round( |
| 5262 |
((a + 1) * (b + 1) * (c + 1)) / float(size**3) * 100 |
| 5263 |
) |
| 5264 |
if perc > prevperc: |
| 5265 |
logfiles.write(f"\r{perc:0.0f}%") |
| 5266 |
prevperc = perc |
| 5267 |
logfiles.write("\n") |
| 5268 |
self.log("Skipped", size**3 - len(seen), "duplicate input values") |
| 5269 |
# Forward lookup input RGB through source profile |
| 5270 |
logfiles.write("Looking up input values through source profile...\n") |
| 5271 |
XYZ_src_out = self.xicclu( |
| 5272 |
profile_in, |
| 5273 |
RGB_src_in, |
| 5274 |
intent[0], |
| 5275 |
pcs="x", |
| 5276 |
scale=255, |
| 5277 |
logfile=logfiles, |
| 5278 |
) |
| 5279 |
del RGB_src_in |
| 5280 |
if intent == "aw": |
| 5281 |
XYZw = self.xicclu(profile_in, [[1, 1, 1]], intent[0], pcs="x")[0] |
| 5282 |
# Lookup scaled down white XYZ |
| 5283 |
logfiles.write("Looking for solution...\n") |
| 5284 |
for n in range(9): |
| 5285 |
XYZscaled = [ |
| 5286 |
[v * (1 - (n * 2001 + i) / 20000.0) for v in XYZw] |
| 5287 |
for i in range(2001) |
| 5288 |
] |
| 5289 |
RGBscaled = self.xicclu( |
| 5290 |
profile_out, |
| 5291 |
XYZscaled, |
| 5292 |
"a", |
| 5293 |
"b" if use_b2a else "if", |
| 5294 |
pcs="x", |
| 5295 |
get_clip=True, |
| 5296 |
) |
| 5297 |
# Find point at which it no longer clips |
| 5298 |
XYZwscaled = None |
| 5299 |
for i, RGBclip in enumerate(RGBscaled): |
| 5300 |
if self.thread_abort: |
| 5301 |
raise Info(lang.getstr("aborted")) |
| 5302 |
if RGBclip[3] is True or max(RGBclip[:3]) > 1: |
| 5303 |
# Clipped, skip |
| 5304 |
continue |
| 5305 |
# Found |
| 5306 |
XYZwscaled = XYZscaled[i] |
| 5307 |
logfiles.write( |
| 5308 |
f"Solution found at index {i:d} " |
| 5309 |
f"(step size {1 / 2000.0:f})\n" |
| 5310 |
) |
| 5311 |
logfiles.write( |
| 5312 |
"RGB white {:6.4f} {:6.4f} {:6.4f}\n".format( |
| 5313 |
*RGBclip[:3] |
| 5314 |
) |
| 5315 |
) |
| 5316 |
logfiles.write( |
| 5317 |
"XYZ white {:6.4f} {:6.4f} {:6.4f}, " |
| 5318 |
"CCT {:.1f} K\n".format( |
| 5319 |
*(XYZscaled[i] + [colormath.XYZ2CCT(*XYZwscaled)]) |
| 5320 |
) |
| 5321 |
) |
| 5322 |
break |
| 5323 |
else: |
| 5324 |
if n == 8: |
| 5325 |
break |
| 5326 |
if XYZwscaled: |
| 5327 |
# Found solution |
| 5328 |
break |
| 5329 |
if not XYZwscaled: |
| 5330 |
raise Error( |
| 5331 |
f"No solution found in {n:d} iterations with {i:d} steps" |
| 5332 |
) |
| 5333 |
for XYZ in XYZ_src_out: |
| 5334 |
XYZ[:] = [v / XYZw[1] * XYZwscaled[1] for v in XYZ] |
| 5335 |
del RGBscaled |
| 5336 |
# Inverse forward lookup source profile output XYZ through |
| 5337 |
# destination profile |
| 5338 |
num_cpus = cpu_count() |
| 5339 |
num_workers = min(max(num_cpus, 1), size) |
| 5340 |
if "A2B0" in profile_out.tags and not use_b2a: |
| 5341 |
if num_cpus > 2: |
| 5342 |
num_workers = int(num_workers * 0.75) |
| 5343 |
num_batches = size // 9 |
| 5344 |
else: |
| 5345 |
if num_cpus > 2: |
| 5346 |
num_workers = 2 |
| 5347 |
num_batches = 1 |
| 5348 |
direction = "backward" if use_b2a else "inverse forward" |
| 5349 |
logfiles.write( |
| 5350 |
f"Creating device link from {direction} " |
| 5351 |
f"lookup ({num_workers:d} workers)...\n" |
| 5352 |
) |
| 5353 |
RGB_dst_out = [] |
| 5354 |
for slices in pool_slice( |
| 5355 |
_xicclu_mp, |
| 5356 |
XYZ_src_out, |
| 5357 |
(profile_out.filename, intent[0], "b" if use_b2a else "if"), |
| 5358 |
{ |
| 5359 |
"pcs": "x", |
| 5360 |
"use_cam_clipping": True, |
| 5361 |
"abortmessage": lang.getstr("aborted"), |
| 5362 |
}, |
| 5363 |
num_workers, |
| 5364 |
self.thread_abort, |
| 5365 |
logfiles, |
| 5366 |
num_batches=num_batches, |
| 5367 |
): |
| 5368 |
RGB_dst_out.extend(slices) |
| 5369 |
del XYZ_src_out |
| 5370 |
logfiles.write("\n") |
| 5371 |
logfiles.write("Filling cLUT...\n") |
| 5372 |
profile_link = ICCProfile() |
| 5373 |
profile_link.profileClass = b"link" |
| 5374 |
profile_link.connectionColorSpace = b"RGB" |
| 5375 |
profile_link.setDescription(name) |
| 5376 |
profile_link.setCopyright(getcfg("copyright")) |
| 5377 |
profile_link.tags.pseq = ProfileSequenceDescType(profile=profile_link) |
| 5378 |
profile_link.tags.pseq.add(profile_in) |
| 5379 |
profile_link.tags.pseq.add(profile_out) |
| 5380 |
profile_link.tags.A2B0 = A2B0 = LUT16Type(None, "A2B0", profile_link) |
| 5381 |
A2B0.matrix = colormath.Matrix3x3([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) |
| 5382 |
if input_encoding in ("t", "T"): |
| 5383 |
A2B0.input = [[]] * 3 |
| 5384 |
for i in range(2048): |
| 5385 |
A2B0.input[0].append(VidRGB_to_cLUT65(i / 2047.0) * 65535) |
| 5386 |
else: |
| 5387 |
A2B0.input = [[0, 65535]] * 3 |
| 5388 |
A2B0.output = [[0, 65535]] * 3 |
| 5389 |
A2B0.clut = [] |
| 5390 |
clut = {} |
| 5391 |
n = 0 |
| 5392 |
for a in range(size): |
| 5393 |
for b in range(size): |
| 5394 |
for c in range(size): |
| 5395 |
abc = (a, b, c) |
| 5396 |
if ( |
| 5397 |
cliphack |
| 5398 |
and input_encoding in ("t", "T") |
| 5399 |
and output_encoding == "n" |
| 5400 |
and ( |
| 5401 |
min(abc) < level_16 |
| 5402 |
or max(abc) > math.ceil(level_235) |
| 5403 |
) |
| 5404 |
): |
| 5405 |
# TV levels in, no value from lookup, full |
| 5406 |
# range out |
| 5407 |
continue |
| 5408 |
seenkey = seenkeys[abc] |
| 5409 |
if seenkey in seen and seen[seenkey] is not True: |
| 5410 |
RGB = seen[seenkey] |
| 5411 |
else: |
| 5412 |
if input_encoding in ("t", "T"): |
| 5413 |
cond = min(abc) <= level_16 and min(abc) == max(abc) |
| 5414 |
else: |
| 5415 |
cond = max(abc) == 0 |
| 5416 |
if cond: |
| 5417 |
# Black hack |
| 5418 |
self.log( |
| 5419 |
"Black hack - forcing output RGB " |
| 5420 |
"{:0.0f} {:0.0f} {:0.0f}".format( |
| 5421 |
*[ |
| 5422 |
cLUT65_to_VidRGB(v / maxind) * 255 |
| 5423 |
for v in abc |
| 5424 |
] |
| 5425 |
) |
| 5426 |
) |
| 5427 |
RGB = [0] * 3 |
| 5428 |
else: |
| 5429 |
RGB = RGB_dst_out[n] |
| 5430 |
seen[seenkey] = RGB |
| 5431 |
n += 1 |
| 5432 |
clut[abc] = RGB |
| 5433 |
del seen |
| 5434 |
del seenkeys |
| 5435 |
del RGB_dst_out |
| 5436 |
preserve_sync = getcfg("3dlut.preserve_sync") |
| 5437 |
prevperc = 0 |
| 5438 |
for a in range(size): |
| 5439 |
for b in range(size): |
| 5440 |
A2B0.clut.append([]) |
| 5441 |
for c in range(size): |
| 5442 |
abc = (a, b, c) |
| 5443 |
if ( |
| 5444 |
cliphack |
| 5445 |
and input_encoding in ("t", "T") |
| 5446 |
and output_encoding == "n" |
| 5447 |
and ( |
| 5448 |
min(abc) < level_16 |
| 5449 |
or max(abc) > math.ceil(level_235) |
| 5450 |
) |
| 5451 |
): |
| 5452 |
# TV levels in, no value from lookup, full |
| 5453 |
# range out |
| 5454 |
key = tuple( |
| 5455 |
min( |
| 5456 |
max(v, math.ceil(level_16)), |
| 5457 |
math.ceil(level_235), |
| 5458 |
) |
| 5459 |
for v in abc |
| 5460 |
) |
| 5461 |
RGB = clut[key] |
| 5462 |
else: |
| 5463 |
# Got value from lookup |
| 5464 |
RGB = clut[abc] |
| 5465 |
del clut[abc] |
| 5466 |
if output_encoding == "t": |
| 5467 |
# TV levels out |
| 5468 |
# Convert 0..255 to 16..235 |
| 5469 |
RGB = [ |
| 5470 |
colormath.convert_range( |
| 5471 |
v, 0, 1, 16.0 / 255, 235.0 / 255 |
| 5472 |
) |
| 5473 |
for v in RGB |
| 5474 |
] |
| 5475 |
|
| 5476 |
if input_encoding in ("t", "T"): |
| 5477 |
# TV levels in, scale/extrapolate clip |
| 5478 |
clipmask, scale, full, uci, cin = clip[abc] |
| 5479 |
del clip[abc] |
| 5480 |
for j, v in enumerate(RGB): |
| 5481 |
if not clipmask: |
| 5482 |
RGB[j] = v |
| 5483 |
continue |
| 5484 |
if ( |
| 5485 |
input_encoding != "T" |
| 5486 |
and scale > 1 |
| 5487 |
and v > 16.0 / 255.0 |
| 5488 |
): |
| 5489 |
# We got +ve clipping |
| 5490 |
# Re-scale all non-black values |
| 5491 |
v = ( |
| 5492 |
v - 16.0 / 255.0 |
| 5493 |
) * scale + 16.0 / 255.0 |
| 5494 |
|
| 5495 |
# Deal with -ve clipping and sync |
| 5496 |
if clipmask & (1 << j): |
| 5497 |
if full[j] == 0.0: |
| 5498 |
# Only extrapolate in black |
| 5499 |
# direction |
| 5500 |
ifull = ( |
| 5501 |
1.0 - full[j] |
| 5502 |
) # Opposite limit to full |
| 5503 |
|
| 5504 |
# Do simple extrapolation |
| 5505 |
# (Not perfect though) |
| 5506 |
v = ifull + (v - ifull) * ( |
| 5507 |
uci[j] - ifull |
| 5508 |
) / (cin[j] - ifull) |
| 5509 |
|
| 5510 |
# Clip or pass sync through |
| 5511 |
if ( |
| 5512 |
v < 0.0 |
| 5513 |
or v > 1.0 |
| 5514 |
or ( |
| 5515 |
preserve_sync |
| 5516 |
and abs(uci[j] - full[j]) < 1e-6 |
| 5517 |
) |
| 5518 |
): |
| 5519 |
v = full[j] |
| 5520 |
|
| 5521 |
RGB[j] = v |
| 5522 |
|
| 5523 |
RGB = [min(max(v, 0), 1) * 65535 for v in RGB] |
| 5524 |
A2B0.clut[-1].append(RGB) |
| 5525 |
perc = round(len(A2B0.clut) / float(size**2) * 100) |
| 5526 |
if perc > prevperc: |
| 5527 |
logfiles.write(f"\r{perc:0.0f}%") |
| 5528 |
prevperc = perc |
| 5529 |
logfiles.write("\n") |
| 5530 |
profile_link.write(link_filename) |
| 5531 |
self.log("Finished creating device link in", time() - xts, "seconds") |
| 5532 |
result = True |
| 5533 |
del clip |
| 5534 |
del clut |
| 5535 |
del A2B0 |
| 5536 |
else: |
| 5537 |
# Create device link (and 3D LUT, if applicable) using collink |
| 5538 |
is_argyll_lut_format = ( |
| 5539 |
self.argyll_version >= [1, 6] |
| 5540 |
and ( |
| 5541 |
( |
| 5542 |
( |
| 5543 |
file_format == "eeColor" |
| 5544 |
or (file_format == "cube" and collink_version >= [1, 7]) |
| 5545 |
) |
| 5546 |
and not TEST |
| 5547 |
) |
| 5548 |
or file_format == "madVR" |
| 5549 |
) |
| 5550 |
) or file_format == "icc" |
| 5551 |
result = self.exec_cmd( |
| 5552 |
collink, |
| 5553 |
[*args, profile_in_basename, profile_out_basename, link_filename], |
| 5554 |
capture_output=True, |
| 5555 |
skip_scripts=True, |
| 5556 |
) |
| 5557 |
if result and not isinstance(result, Exception): |
| 5558 |
self.log("Finished creating 3D LUT in", time() - xts, "seconds") |
| 5559 |
|
| 5560 |
if ( |
| 5561 |
result |
| 5562 |
and not isinstance(result, Exception) |
| 5563 |
and save_link_icc |
| 5564 |
and os.path.isfile(link_filename) |
| 5565 |
): |
| 5566 |
profile_link = ICCProfile(link_filename) |
| 5567 |
profile_link.setDescription(name) |
| 5568 |
profile_link.setCopyright(getcfg("copyright")) |
| 5569 |
if manufacturer: |
| 5570 |
profile_link.setDeviceManufacturerDescription(manufacturer) |
| 5571 |
if model: |
| 5572 |
profile_link.setDeviceModelDescription(model) |
| 5573 |
profile_link.device["manufacturer"] = device_manufacturer |
| 5574 |
profile_link.device["model"] = device_model |
| 5575 |
if mmod: |
| 5576 |
profile_link.tags.mmod = mmod |
| 5577 |
profile_link.tags.meta = DictType() |
| 5578 |
profile_link.tags.meta.update( |
| 5579 |
[ |
| 5580 |
("CMF_product", APPNAME), |
| 5581 |
("CMF_binary", APPNAME), |
| 5582 |
("CMF_version", VERSION_STRING), |
| 5583 |
( |
| 5584 |
"collink.args", |
| 5585 |
sp.list2cmdline( |
| 5586 |
[ |
| 5587 |
*args, |
| 5588 |
profile_in_basename, |
| 5589 |
profile_out_basename, |
| 5590 |
link_basename, |
| 5591 |
] |
| 5592 |
), |
| 5593 |
), |
| 5594 |
("collink.version", collink_version_string), |
| 5595 |
("encoding.input", input_encoding), |
| 5596 |
("encoding.output", output_encoding), |
| 5597 |
] |
| 5598 |
) |
| 5599 |
profile_link.calculate_id() |
| 5600 |
profile_link.write(f"{filename}{PROFILE_EXT}") |
| 5601 |
profile_link.tags.A2B0.clut_writepng(f"{filename}.A2B0.CLUT.png") |
| 5602 |
del profile_link |
| 5603 |
|
| 5604 |
if use_xicclu and file_format == "madVR": |
| 5605 |
# We need to up-interpolate the device link ourself |
| 5606 |
# Call this in a separate process so I/O congestion |
| 5607 |
# doesn't interfere with UI updates and audio |
| 5608 |
# madvr.icc_device_link_to_madvr(link_filename, |
| 5609 |
# rgb_space=profile_in.get_rgb_space(), |
| 5610 |
# hdr=smpte2084 + hdr_display, |
| 5611 |
# logfile=logfiles, |
| 5612 |
# convert_video_rgb_to_clut65=True) |
| 5613 |
interp_args = [] |
| 5614 |
if os.path.basename(EXE).lower().startswith("python"): |
| 5615 |
if os.path.basename(EXE).lower().startswith("pythonw"): |
| 5616 |
cmd = os.path.join( |
| 5617 |
EXEDIR, "python" + os.path.basename(EXE)[7:] |
| 5618 |
) |
| 5619 |
else: |
| 5620 |
cmd = EXE |
| 5621 |
py = os.path.normpath( |
| 5622 |
os.path.join( |
| 5623 |
PYDIR, "..", f"{APPNAME}-eeColor-to-madVR-converter.py" |
| 5624 |
) |
| 5625 |
) |
| 5626 |
if os.path.exists(py): |
| 5627 |
# Running from source or 0install |
| 5628 |
# If parent is running from 0install, the child |
| 5629 |
# will inherit the correct environment (PYTHONPATH) |
| 5630 |
# so no need to run child through 0install |
| 5631 |
# Need to run unbuffered so we can grab |
| 5632 |
# progress |
| 5633 |
interp_args.append("-u") |
| 5634 |
interp_args.append(py) |
| 5635 |
else: |
| 5636 |
# Regular install |
| 5637 |
# Need to run unbuffered so we can grab |
| 5638 |
# progress |
| 5639 |
interp_args.append("-u") |
| 5640 |
if sys.platform in ("win32", "darwin"): |
| 5641 |
interp_args.append( |
| 5642 |
get_data_path( |
| 5643 |
os.path.join( |
| 5644 |
"scripts", |
| 5645 |
f"{APPNAME.lower()}-eecolor-to-madvr-converter", |
| 5646 |
) |
| 5647 |
) |
| 5648 |
) |
| 5649 |
else: |
| 5650 |
# Linux |
| 5651 |
interp_args.append( |
| 5652 |
which( |
| 5653 |
f"{APPNAME.lower()}-eecolor-to-madvr-converter" |
| 5654 |
) |
| 5655 |
) |
| 5656 |
elif ISAPP: |
| 5657 |
cmd = os.path.join(EXEDIR, "python") |
| 5658 |
interp_args.extend( |
| 5659 |
[ |
| 5660 |
"-c", |
| 5661 |
"import sys;sys.path.insert(0, {});execfile({})".format( |
| 5662 |
os.path.join( |
| 5663 |
PYDIR.encode(FS_ENC), |
| 5664 |
"lib", |
| 5665 |
"python{}{}".format(*sys.version_info[:2]), |
| 5666 |
"site-packages.zip", |
| 5667 |
), |
| 5668 |
os.path.join( |
| 5669 |
PYDIR.encode(FS_ENC), |
| 5670 |
f"{APPNAME.lower()}-eecolor-to-madvr-converter", |
| 5671 |
), |
| 5672 |
), |
| 5673 |
] |
| 5674 |
) |
| 5675 |
else: |
| 5676 |
cmd = os.path.join( |
| 5677 |
PYDIR, f"{APPNAME}-eeColor-to-madVR-converter{EXE_EXT}" |
| 5678 |
) |
| 5679 |
if in_colors: |
| 5680 |
interp_args.append( |
| 5681 |
"--colorspace={}".format( |
| 5682 |
",".join([str(v) for v in in_colors]) |
| 5683 |
) |
| 5684 |
) |
| 5685 |
interp_args.append(f"--hdr={smpte2084 + hdr_display:0.0f}") |
| 5686 |
interp_args.append("--convert-video-rgb-to-clut65") |
| 5687 |
interp_args.append("--append-linear-cal") |
| 5688 |
interp_args.append("--batch") |
| 5689 |
interp_args.append(link_filename) |
| 5690 |
result = self.exec_cmd( |
| 5691 |
cmd, |
| 5692 |
interp_args, |
| 5693 |
capture_output=True, |
| 5694 |
skip_scripts=True, |
| 5695 |
use_pty=True, |
| 5696 |
) |
| 5697 |
if DEBUG: |
| 5698 |
h3d = madvr.H3DLUT(os.path.join(cwd, name + ".3dlut")) |
| 5699 |
h3d.write_devicelink(filename + ".3dlut" + PROFILE_EXT) |
| 5700 |
|
| 5701 |
if result and not isinstance(result, Exception): |
| 5702 |
if file_format == "madVR" and is_argyll_lut_format: |
| 5703 |
# We need to update Input_Primaries, otherwise the |
| 5704 |
# madVR 3D LUT won't work correctly! (collink fills |
| 5705 |
# Input_Primaries from a lookup through the input |
| 5706 |
# profile, which won't work correctly if the input |
| 5707 |
# profile is cLUT-based. Also, we want to use a D65 |
| 5708 |
# white as madVR can only deal correctly with D65 |
| 5709 |
h3d = madvr.H3DLUT(os.path.join(cwd, name + ".3dlut")) |
| 5710 |
input_primaries = h3d.parametersData.get("Input_Primaries") |
| 5711 |
if input_primaries: |
| 5712 |
if in_colors: |
| 5713 |
h3d.parametersData["Input_Primaries"] = in_colors |
| 5714 |
if smpte2084: |
| 5715 |
h3d.parametersData["Input_Transfer_Function"] = "PQ" |
| 5716 |
if hdr_display: |
| 5717 |
h3d.parametersData["Output_Transfer_Function"] = "PQ" |
| 5718 |
h3d.write() |
| 5719 |
else: |
| 5720 |
raise Error("madVR 3D LUT doesn't contain Input_Primaries") |
| 5721 |
|
| 5722 |
if hdr or not use_collink_bt1886 or XYZwp: |
| 5723 |
if not hdr and XYZwp != profile_in_wtpt_XYZ: |
| 5724 |
# Update profile description |
| 5725 |
profile_in.setDescription( |
| 5726 |
"{} {}x {}y".format( |
| 5727 |
profile_in.getDescription(), |
| 5728 |
*[ |
| 5729 |
stripzeros(f"{v:.4f}") |
| 5730 |
for v in colormath.XYZ2xyY(*XYZwp)[:2] |
| 5731 |
], |
| 5732 |
) |
| 5733 |
) |
| 5734 |
# Save source profile |
| 5735 |
in_name, in_ext = os.path.splitext(profile_in_basename) |
| 5736 |
profile_in.filename = os.path.join( |
| 5737 |
os.path.dirname(path), |
| 5738 |
self.lut3d_get_filename(profile_in_basename, False, False) |
| 5739 |
+ in_ext, |
| 5740 |
) |
| 5741 |
profile_in.write() |
| 5742 |
if isinstance(profile_in.tags.get("A2B0"), LUT16Type): |
| 5743 |
# Write diagnostic PNG |
| 5744 |
profile_in.tags.A2B0.clut_writepng( |
| 5745 |
"{}.A2B0.CLUT.png".format( # noqa: UP032 |
| 5746 |
os.path.splitext(profile_in.filename)[0] |
| 5747 |
) |
| 5748 |
) |
| 5749 |
if isinstance(profile_in.tags.get("DBG0"), LUT16Type): |
| 5750 |
# HDR RGB |
| 5751 |
profile_in.tags.DBG0.clut_writepng( |
| 5752 |
"{}.DBG0.CLUT.png".format( # noqa: UP032 |
| 5753 |
os.path.splitext(profile_in.filename)[0] |
| 5754 |
) |
| 5755 |
) |
| 5756 |
if isinstance(profile_in.tags.get("DBG1"), LUT16Type): |
| 5757 |
# Display RGB |
| 5758 |
profile_in.tags.DBG1.clut_writepng( |
| 5759 |
"{}.DBG1.CLUT.png".format( # noqa: UP032 |
| 5760 |
os.path.splitext(profile_in.filename)[0] |
| 5761 |
) |
| 5762 |
) |
| 5763 |
if isinstance(profile_in.tags.get("DBG2"), LUT16Type): |
| 5764 |
# Display XYZ |
| 5765 |
profile_in.tags.DBG2.clut_writepng( |
| 5766 |
"{}.DBG2.CLUT.png".format( # noqa: UP032 |
| 5767 |
os.path.splitext(profile_in.filename)[0] |
| 5768 |
) |
| 5769 |
) |
| 5770 |
|
| 5771 |
if is_argyll_lut_format or (use_xicclu and file_format == "madVR"): |
| 5772 |
# Collink has already written the 3DLUT for us, |
| 5773 |
# or we have written the madVR 3D LUT |
| 5774 |
if file_format == "cube": |
| 5775 |
if maxval is None: |
| 5776 |
maxval = 1.0 |
| 5777 |
# Strip any leading whitespace from each line (although |
| 5778 |
# leading/trailing spaces are allowed according to the spec). |
| 5779 |
# Also, Argyll does not write (optional) DOMAIN_MIN/MAX |
| 5780 |
# keywords. Add them after the fact. |
| 5781 |
cube_filename = os.path.join(cwd, f"{name}.cube") |
| 5782 |
if os.path.isfile(cube_filename): |
| 5783 |
add_domain = True |
| 5784 |
cube_data = [] |
| 5785 |
with open(cube_filename, "rb") as cube_file: |
| 5786 |
for line in cube_file: |
| 5787 |
# Strip any leading whitespace |
| 5788 |
line = line.lstrip() |
| 5789 |
if line.startswith(b"DOMAIN_"): |
| 5790 |
# Account for the possibility that a |
| 5791 |
# future Argyll version might write |
| 5792 |
# DOMAIN_MIN/MAX keywords. |
| 5793 |
add_domain = False |
| 5794 |
elif line.startswith(b"0.") and add_domain: |
| 5795 |
# 1st cube data entry marks end of keywords. |
| 5796 |
# Add DOMAIN_MIN/MAX keywords |
| 5797 |
cube_data.append(b"DOMAIN_MIN 0.0 0.0 0.0\n") |
| 5798 |
fp_offset = str(maxval).find(".") |
| 5799 |
domain_max = b"DOMAIN_MAX %s %s %s\n" % ( |
| 5800 |
(b"%%.%if" % len(str(maxval)[fp_offset + 1 :]),) |
| 5801 |
* 3 |
| 5802 |
) |
| 5803 |
cube_data.append(domain_max % ((maxval,) * 3)) |
| 5804 |
cube_data.append(b"\n") |
| 5805 |
add_domain = False |
| 5806 |
cube_data.append(line) |
| 5807 |
# Write updated cube |
| 5808 |
with open(cube_filename, "wb") as cube_file: |
| 5809 |
cube_file.write(b"".join(cube_data)) |
| 5810 |
result2 = self.wrapup( |
| 5811 |
not isinstance(result, UnloggedInfo) and result, |
| 5812 |
dst_path=path, |
| 5813 |
ext_filter=[".3dlut", ".cube", ".log", ".png", ".txt", ".wrl"], |
| 5814 |
) |
| 5815 |
if not result: |
| 5816 |
result = UnloggedError(lang.getstr("aborted")) |
| 5817 |
if isinstance(result2, Exception): |
| 5818 |
if isinstance(result, Exception): |
| 5819 |
result = Error(f"{result}\n\n{result2}") |
| 5820 |
else: |
| 5821 |
result = result2 |
| 5822 |
if not isinstance(result, Exception): |
| 5823 |
return |
| 5824 |
|
| 5825 |
if isinstance(result, Exception): |
| 5826 |
raise result |
| 5827 |
if not result: |
| 5828 |
raise UnloggedError(lang.getstr("aborted")) |
| 5829 |
|
| 5830 |
# We have to create the 3DLUT ourselves |
| 5831 |
logfiles.write(f"Generating {file_format} 3D LUT...\n") |
| 5832 |
|
| 5833 |
# Create input RGB values |
| 5834 |
RGB_oin = [] |
| 5835 |
RGB_in = [] |
| 5836 |
RGB_indexes = [] |
| 5837 |
seen = {} |
| 5838 |
if file_format == "eeColor": |
| 5839 |
# Fixed size |
| 5840 |
size = 65 |
| 5841 |
elif file_format == "ReShade": |
| 5842 |
file_format = "png" |
| 5843 |
if file_format == "3dl": |
| 5844 |
if maxval is None: |
| 5845 |
maxval = 1023 |
| 5846 |
if output_bits is None: |
| 5847 |
output_bits = math.log(maxval + 1) / math.log(2) |
| 5848 |
if input_bits is None: |
| 5849 |
input_bits = output_bits |
| 5850 |
|
| 5851 |
# Note: We only round up for the input values, output values |
| 5852 |
# are rounded to nearest integer |
| 5853 |
def quantizer(v): |
| 5854 |
return math.ceil(v * (2**input_bits - 1)) |
| 5855 |
|
| 5856 |
scale = quantizer(1.0) |
| 5857 |
else: |
| 5858 |
|
| 5859 |
def quantizer(v): |
| 5860 |
return v |
| 5861 |
|
| 5862 |
scale = 1.0 |
| 5863 |
step = 1.0 / (size - 1) |
| 5864 |
RGB_triplet = [0.0, 0.0, 0.0] |
| 5865 |
RGB_index = [0, 0, 0] |
| 5866 |
# Set the fastest and slowest changing columns, from right to left |
| 5867 |
if file_format in ("3dl", "mga", "spi3d") or ( |
| 5868 |
file_format == "png" and getcfg("3dlut.image.order") == "bgr" |
| 5869 |
): |
| 5870 |
columns = (0, 1, 2) |
| 5871 |
elif file_format == "eeColor": |
| 5872 |
columns = (2, 0, 1) |
| 5873 |
else: |
| 5874 |
columns = (2, 1, 0) |
| 5875 |
for i in range(size): |
| 5876 |
# Red |
| 5877 |
if file_format == "eeColor" and not EECOLOR65 and i == size - 1: |
| 5878 |
# Last cLUT entry is fixed to 1.0 for eeColor and unchangeable |
| 5879 |
continue |
| 5880 |
RGB_triplet[columns[0]] = quantizer(step * i) |
| 5881 |
RGB_index[columns[0]] = i |
| 5882 |
for j in range(size): |
| 5883 |
# Green |
| 5884 |
if file_format == "eeColor" and not EECOLOR65 and j == size - 1: |
| 5885 |
# Last cLUT entry is fixed to 1.0 for eeColor and unchangeable |
| 5886 |
continue |
| 5887 |
RGB_triplet[columns[1]] = quantizer(step * j) |
| 5888 |
RGB_index[columns[1]] = j |
| 5889 |
for k in range(size): |
| 5890 |
# Blue |
| 5891 |
if self.thread_abort: |
| 5892 |
raise Info(lang.getstr("aborted")) |
| 5893 |
if file_format == "eeColor" and not EECOLOR65 and k == size - 1: |
| 5894 |
# Last cLUT entry is fixed to 1.0 for eeColor and unchangeable |
| 5895 |
continue |
| 5896 |
RGB_triplet[columns[2]] = quantizer(step * k) |
| 5897 |
RGB_oin.append(list(RGB_triplet)) |
| 5898 |
RGB_copy = list(RGB_triplet) |
| 5899 |
if file_format == "eeColor": |
| 5900 |
for l in range(3): |
| 5901 |
RGB_copy[l] = eeColor_to_VidRGB(RGB_copy[l]) |
| 5902 |
if input_encoding in ("t", "T"): |
| 5903 |
RGB_copy[l] = VidRGB_to_cLUT65(RGB_copy[l]) |
| 5904 |
RGB_index[columns[2]] = k |
| 5905 |
RGB_in.append(RGB_copy) |
| 5906 |
RGB_indexes.append(list(RGB_index)) |
| 5907 |
|
| 5908 |
# Lookup RGB -> RGB values through devicelink profile using icclu |
| 5909 |
# (Using icclu instead of xicclu because xicclu in versions |
| 5910 |
# prior to Argyll CMS 1.6.0 could not deal with devicelink profiles) |
| 5911 |
RGB_out = self.xicclu( |
| 5912 |
link_filename, RGB_in, scale=scale, use_icclu=True, logfile=logfiles |
| 5913 |
) |
| 5914 |
|
| 5915 |
if file_format == "eeColor" and output_encoding == "n": |
| 5916 |
RGBw = self.xicclu(link_filename, [[1, 1, 1]], use_icclu=True)[0] |
| 5917 |
|
| 5918 |
# Remove temporary files, move log file |
| 5919 |
result2 = self.wrapup(dst_path=path, ext_filter=[".log"]) |
| 5920 |
|
| 5921 |
if isinstance(result, Exception): |
| 5922 |
raise result |
| 5923 |
|
| 5924 |
valsep = " " |
| 5925 |
if file_format not in ("dcl", "png"): |
| 5926 |
lut = [[f"# Created with {APPNAME} {VERSION_STRING}"]] |
| 5927 |
linesep = "\n" |
| 5928 |
if file_format in ("3dl", "dcl"): |
| 5929 |
maxval = math.pow(2, output_bits) - 1 |
| 5930 |
if file_format == "3dl": |
| 5931 |
lut.append([f"# INPUT RANGE: {input_bits:d}"]) |
| 5932 |
lut.append([f"# OUTPUT RANGE: {output_bits:d}"]) |
| 5933 |
lut.append([]) |
| 5934 |
for i in range(size): |
| 5935 |
lut[-1].append(f"{quantizer(i * step):d}") |
| 5936 |
else: |
| 5937 |
# dcl |
| 5938 |
lut = [["# DeviceControl-LG 3D"]] |
| 5939 |
linesep = "\r\n" |
| 5940 |
for RGB_triplet in RGB_out: |
| 5941 |
lut.append([]) |
| 5942 |
for component in (0, 1, 2): |
| 5943 |
lut[-1].append( |
| 5944 |
f"{round(RGB_triplet[component] / scale * maxval):d}" |
| 5945 |
) |
| 5946 |
elif file_format == "cube": |
| 5947 |
if maxval is None: |
| 5948 |
maxval = 1.0 |
| 5949 |
lut.append([f"LUT_3D_SIZE {size:d}"]) |
| 5950 |
lut.append(["DOMAIN_MIN 0.0 0.0 0.0"]) |
| 5951 |
fp_offset = str(maxval).find(".") |
| 5952 |
domain_max = "DOMAIN_MAX {} {} {}".format( |
| 5953 |
*((f"{{:.{len(str(maxval)[fp_offset + 1 :]):d}f}}",) * 3) |
| 5954 |
) |
| 5955 |
lut.append([domain_max.format(*((maxval,) * 3))]) |
| 5956 |
lut.append([]) |
| 5957 |
for RGB_triplet in RGB_out: |
| 5958 |
lut.append([]) |
| 5959 |
for component in (0, 1, 2): |
| 5960 |
lut[-1].append(f"{RGB_triplet[component] * maxval:.6f}") |
| 5961 |
elif file_format == "spi3d": |
| 5962 |
if maxval is None: |
| 5963 |
maxval = 1.0 |
| 5964 |
lut = [["SPILUT 1.0"]] |
| 5965 |
lut.append(["3 3"]) |
| 5966 |
lut.append(["{:d} {:d} {:d}".format(*([size] * 3))]) |
| 5967 |
for i, RGB_triplet in enumerate(RGB_out): |
| 5968 |
lut.append([str(index) for index in RGB_indexes[i]]) |
| 5969 |
for component in (0, 1, 2): |
| 5970 |
lut[-1].append(f"{RGB_triplet[component] * maxval:.6f}") |
| 5971 |
elif file_format == "eeColor": |
| 5972 |
if maxval is None: |
| 5973 |
maxval = 1.0 |
| 5974 |
lut = [] |
| 5975 |
for i, RGB_triplet in enumerate(RGB_out): |
| 5976 |
lut.append([f"{component * maxval:.6f}" for component in RGB_oin[i]]) |
| 5977 |
for component in (0, 1, 2): |
| 5978 |
v = RGB_triplet[component] * maxval |
| 5979 |
if output_encoding == "n": |
| 5980 |
# For eeColor and full range RGB, make sure that the cLUT |
| 5981 |
# output maps to 1.0 |
| 5982 |
# The output curve will correct this |
| 5983 |
v /= RGBw[component] |
| 5984 |
v = min(v, 1) |
| 5985 |
v = VidRGB_to_eeColor(v) |
| 5986 |
lut[-1].append(f"{v:.6f}") |
| 5987 |
linesep = "\r\n" |
| 5988 |
elif file_format == "mga": |
| 5989 |
lut = [ |
| 5990 |
["#HEADER"], |
| 5991 |
[f"#filename: {os.path.basename(path)}"], |
| 5992 |
["#type: 3D cube file"], |
| 5993 |
["#format: 1.00"], |
| 5994 |
["#created: {}".format(strftime("%d %B %Y"))], |
| 5995 |
[f"#owner: {getpass.getuser()}"], |
| 5996 |
[f"#title: {os.path.splitext(os.path.basename(path))[0]}"], |
| 5997 |
["#END"], |
| 5998 |
] |
| 5999 |
lut.append([]) |
| 6000 |
lut.append(["channel 3d"]) |
| 6001 |
lut.append([f"in {size**3:d}"]) |
| 6002 |
maxval = 2**output_bits - 1 |
| 6003 |
lut.append([f"out {maxval + 1:d}"]) |
| 6004 |
lut.append([""]) |
| 6005 |
lut.append(["format lut"]) |
| 6006 |
lut.append([""]) |
| 6007 |
lut.append(["values\tred\tgreen\tblue"]) |
| 6008 |
for i, RGB_triplet in enumerate(RGB_out): |
| 6009 |
lut.append([f"{i:d}"]) |
| 6010 |
for component in (0, 1, 2): |
| 6011 |
lut[-1].append(f"{round(RGB_triplet[component] * maxval)}") |
| 6012 |
valsep = "\t" |
| 6013 |
elif file_format == "png": |
| 6014 |
lut = [[]] |
| 6015 |
if output_bits > 8: |
| 6016 |
# PNG only supports 8 and 16 bit |
| 6017 |
output_bits = 16 |
| 6018 |
maxval = 2**output_bits - 1 |
| 6019 |
for RGB_triplet in RGB_out: |
| 6020 |
if len(lut[-1]) == size: |
| 6021 |
# Append new scanline |
| 6022 |
lut.append([]) |
| 6023 |
lut[-1].append([round(v * maxval) for v in RGB_triplet]) |
| 6024 |
# Current layout is vertical |
| 6025 |
if getcfg("3dlut.image.layout") == "h": |
| 6026 |
# Change layout to horizontal |
| 6027 |
lutv = lut |
| 6028 |
lut = [[]] |
| 6029 |
for i in range(size): |
| 6030 |
if len(lut[-1]) == size**2: |
| 6031 |
# Append new scanline |
| 6032 |
lut.append([]) |
| 6033 |
for j in range(size): |
| 6034 |
lut[-1].extend(lutv[i + size * j]) |
| 6035 |
|
| 6036 |
if file_format != "png": |
| 6037 |
lut.append([]) |
| 6038 |
for i, line in enumerate(lut): |
| 6039 |
lut[i] = valsep.join(line) |
| 6040 |
result = linesep.join(lut) |
| 6041 |
|
| 6042 |
# Write 3DLUT |
| 6043 |
with open(path, "wb") as lut_file: |
| 6044 |
if file_format != "png": |
| 6045 |
lut_file.write(result.encode()) |
| 6046 |
else: |
| 6047 |
im = imfile.Image(lut, output_bits) |
| 6048 |
im.write(lut_file) |
| 6049 |
|
| 6050 |
if file_format == "eeColor": |
| 6051 |
# Write eeColor 1D LUTs |
| 6052 |
for i, color in enumerate(["red", "green", "blue"]): |
| 6053 |
for count, inout in [(1024, "first"), (8192, "second")]: |
| 6054 |
with open(f"{filename}-{inout}1d{color}.txt", "wb") as lut1d: |
| 6055 |
for j in range(count): |
| 6056 |
v = j / (count - 1.0) |
| 6057 |
if inout == "second" and output_encoding == "n": |
| 6058 |
# For eeColor and Full range RGB, unmap the |
| 6059 |
# cLUT output maps from 1.0 |
| 6060 |
v *= RGBw[i] |
| 6061 |
n_v = f"{v:.6f}\n" |
| 6062 |
lut1d.write(n_v.encode()) |
| 6063 |
|
| 6064 |
if isinstance(result2, Exception): |
| 6065 |
raise result2 |
| 6066 |
|
| 6067 |
def enumerate_displays_and_ports( |
| 6068 |
self, |
| 6069 |
silent=False, |
| 6070 |
check_lut_access=True, |
| 6071 |
enumerate_ports=True, |
| 6072 |
include_network_devices=True, |
| 6073 |
): |
| 6074 |
"""Enumerate the available displays and ports. |
| 6075 |
|
| 6076 |
Also sets Argyll version number, availability of certain options |
| 6077 |
like black point rate, and checks LUT access for each display. |
| 6078 |
|
| 6079 |
""" |
| 6080 |
if (silent and check_argyll_bin()) or (not silent and check_set_argyll_bin()): |
| 6081 |
displays = [] |
| 6082 |
xrandr_names = {} |
| 6083 |
lut_access = [] |
| 6084 |
if VERBOSE >= 1: |
| 6085 |
print(lang.getstr("enumerating_displays_and_comports")) |
| 6086 |
instruments = [] |
| 6087 |
current_display_name = config.get_display_name() |
| 6088 |
cfg_instruments = getcfg("instruments") |
| 6089 |
current_instrument = config.get_instrument_name() |
| 6090 |
if enumerate_ports: |
| 6091 |
cmd = get_argyll_util("dispcal") |
| 6092 |
else: |
| 6093 |
cmd = get_argyll_util("dispwin") |
| 6094 |
for instrument in cfg_instruments: |
| 6095 |
# Names are canonical from 1.1.4.7 onwards, but we may have |
| 6096 |
# verbose names from an old configuration |
| 6097 |
instrument = get_canonical_instrument_name(instrument) |
| 6098 |
if instrument.strip(): |
| 6099 |
instruments.append(instrument) |
| 6100 |
args = [] |
| 6101 |
if include_network_devices: |
| 6102 |
args.append("-dcc:?") |
| 6103 |
args.append("-?") |
| 6104 |
argyll_bin_dir = os.path.dirname(cmd) |
| 6105 |
if argyll_bin_dir != self.argyll_bin_dir: |
| 6106 |
self.argyll_bin_dir = argyll_bin_dir |
| 6107 |
print(self.argyll_bin_dir) |
| 6108 |
result = self.exec_cmd( |
| 6109 |
cmd, |
| 6110 |
args, |
| 6111 |
capture_output=True, |
| 6112 |
skip_scripts=True, |
| 6113 |
silent=True, |
| 6114 |
log_output=False, |
| 6115 |
) |
| 6116 |
if isinstance(result, Exception): |
| 6117 |
print(result) |
| 6118 |
arg = None |
| 6119 |
DEFAULTS["calibration.black_point_hack"] = 0 |
| 6120 |
DEFAULTS["calibration.black_point_rate.enabled"] = 0 |
| 6121 |
DEFAULTS["patterngenerator.prisma.argyll"] = 0 |
| 6122 |
n = -1 |
| 6123 |
self.display_rects = [] |
| 6124 |
non_standard_display_args = ("-dweb[:port]", "-dmadvr") |
| 6125 |
if TEST: |
| 6126 |
# Add dummy Chromecasts |
| 6127 |
self.output.append(" -dcc[:n]") |
| 6128 |
self.output.append(" 100 = '\xd4\xc7\xf3 Test A'") |
| 6129 |
self.output.append(" 101 = '\xd4\xc7\xf3 Test B'") |
| 6130 |
argyll_version_string = None |
| 6131 |
self.reset_argyll_enum() |
| 6132 |
for line in self.output: |
| 6133 |
if not isinstance(line, str): |
| 6134 |
continue |
| 6135 |
n += 1 |
| 6136 |
line = line.strip() |
| 6137 |
if argyll_version_string is None and "version" in line.lower(): |
| 6138 |
argyll_version_string = line[line.lower().find("version") + 8 :] |
| 6139 |
if argyll_version_string != self.argyll_version_string: |
| 6140 |
self.set_argyll_version_from_string(argyll_version_string) |
| 6141 |
print(f"ArgyllCMS {self.argyll_version_string}") |
| 6142 |
DEFAULTS["copyright"] = ( |
| 6143 |
f"No copyright. Created with {APPNAME} {VERSION_STRING} and " |
| 6144 |
f"Argyll CMS {argyll_version_string}" |
| 6145 |
) |
| 6146 |
|
| 6147 |
if self.argyll_version > [1, 0, 4]: |
| 6148 |
# Rate of blending from neutral to black point. |
| 6149 |
DEFAULTS["calibration.black_point_rate.enabled"] = 1 |
| 6150 |
|
| 6151 |
if ( |
| 6152 |
self.argyll_version >= [1, 7] |
| 6153 |
and "Beta" not in self.argyll_version_string |
| 6154 |
): |
| 6155 |
# Forced black point hack available |
| 6156 |
# (Argyll CMS 1.7) |
| 6157 |
DEFAULTS["calibration.black_point_hack"] = 1 |
| 6158 |
|
| 6159 |
# TODO: OBSERVERS should include 2012_2 and 2012_10 already. |
| 6160 |
if self.argyll_version >= [1, 9, 4]: |
| 6161 |
if self.argyll_version < [3, 4, 0]: |
| 6162 |
# Add CIE 2012 observers |
| 6163 |
valid_observers = natsort([*OBSERVERS, "2012_2", "2012_10"]) |
| 6164 |
else: |
| 6165 |
# Add CIE 2015 observers (renamed from "2012_*" in |
| 6166 |
# ArgyllCMS 3.4.0; migrate any stored "2012_*" values |
| 6167 |
# so they don't silently fall back to the default |
| 6168 |
# "1931_2" observer and produce wrong results). |
| 6169 |
valid_observers = natsort([*OBSERVERS, "2015_2", "2015_10"]) |
| 6170 |
observer_rename = {"2012_2": "2015_2", "2012_10": "2015_10"} |
| 6171 |
else: |
| 6172 |
valid_observers = OBSERVERS |
| 6173 |
for key in [ |
| 6174 |
"{}", |
| 6175 |
"colorimeter_correction.{}", |
| 6176 |
"colorimeter_correction.{}.reference", |
| 6177 |
]: |
| 6178 |
key = key.format("observer") |
| 6179 |
config.VALID_VALUES[key] = valid_observers |
| 6180 |
if self.argyll_version >= [3, 4, 0]: |
| 6181 |
stored = getcfg(key, fallback=False, raw=True) |
| 6182 |
if stored in observer_rename: |
| 6183 |
setcfg(key, observer_rename[stored]) |
| 6184 |
continue |
| 6185 |
line = line.split(None, 1) |
| 6186 |
if len(line) and line[0][0] == "-": |
| 6187 |
arg = line[0] |
| 6188 |
value = line[-1].split(None, 1)[0] |
| 6189 |
if arg == "-d" and not value.startswith("n"): |
| 6190 |
# Argyll 2.0.2 started listing -d madvr and -d dummy |
| 6191 |
# instead of -dmadvr and -ddummy |
| 6192 |
# Use the non-space-delimited as the canonical form |
| 6193 |
arg += value |
| 6194 |
if arg == "-A": |
| 6195 |
# Rate of blending from neutral to black point. |
| 6196 |
DEFAULTS["calibration.black_point_rate.enabled"] = 1 |
| 6197 |
elif arg in non_standard_display_args: |
| 6198 |
displays.append(arg) |
| 6199 |
elif arg == "-b" and not line[-1].startswith("bright"): |
| 6200 |
# Forced black point hack available |
| 6201 |
# (Argyll CMS 1.7b 2014-12-22) |
| 6202 |
DEFAULTS["calibration.black_point_hack"] = 1 |
| 6203 |
elif arg == "-dprisma[:host]": |
| 6204 |
DEFAULTS["patterngenerator.prisma.argyll"] = 1 |
| 6205 |
elif arg in ("-dvirtual", "-ddummy"): |
| 6206 |
# Custom modified Argyll V2.0.2 (-dvirtual) |
| 6207 |
# or Argyll >= 2.0.2 (-d dummy) |
| 6208 |
self.argyll_virtual_display = arg[2:] |
| 6209 |
print("Argyll has virtual display support") |
| 6210 |
elif len(line) > 1 and line[1][0] == "=": |
| 6211 |
value = line[1].strip(" ='") |
| 6212 |
if arg == "-d": |
| 6213 |
# Standard displays |
| 6214 |
match = re.findall( |
| 6215 |
r"(.+?),? at (-?\d+), (-?\d+), width (\d+), height (\d+)", |
| 6216 |
value, |
| 6217 |
) |
| 6218 |
if len(match): |
| 6219 |
xrandr_name = re.search(r", Output (.+)", match[0][0]) |
| 6220 |
if xrandr_name: |
| 6221 |
xrandr_names[len(displays)] = xrandr_name.group(1) |
| 6222 |
display = "{} @ {}, {}, {}x{}".format(*match[0]) |
| 6223 |
if " ".join(value.split()[-2:]) == "(Primary Display)": |
| 6224 |
display += " [PRIMARY]" |
| 6225 |
displays.append(display) |
| 6226 |
self.display_rects.append( |
| 6227 |
wx.Rect(*[int(item) for item in match[0][1:]]) |
| 6228 |
) |
| 6229 |
elif arg == "-dcc[:n]": |
| 6230 |
# Chromecast |
| 6231 |
if value: |
| 6232 |
# Note the Chromecast name may be mangled due |
| 6233 |
# to being UTF-8 encoded, but commandline output |
| 6234 |
# will always be decoded to Unicode using the |
| 6235 |
# stdout encoding, which may not be UTF-8 |
| 6236 |
# (e.g. under Windows). We can recover characters |
| 6237 |
# valid in both UTF-8 and stdout encoding |
| 6238 |
# by a re-encode/decode step |
| 6239 |
displays.append( |
| 6240 |
f"Chromecast {line[0]}: {safe_str(value, ENC)}" |
| 6241 |
) |
| 6242 |
elif arg == "-dprisma[:host]": |
| 6243 |
# Prisma (via Argyll CMS) |
| 6244 |
# <serial no>: <name> @ <ip> |
| 6245 |
# 141550000000: prisma-0000 @ 172.31.31.162 |
| 6246 |
match = re.findall(r".+?: (.+) @ (.+)", value) |
| 6247 |
if len(match): |
| 6248 |
displays.append( |
| 6249 |
f"Prisma {line[0]}: {safe_str(match[0][0], ENC)} " |
| 6250 |
f"@ {match[0][1]}" |
| 6251 |
) |
| 6252 |
elif arg == "-c" and enumerate_ports: |
| 6253 |
if ( |
| 6254 |
re.match(r"/dev(?:/[\w.\-]+)*$", value) |
| 6255 |
or re.match(r"COM\d+$", value) |
| 6256 |
) and getcfg("skip_legacy_serial_ports"): |
| 6257 |
# Skip all legacy serial ports (this means we |
| 6258 |
# deliberately don't support DTP92 and |
| 6259 |
# Spectrolino, although they may work when |
| 6260 |
# used with a serial to USB adaptor) |
| 6261 |
continue |
| 6262 |
value = value.split(None, 1) |
| 6263 |
if len(value) > 1: |
| 6264 |
value = value[1].split("'", 1)[0].strip("()") |
| 6265 |
else: |
| 6266 |
value = value[0] |
| 6267 |
value = get_canonical_instrument_name(value) |
| 6268 |
instruments.append(value) |
| 6269 |
if TEST: |
| 6270 |
inames = list(all_instruments.keys()) |
| 6271 |
inames.sort() |
| 6272 |
for iname in inames: |
| 6273 |
iname = get_canonical_instrument_name(iname) |
| 6274 |
if iname not in instruments: |
| 6275 |
instruments.append(iname) |
| 6276 |
if VERBOSE >= 1: |
| 6277 |
print(lang.getstr("success")) |
| 6278 |
if instruments != self.instruments: |
| 6279 |
self.instruments = instruments |
| 6280 |
setcfg("instruments", instruments) |
| 6281 |
if ( |
| 6282 |
current_instrument != self.get_instrument_name() |
| 6283 |
and current_instrument in instruments |
| 6284 |
): |
| 6285 |
setcfg("comport.number", instruments.index(current_instrument) + 1) |
| 6286 |
if displays != self._displays: |
| 6287 |
self._displays = list(displays) |
| 6288 |
setcfg("displays", displays) |
| 6289 |
if real_display_size_mm: |
| 6290 |
# Sync with Argyll - needed under Linux to map EDID |
| 6291 |
real_display_size_mm.enumerate_displays() |
| 6292 |
displays = [ |
| 6293 |
display |
| 6294 |
for display in displays |
| 6295 |
if display not in non_standard_display_args |
| 6296 |
] |
| 6297 |
self.display_edid = [] |
| 6298 |
self.display_manufacturers = [] |
| 6299 |
self.display_names = [] |
| 6300 |
if sys.platform == "win32": |
| 6301 |
# The ordering will work as long |
| 6302 |
# as Argyll continues using |
| 6303 |
# EnumDisplayMonitors |
| 6304 |
try: |
| 6305 |
monitors = util_win.get_real_display_devices_info() |
| 6306 |
except Exception as exception: |
| 6307 |
if not isinstance(exception, pywintypes.error): |
| 6308 |
print(traceback.format_exc()) |
| 6309 |
monitors = [] |
| 6310 |
for i, display in enumerate(displays): |
| 6311 |
if display.startswith(("Chromecast ", "Prisma ")): |
| 6312 |
self.display_edid.append({}) |
| 6313 |
if display.startswith("Prisma "): |
| 6314 |
display_manufacturer = "Q, Inc" |
| 6315 |
else: |
| 6316 |
display_manufacturer = "Google" |
| 6317 |
self.display_manufacturers.append(display_manufacturer) |
| 6318 |
self.display_names.append(display.split(":", 1)[1].strip()) |
| 6319 |
continue |
| 6320 |
display_name = split_display_name(display) |
| 6321 |
# Make sure we have nice descriptions |
| 6322 |
desc = [] |
| 6323 |
if sys.platform == "win32" and i < len(monitors): |
| 6324 |
# Get monitor description using win32api |
| 6325 |
device = util_win.get_active_display_device( |
| 6326 |
monitors[i]["Device"] |
| 6327 |
) |
| 6328 |
if device: |
| 6329 |
desc.append(device.DeviceString) |
| 6330 |
# Deal with HiDPI - update monitor rect |
| 6331 |
m_left, m_top, m_right, m_bottom = monitors[i]["Monitor"] |
| 6332 |
m_width = m_right - m_left |
| 6333 |
m_height = m_bottom - m_top |
| 6334 |
self.display_rects[i] = wx.Rect( |
| 6335 |
m_left, m_top, m_width, m_height |
| 6336 |
) |
| 6337 |
is_primary = " [PRIMARY]" in display |
| 6338 |
display = " @ ".join( |
| 6339 |
[ |
| 6340 |
display_name, |
| 6341 |
f"{m_left:d}, {m_top:d}, {m_width:d}x{m_height:d}", |
| 6342 |
] |
| 6343 |
) |
| 6344 |
if is_primary: |
| 6345 |
display += " [PRIMARY]" |
| 6346 |
# Get monitor descriptions from EDID |
| 6347 |
try: |
| 6348 |
# Important: display_name must be given for get_edid |
| 6349 |
# under Mac OS X, but it doesn't hurt to always |
| 6350 |
# include it |
| 6351 |
edid = get_edid(i, display_name) |
| 6352 |
except Exception as exception: |
| 6353 |
suppress_errors = (SystemError, TypeError, ValueError, WMIError) |
| 6354 |
if sys.platform == "win32": |
| 6355 |
suppress_errors += (pywintypes.error,) |
| 6356 |
if isinstance(exception, EnvironmentError): |
| 6357 |
print(exception) |
| 6358 |
elif not isinstance(exception, suppress_errors): |
| 6359 |
print(traceback.format_exc()) |
| 6360 |
edid = {} |
| 6361 |
self.display_edid.append(edid) |
| 6362 |
if edid: |
| 6363 |
manufacturer = edid.get("manufacturer", "").split() |
| 6364 |
monitor = edid.get( |
| 6365 |
"monitor_name", |
| 6366 |
edid.get("ascii", str(edid["product_id"] or "")), |
| 6367 |
) |
| 6368 |
if ( |
| 6369 |
monitor in ("Color LCD", "iMac") |
| 6370 |
and edid["manufacturer_id"] == "APP" |
| 6371 |
and sys.platform == "darwin" |
| 6372 |
): |
| 6373 |
# Get mac model if internal display |
| 6374 |
model_id = get_model_id() |
| 6375 |
if model_id: |
| 6376 |
# Override monitor name |
| 6377 |
monitor = model_id |
| 6378 |
# Override EDID |
| 6379 |
edid["monitor_name"] = monitor |
| 6380 |
if monitor and monitor not in "".join(desc): |
| 6381 |
desc = [monitor] |
| 6382 |
else: |
| 6383 |
manufacturer = [] |
| 6384 |
if sys.platform == "darwin" and i < len(self.display_rects): |
| 6385 |
rect = self.display_rects[i] |
| 6386 |
sp_name = get_display_name_from_system_profiler( |
| 6387 |
rect.width, rect.height |
| 6388 |
) |
| 6389 |
if sp_name: |
| 6390 |
if sp_name in ("Color LCD", "iMac"): |
| 6391 |
model_id = get_model_id() |
| 6392 |
if model_id: |
| 6393 |
sp_name = model_id |
| 6394 |
desc = [sp_name] |
| 6395 |
if desc and desc[-1] not in display: |
| 6396 |
# Only replace the description if it not already |
| 6397 |
# contains the monitor model |
| 6398 |
display = " @".join([" ".join(desc), display.split("@")[-1]]) |
| 6399 |
displays[i] = display |
| 6400 |
self.display_manufacturers.append(" ".join(manufacturer)) |
| 6401 |
self.display_names.append(split_display_name(display)) |
| 6402 |
if self.argyll_version >= [1, 4, 0]: |
| 6403 |
displays.append("Web @ localhost") |
| 6404 |
self.display_edid.append({}) |
| 6405 |
self.display_manufacturers.append("") |
| 6406 |
self.display_names.append("Web") |
| 6407 |
if self.argyll_version >= [1, 6, 0]: |
| 6408 |
displays.append("madVR") |
| 6409 |
self.display_edid.append({}) |
| 6410 |
self.display_manufacturers.append("") |
| 6411 |
self.display_names.append("madVR") |
| 6412 |
# Prisma (via DisplayCAL) |
| 6413 |
displays.append("Prisma") |
| 6414 |
self.display_edid.append({}) |
| 6415 |
self.display_manufacturers.append("Q, Inc") |
| 6416 |
self.display_names.append("Prisma") |
| 6417 |
# Resolve |
| 6418 |
displays.append("Resolve") |
| 6419 |
self.display_edid.append({}) |
| 6420 |
self.display_manufacturers.append("DaVinci") |
| 6421 |
self.display_names.append("Resolve") |
| 6422 |
# Untethered |
| 6423 |
displays.append("Untethered") |
| 6424 |
self.display_edid.append({}) |
| 6425 |
self.display_manufacturers.append("") |
| 6426 |
self.display_names.append("Untethered") |
| 6427 |
# - |
| 6428 |
self.displays = displays |
| 6429 |
setcfg("displays", displays) |
| 6430 |
if ( |
| 6431 |
current_display_name != config.get_display_name() |
| 6432 |
and current_display_name in self.display_names |
| 6433 |
): |
| 6434 |
setcfg( |
| 6435 |
"display.number", |
| 6436 |
self.display_names.index(current_display_name) + 1, |
| 6437 |
) |
| 6438 |
# Filter out Prisma (via DisplayCAL), Resolve and Untethered |
| 6439 |
# IMPORTANT: Also make changes to display filtering in |
| 6440 |
# worker.Worker.has_separate_lut_access |
| 6441 |
displays = displays[:-3] |
| 6442 |
if self.argyll_version >= [1, 6, 0]: |
| 6443 |
# Filter out madVR |
| 6444 |
displays = displays[:-1] |
| 6445 |
if self.argyll_version >= [1, 4, 0]: |
| 6446 |
# Filter out Web @ localhost |
| 6447 |
displays = displays[:-1] |
| 6448 |
if check_lut_access: |
| 6449 |
dispwin = get_argyll_util("dispwin") |
| 6450 |
test_cal = get_data_path("test.cal") |
| 6451 |
if not test_cal: |
| 6452 |
print(lang.getstr("file.missing", "test.cal")) |
| 6453 |
tmp = self.create_tempdir() |
| 6454 |
if isinstance(tmp, Exception): |
| 6455 |
print(tmp) |
| 6456 |
tmp = None |
| 6457 |
for i, disp in enumerate(displays): |
| 6458 |
if disp.startswith(("Chromecast ", "Prisma ")) or not test_cal: |
| 6459 |
lut_access.append(None) |
| 6460 |
continue |
| 6461 |
if sys.platform == "darwin": |
| 6462 |
# There's no easy way to check LUT access under |
| 6463 |
# Mac OS X because loading a LUT isn't persistent |
| 6464 |
# unless you run as root. Just assume we have |
| 6465 |
# access to all displays. |
| 6466 |
lut_access.append(True) |
| 6467 |
continue |
| 6468 |
if VERBOSE >= 1: |
| 6469 |
print(lang.getstr("checking_lut_access", (i + 1))) |
| 6470 |
# Save current calibration? |
| 6471 |
if tmp: |
| 6472 |
current_cal = os.path.join(tmp, "current.cal") |
| 6473 |
tmp_cal = current_cal |
| 6474 |
result = self.save_current_video_lut( |
| 6475 |
i + 1, current_cal, silent=True |
| 6476 |
) |
| 6477 |
# Load test.cal |
| 6478 |
result = self.exec_cmd( |
| 6479 |
dispwin, |
| 6480 |
[f"-d{i + 1}", "-c", test_cal], |
| 6481 |
capture_output=True, |
| 6482 |
skip_scripts=True, |
| 6483 |
silent=True, |
| 6484 |
) |
| 6485 |
if isinstance(result, Exception): |
| 6486 |
print(result) |
| 6487 |
elif result is None: |
| 6488 |
lut_access.append(None) |
| 6489 |
continue |
| 6490 |
# Check if LUT == test.cal |
| 6491 |
result = self.exec_cmd( |
| 6492 |
dispwin, |
| 6493 |
[f"-d{(i + 1)}", "-V", test_cal], |
| 6494 |
capture_output=True, |
| 6495 |
skip_scripts=True, |
| 6496 |
silent=True, |
| 6497 |
) |
| 6498 |
if isinstance(result, Exception): |
| 6499 |
print(result) |
| 6500 |
elif result is None: |
| 6501 |
lut_access.append(None) |
| 6502 |
continue |
| 6503 |
retcode = -1 |
| 6504 |
for line in self.output: |
| 6505 |
if line.find("IS loaded") >= 0: |
| 6506 |
retcode = 0 |
| 6507 |
break |
| 6508 |
# Reset LUT & (re-)load previous cal (if any) |
| 6509 |
if not tmp or not os.path.isfile(current_cal): |
| 6510 |
current_cal = self.get_dispwin_display_profile_argument(i) |
| 6511 |
result = self.exec_cmd( |
| 6512 |
dispwin, |
| 6513 |
[f"-d{i + 1}", "-c", current_cal], |
| 6514 |
capture_output=True, |
| 6515 |
skip_scripts=True, |
| 6516 |
silent=True, |
| 6517 |
) |
| 6518 |
if isinstance(result, Exception): |
| 6519 |
print(result) |
| 6520 |
if tmp and os.path.isfile(tmp_cal): |
| 6521 |
try: |
| 6522 |
os.remove(tmp_cal) |
| 6523 |
except OSError as exception: |
| 6524 |
print(exception) |
| 6525 |
lut_access.append(retcode == 0) |
| 6526 |
if VERBOSE >= 1: |
| 6527 |
if retcode == 0: |
| 6528 |
print(lang.getstr("success")) |
| 6529 |
else: |
| 6530 |
print(lang.getstr("failure")) |
| 6531 |
else: |
| 6532 |
lut_access.extend([None] * len(displays)) |
| 6533 |
if self.argyll_version >= [1, 4, 0]: |
| 6534 |
# Web @ localhost |
| 6535 |
lut_access.append(False) |
| 6536 |
if self.argyll_version >= [1, 6, 0]: |
| 6537 |
# madVR |
| 6538 |
lut_access.append(True) |
| 6539 |
# Prisma (via DisplayCAL) |
| 6540 |
lut_access.append(False) |
| 6541 |
# Resolve |
| 6542 |
lut_access.append(False) |
| 6543 |
# Untethered |
| 6544 |
lut_access.append(False) |
| 6545 |
self.lut_access = lut_access |
| 6546 |
elif silent or not check_argyll_bin(): |
| 6547 |
self.clear_argyll_info() |
| 6548 |
|
| 6549 |
def exec_cmd( |
| 6550 |
self, |
| 6551 |
cmd, |
| 6552 |
args=None, |
| 6553 |
capture_output=False, |
| 6554 |
display_output=False, |
| 6555 |
low_contrast=True, |
| 6556 |
skip_scripts=False, |
| 6557 |
silent=False, |
| 6558 |
parent=None, |
| 6559 |
asroot=False, |
| 6560 |
log_output=True, |
| 6561 |
title=APPNAME, |
| 6562 |
shell=False, |
| 6563 |
working_dir=None, |
| 6564 |
dry_run=None, |
| 6565 |
sessionlogfile=None, |
| 6566 |
use_pty=False, |
| 6567 |
): |
| 6568 |
"""Execute a command. |
| 6569 |
|
| 6570 |
Return value is either True (succeed), False (failed), None (canceled) |
| 6571 |
or an exception. |
| 6572 |
|
| 6573 |
Args: |
| 6574 |
cmd (str): the full path of the command. |
| 6575 |
args (list[str]): The arguments, if any. |
| 6576 |
capture_output (bool): If True, swallows any output from the |
| 6577 |
command and sets the 'output' and 'errors' properties of the |
| 6578 |
Worker instance. |
| 6579 |
display_output (bool): Shows the log after the command. |
| 6580 |
low_contrast (bool): If True sets low contrast shell colors while |
| 6581 |
the command is run. |
| 6582 |
skip_scripts (bool): If True, skips the creation of shell scripts |
| 6583 |
that allow re-running the command. Note that this is also |
| 6584 |
controlled by a global config option and scripts will only be |
| 6585 |
created if it evaluates to False. |
| 6586 |
silent (bool): If True, skips most output and also most error |
| 6587 |
dialogs (except unexpected failures). |
| 6588 |
parent (): Sets the parent window for auth dialog (if asroot is |
| 6589 |
True). |
| 6590 |
asroot (bool): If True, on Linux runs the command using sudo. |
| 6591 |
log_output (bool): If True, logs any output if capture_output is |
| 6592 |
also set. |
| 6593 |
title (str): Title for auth dialog (if asroot is True). |
| 6594 |
shell (bool): If True, runs the command in a shell. |
| 6595 |
working_dir (str): Working directory. If None, will be determined |
| 6596 |
from absulte path of last argument and last argument will be |
| 6597 |
set to only the basename. If False, no working dir will be used |
| 6598 |
and file arguments not changed. |
| 6599 |
dry_run (bool): If True, does not run the command, but returns. |
| 6600 |
sessionlogfile (str): If not None, the session log file to write. |
| 6601 |
use_pty (bool): If True, uses a pseudo terminal to run the command. |
| 6602 |
""" |
| 6603 |
if args is None: |
| 6604 |
args = [] |
| 6605 |
|
| 6606 |
# convert all args to str if any are bytes |
| 6607 |
for i, arg in enumerate(args): |
| 6608 |
if isinstance(arg, bytes): |
| 6609 |
args[i] = arg.decode("utf-8") |
| 6610 |
|
| 6611 |
# If dry_run is explicitly set to False, ignore dry_run config value |
| 6612 |
dry_run = dry_run is not False and (dry_run or getcfg("dry_run")) |
| 6613 |
if not capture_output: |
| 6614 |
capture_output = False |
| 6615 |
if sys.stdout and hasattr(sys.stdout, "isatty") and not sys.stdout.isatty(): |
| 6616 |
capture_output = True |
| 6617 |
|
| 6618 |
self.clear_cmd_output() |
| 6619 |
if None in [cmd, args]: |
| 6620 |
if VERBOSE >= 1 and not silent: |
| 6621 |
print(lang.getstr("aborted")) |
| 6622 |
return False |
| 6623 |
self.cmd = cmd |
| 6624 |
cmdname = os.path.splitext(os.path.basename(cmd))[0] |
| 6625 |
self.cmdname = cmdname |
| 6626 |
if "-?" not in args and cmdname == get_argyll_utilname("dispwin"): |
| 6627 |
if "-I" in args or "-U" in args: |
| 6628 |
if "-Sl" in args or "-Sn" in args: |
| 6629 |
# Root is required if installing a profile to a system |
| 6630 |
# location |
| 6631 |
asroot = True |
| 6632 |
elif "-s" not in args and not self.calibration_loading_generally_supported: |
| 6633 |
# Loading/clearing calibration not supported |
| 6634 |
# Don't actually do it, pretend we were successful |
| 6635 |
if "-V" in args: |
| 6636 |
self.output.append("IS loaded") |
| 6637 |
self.retcode = 0 |
| 6638 |
return True |
| 6639 |
if asroot: |
| 6640 |
silent = False |
| 6641 |
measure_cmds = ( |
| 6642 |
get_argyll_utilname("dispcal"), |
| 6643 |
get_argyll_utilname("dispread"), |
| 6644 |
get_argyll_utilname("spotread"), |
| 6645 |
) |
| 6646 |
process_cmds = ( |
| 6647 |
get_argyll_utilname("collink"), |
| 6648 |
get_argyll_utilname("colprof"), |
| 6649 |
get_argyll_utilname("targen"), |
| 6650 |
) |
| 6651 |
# Run commands through wexpect.spawn instead of subprocess.Popen if |
| 6652 |
# any of these conditions apply |
| 6653 |
use_pty = ( |
| 6654 |
args |
| 6655 |
and "-?" not in args |
| 6656 |
and (use_pty or cmdname in measure_cmds + process_cmds) |
| 6657 |
) |
| 6658 |
self.measure_cmd = "-?" not in args and cmdname in measure_cmds |
| 6659 |
report_current_cal = cmdname == get_argyll_utilname("dispcal") and ( |
| 6660 |
"-r" in args or "-z" in args |
| 6661 |
) |
| 6662 |
if self.measure_cmd and not dry_run and sys.platform not in ("darwin", "win32"): |
| 6663 |
# Inhibit session to prevent screensaver/powersaving etc. |
| 6664 |
# Useful commands to figure out list of DBus interfaces: |
| 6665 |
# dbus-send [--session|--system] \ |
| 6666 |
# --dest=org.freedesktop.DBus \ |
| 6667 |
# --type=method_call \ |
| 6668 |
# --print-reply \ |
| 6669 |
# /org/freedesktop/DBus \ |
| 6670 |
# org.freedesktop.DBus.ListNames |
| 6671 |
if dbus_session: |
| 6672 |
desktop = os.getenv("XDG_CURRENT_DESKTOP", "").split(":") |
| 6673 |
inhibit_reason = "Display device measurements" |
| 6674 |
gnome_sm = "org.gnome.SessionManager" |
| 6675 |
gnome_sm_xid = 0 |
| 6676 |
# GNOME SessionManager.Inhibit flags: |
| 6677 |
# 1 Inhibit logging out |
| 6678 |
# 2 Inhibit user switching |
| 6679 |
# 4 Inhibit suspending |
| 6680 |
# 8 Inhibit idle |
| 6681 |
gnome_sm_flags = 1 | 2 | 4 | 8 |
| 6682 |
ifaces = getattr(self, "dbus_ifaces", None) |
| 6683 |
if not ifaces: |
| 6684 |
ifaces = { |
| 6685 |
gnome_sm: { |
| 6686 |
"args": ( |
| 6687 |
gnome_sm_xid, |
| 6688 |
inhibit_reason, |
| 6689 |
gnome_sm_flags, |
| 6690 |
), |
| 6691 |
"uninhibit": "uninhibit", |
| 6692 |
}, |
| 6693 |
"org.freedesktop.ScreenSaver": {"precedence": [gnome_sm]}, |
| 6694 |
"org.freedesktop.PowerManagement.Inhibit": { |
| 6695 |
"precedence": [gnome_sm] |
| 6696 |
}, |
| 6697 |
} |
| 6698 |
self.dbus_ifaces = ifaces |
| 6699 |
for bus_name in ifaces: |
| 6700 |
iface_dict = ifaces[bus_name] |
| 6701 |
if bus_name.startswith("org.freedesktop."): |
| 6702 |
skip = False |
| 6703 |
for precedence in iface_dict.get("precedence", []): |
| 6704 |
if ifaces[precedence].get("cookie"): |
| 6705 |
# Already took care of inhibit |
| 6706 |
skip = True |
| 6707 |
break |
| 6708 |
if skip: |
| 6709 |
continue |
| 6710 |
else: |
| 6711 |
iface_domain = bus_name.split(".")[1] |
| 6712 |
if iface_domain.upper() not in desktop: |
| 6713 |
# Not current desktop environment |
| 6714 |
continue |
| 6715 |
object_path = "/" + bus_name.replace(".", "/") |
| 6716 |
other_path = iface_dict.get("path") |
| 6717 |
if other_path: |
| 6718 |
if other_path.startswith("/"): |
| 6719 |
object_path = other_path |
| 6720 |
else: |
| 6721 |
object_path += "/" + other_path |
| 6722 |
if iface_dict.get("cookie"): |
| 6723 |
continue |
| 6724 |
try: |
| 6725 |
iface = iface_dict.get("iface") |
| 6726 |
if not iface: |
| 6727 |
iface = DBusObject(BUSTYPE_SESSION, bus_name, object_path) |
| 6728 |
cookie = iface.inhibit( |
| 6729 |
APPNAME, *iface_dict.get("args", (inhibit_reason,)) |
| 6730 |
) |
| 6731 |
except DBusException as exception: |
| 6732 |
# The user might be running a minimal Wayland environment |
| 6733 |
# without a screensaver or power management daemon |
| 6734 |
self.log( |
| 6735 |
f"{APPNAME}: Warning - could not inhibit " |
| 6736 |
f"{bus_name}: {exception}" |
| 6737 |
) |
| 6738 |
continue # Skip to the next interface |
| 6739 |
iface_dict["iface"] = iface |
| 6740 |
iface_dict["cookie"] = cookie |
| 6741 |
self.log(f"{APPNAME}: Inhibited {bus_name}") |
| 6742 |
else: |
| 6743 |
self.log( |
| 6744 |
f"{APPNAME}: Warning - no D-Bus session bus - " |
| 6745 |
"cannot inhibit session, screensaver/powersaving may " |
| 6746 |
"still be active!" |
| 6747 |
) |
| 6748 |
profiling_inhibit = False |
| 6749 |
display_profile = None |
| 6750 |
if ( |
| 6751 |
sys.platform not in ("darwin", "win32") |
| 6752 |
and self.measure_cmd |
| 6753 |
and self._use_patternwindow |
| 6754 |
and not dry_run |
| 6755 |
and not report_current_cal |
| 6756 |
): |
| 6757 |
# Preliminary Wayland support. This still needs a lot |
| 6758 |
# of work as Argyll doesn't support Wayland natively yet, |
| 6759 |
# so we use virtual display to drive our own patch window. |
| 6760 |
# We need to make sure videoLUT is linear. Only way to |
| 6761 |
# achieve this currently under Wayland is by using colord. |
| 6762 |
|
| 6763 |
# Inhibit display device to reset videoLUT to linear and profile |
| 6764 |
# to none |
| 6765 |
device_id = self.get_device_id(query=True) |
| 6766 |
object_path = None |
| 6767 |
if device_id: |
| 6768 |
try: |
| 6769 |
object_path = colord.get_object_path(device_id, "device") |
| 6770 |
except colord.CDError as exception: |
| 6771 |
self.log(exception) |
| 6772 |
else: |
| 6773 |
self.log( |
| 6774 |
f"{APPNAME}: Warning - couldn't get display device ID - " |
| 6775 |
"cannot inhibit display device!" |
| 6776 |
) |
| 6777 |
if dbus_system and object_path: |
| 6778 |
# Use DBus interface to call ProfilingInhibit() |
| 6779 |
try: |
| 6780 |
cd_device = colord.Device(object_path) |
| 6781 |
cd_device.profiling_inhibit() |
| 6782 |
except (colord.CDError, DBusException) as exception: |
| 6783 |
self.log(f"{APPNAME}: Warning - Handled exception: {exception}") |
| 6784 |
else: |
| 6785 |
profiling_inhibit = True |
| 6786 |
self.log(f"{APPNAME}: Inhibited display device", object_path) |
| 6787 |
elif object_path: |
| 6788 |
self.log( |
| 6789 |
f"{APPNAME}: Warning - no D-Bus system bus - " |
| 6790 |
"cannot inhibit display device!" |
| 6791 |
) |
| 6792 |
if not profiling_inhibit: |
| 6793 |
# Fallback - install linear cal sRGB profile |
| 6794 |
self.log(f"{APPNAME}: Temporarily installing sRGB profile...") |
| 6795 |
display_profile = config.get_display_profile() |
| 6796 |
self.srgb = srgb = ICCProfile.from_named_rgb_space("sRGB") |
| 6797 |
# Date should not change so the ID stays the same. |
| 6798 |
srgb.dateTime = datetime.datetime(2003, 0o1, 23, 0, 0, 0) |
| 6799 |
srgb.tags.vcgt = VideoCardGammaTableType("", "vcgt") |
| 6800 |
srgb.tags.vcgt.update( |
| 6801 |
{ |
| 6802 |
"channels": 3, |
| 6803 |
"entryCount": 256, |
| 6804 |
"entrySize": 1, |
| 6805 |
"data": [ |
| 6806 |
list(range(256)), |
| 6807 |
list(range(256)), |
| 6808 |
list(range(256)), |
| 6809 |
], |
| 6810 |
} |
| 6811 |
) |
| 6812 |
srgb.setDescription(f"{APPNAME} Linear Calibration sRGB Profile") |
| 6813 |
srgb.calculate_id() |
| 6814 |
srgb.write( |
| 6815 |
os.path.join( |
| 6816 |
self.tempdir, f"{APPNAME} Linear Calibration sRGB Profile.icc" |
| 6817 |
) |
| 6818 |
) |
| 6819 |
cdinstall = self._attempt_install_profile_colord(srgb) |
| 6820 |
if not cdinstall: |
| 6821 |
return Error(lang.getstr("calibration.reset_error")) |
| 6822 |
if isinstance(cdinstall, Exception): |
| 6823 |
return UnloggedError(safe_str(cdinstall)) |
| 6824 |
self.log(f"{APPNAME}: Successfully assigned sRGB profile") |
| 6825 |
self.use_patterngenerator = ( |
| 6826 |
self.measure_cmd |
| 6827 |
and cmdname != get_argyll_utilname("spotread") |
| 6828 |
and ( |
| 6829 |
config.get_display_name() == "Resolve" |
| 6830 |
or ( |
| 6831 |
config.get_display_name() == "Prisma" |
| 6832 |
and not DEFAULTS["patterngenerator.prisma.argyll"] |
| 6833 |
) |
| 6834 |
or self._use_patternwindow |
| 6835 |
) |
| 6836 |
) |
| 6837 |
use_3dlut_override = ( |
| 6838 |
( |
| 6839 |
( |
| 6840 |
self.use_patterngenerator |
| 6841 |
and config.get_display_name(None, True) == "Prisma" |
| 6842 |
) |
| 6843 |
or ( |
| 6844 |
config.get_display_name(None, True) == "madVR" |
| 6845 |
and (sys.platform != "win32" or not getcfg("madtpg.native")) |
| 6846 |
) |
| 6847 |
) |
| 6848 |
and cmdname == get_argyll_utilname("dispread") |
| 6849 |
and "-V" in args |
| 6850 |
) |
| 6851 |
if use_3dlut_override: |
| 6852 |
args.remove("-V") |
| 6853 |
working_basename = None |
| 6854 |
if args and args[-1].find(os.path.sep) > -1: |
| 6855 |
working_basename = os.path.basename(args[-1]) |
| 6856 |
if cmdname not in ( |
| 6857 |
get_argyll_utilname("dispcal"), |
| 6858 |
get_argyll_utilname("dispread"), |
| 6859 |
get_argyll_utilname("colprof"), |
| 6860 |
get_argyll_utilname("targen"), |
| 6861 |
get_argyll_utilname("txt2ti3"), |
| 6862 |
): |
| 6863 |
# Last arg is with extension |
| 6864 |
working_basename = os.path.splitext(working_basename)[0] |
| 6865 |
if working_dir is None: |
| 6866 |
working_dir = os.path.dirname(args[-1]) |
| 6867 |
if working_dir is None: |
| 6868 |
if self.use_patterngenerator: |
| 6869 |
working_dir = self.create_tempdir() |
| 6870 |
else: |
| 6871 |
working_dir = self.tempdir |
| 6872 |
if working_dir and not os.path.isdir(working_dir): |
| 6873 |
working_dir = None |
| 6874 |
if working_dir and working_dir == self.tempdir: |
| 6875 |
# Get a list of files in the temp directory and their modification |
| 6876 |
# times so we can determine later if anything has changed and we |
| 6877 |
# should keep the files in case of errors |
| 6878 |
for filename in os.listdir(working_dir): |
| 6879 |
self.tmpfiles[filename] = os.stat( |
| 6880 |
os.path.join(working_dir, filename) |
| 6881 |
).st_mtime |
| 6882 |
if ( |
| 6883 |
working_basename |
| 6884 |
and working_dir == self.tempdir |
| 6885 |
and not silent |
| 6886 |
and log_output |
| 6887 |
and not dry_run |
| 6888 |
): |
| 6889 |
self.set_sessionlogfile(sessionlogfile, working_basename, working_dir) |
| 6890 |
if not silent or VERBOSE >= 3: |
| 6891 |
self.log("-" * 80) |
| 6892 |
if self.sessionlogfile: |
| 6893 |
print("Session log:", self.sessionlogfile.filename) |
| 6894 |
print("") |
| 6895 |
use_madvr = ( |
| 6896 |
cmdname |
| 6897 |
in ( |
| 6898 |
get_argyll_utilname("dispcal"), |
| 6899 |
get_argyll_utilname("dispread"), |
| 6900 |
get_argyll_utilname("dispwin"), |
| 6901 |
) |
| 6902 |
and get_arg("-dmadvr", args) |
| 6903 |
and madvr |
| 6904 |
) |
| 6905 |
self.use_madvr = use_madvr |
| 6906 |
madvr_use_virtual_display = ( |
| 6907 |
use_madvr |
| 6908 |
and self.argyll_virtual_display |
| 6909 |
and (sys.platform != "win32" or getcfg("patterngenerator.ffp_insertion")) |
| 6910 |
) |
| 6911 |
if use_madvr: |
| 6912 |
# Try to connect to running madTPG or launch a new instance |
| 6913 |
try: |
| 6914 |
if self.madtpg_connect(): |
| 6915 |
# Connected |
| 6916 |
if ( |
| 6917 |
isinstance(self.madtpg, madvr.MadTPG_Net) |
| 6918 |
or madvr_use_virtual_display |
| 6919 |
): |
| 6920 |
# Need to handle calibration clearing/loading/saving |
| 6921 |
# for madVR net-protocol pure python implementation |
| 6922 |
cal = None |
| 6923 |
calfilename = None |
| 6924 |
profile = None |
| 6925 |
ramp = False |
| 6926 |
if cmdname == get_argyll_utilname("dispwin"): |
| 6927 |
if "-c" in args: |
| 6928 |
# Clear calibration |
| 6929 |
self.log("MadTPG_Net clear calibration") |
| 6930 |
ramp = None |
| 6931 |
if "-L" in args: |
| 6932 |
# NOTE: Hmm, profile will be None. It's not |
| 6933 |
# functionality we currently use though. |
| 6934 |
profile = config.get_display_profile() |
| 6935 |
if "-s" in args: |
| 6936 |
# Save calibration. Get from madTPG |
| 6937 |
self.log("MadTPG_Net save calibration:", args[-1]) |
| 6938 |
ramp = self.madtpg.get_device_gamma_ramp() |
| 6939 |
if not ramp: |
| 6940 |
self.madtpg_disconnect(False) |
| 6941 |
return Error("madVR_GetDeviceGammaRamp failed") |
| 6942 |
cal = """CAL |
| 6943 |
|
| 6944 |
KEYWORD "DEVICE_CLASS" |
| 6945 |
DEVICE_CLASS "DISPLAY" |
| 6946 |
KEYWORD "COLOR_REP" |
| 6947 |
COLOR_REP "RGB" |
| 6948 |
BEGIN_DATA_FORMAT |
| 6949 |
RGB_I RGB_R RGB_G RGB_B |
| 6950 |
END_DATA_FORMAT |
| 6951 |
NUMBER_OF_SETS 256 |
| 6952 |
BEGIN_DATA |
| 6953 |
""" |
| 6954 |
# Convert ushort_Array_256_Array_3 to dictionary |
| 6955 |
RGB = {} |
| 6956 |
for j in range(3): |
| 6957 |
for i in range(256): |
| 6958 |
if i not in RGB: |
| 6959 |
RGB[i] = [] |
| 6960 |
RGB[i].append(ramp[j][i] / 65535.0) |
| 6961 |
# Get RGB from dictionary |
| 6962 |
for i in RGB: |
| 6963 |
R, G, B = RGB[i] |
| 6964 |
cal += f"{i / 255.0:f} {R:f} {G:f} {B:f}\n" |
| 6965 |
cal += "END_DATA" |
| 6966 |
# Write out .cal file |
| 6967 |
try: |
| 6968 |
with open(args[-1], "w") as calfile: |
| 6969 |
calfile.write(cal) |
| 6970 |
except OSError as exception: |
| 6971 |
self.madtpg_disconnect(False) |
| 6972 |
return exception |
| 6973 |
cal = None |
| 6974 |
ramp = False |
| 6975 |
elif working_basename: |
| 6976 |
# .cal/.icc/.icm file to load |
| 6977 |
calfilename = args[-1] |
| 6978 |
elif cmdname == get_argyll_utilname("dispread"): |
| 6979 |
# Check for .cal file to load |
| 6980 |
# NOTE this isn't normally used as we use -K |
| 6981 |
# for madTPG, but is overridable by the user |
| 6982 |
k_arg = get_arg("-k", args, True) |
| 6983 |
if k_arg: |
| 6984 |
calfilename = args[k_arg[0] + 1] |
| 6985 |
else: |
| 6986 |
ramp = None |
| 6987 |
else: |
| 6988 |
# dispcal |
| 6989 |
ramp = None |
| 6990 |
if calfilename: |
| 6991 |
# Load calibration from cal file or ICC profile |
| 6992 |
self.log("MadTPG_Net load calibration:", calfilename) |
| 6993 |
result = check_file_isfile(calfilename) |
| 6994 |
if isinstance(result, Exception): |
| 6995 |
self.madtpg_disconnect(False) |
| 6996 |
return result |
| 6997 |
if calfilename.lower().endswith(".cal"): |
| 6998 |
# .cal file |
| 6999 |
try: |
| 7000 |
cal = CGATS(calfilename) |
| 7001 |
except (OSError, CGATSError) as exception: |
| 7002 |
self.madtpg_disconnect(False) |
| 7003 |
return exception |
| 7004 |
else: |
| 7005 |
# ICC profile |
| 7006 |
try: |
| 7007 |
profile = ICCProfile(calfilename) |
| 7008 |
except (OSError, ICCProfileInvalidError) as exception: |
| 7009 |
self.madtpg_disconnect(False) |
| 7010 |
return exception |
| 7011 |
if profile: |
| 7012 |
# Load calibration from ICC profile (if present) |
| 7013 |
cal = extract_cal_from_profile(profile, None, False) |
| 7014 |
if not cal: |
| 7015 |
# Linear |
| 7016 |
ramp = None |
| 7017 |
if cal: |
| 7018 |
# Check calibration we're going to load |
| 7019 |
try: |
| 7020 |
cal = verify_cgats(cal, ("RGB_R", "RGB_G", "RGB_B")) |
| 7021 |
if len(cal.DATA) != 256: |
| 7022 |
# Needs to have 256 entries |
| 7023 |
raise CGATSError( |
| 7024 |
"{}: {} != 256".format( |
| 7025 |
lang.getstr("calibration"), |
| 7026 |
lang.getstr("number_of_entries"), |
| 7027 |
) |
| 7028 |
) |
| 7029 |
except CGATSError as exception: |
| 7030 |
self.madtpg_disconnect(False) |
| 7031 |
return exception |
| 7032 |
# Convert calibration to ushort_Array_256_Array_3 |
| 7033 |
ramp = ((ctypes.c_ushort * 256) * 3)() |
| 7034 |
for i in range(256): |
| 7035 |
for j, channel in enumerate("RGB"): |
| 7036 |
ramp[j][i] = round( |
| 7037 |
cal.DATA[i][f"RGB_{channel}"] * 65535 |
| 7038 |
) |
| 7039 |
else: |
| 7040 |
ramp = None |
| 7041 |
if ramp is not False and not self.madtpg.set_device_gamma_ramp( |
| 7042 |
ramp |
| 7043 |
): |
| 7044 |
self.madtpg_disconnect(False) |
| 7045 |
return Error("madVR_SetDeviceGammaRamp failed") |
| 7046 |
if ( |
| 7047 |
isinstance(self.madtpg, madvr.MadTPG_Net) |
| 7048 |
or madvr_use_virtual_display |
| 7049 |
) and cmdname == get_argyll_utilname("dispwin"): |
| 7050 |
# For madVR net-protocol pure python implementation |
| 7051 |
# we are now done |
| 7052 |
if "-s" not in args: |
| 7053 |
# Only disconnect if we didn't save calibration (as |
| 7054 |
# part of a follow-up measurement) |
| 7055 |
self.madtpg_disconnect(False) |
| 7056 |
return True |
| 7057 |
if "-V" not in args and not use_3dlut_override: |
| 7058 |
endis = "disable" |
| 7059 |
else: |
| 7060 |
endis = "enable" |
| 7061 |
if not getattr(self.madtpg, endis + "_3dlut")(): |
| 7062 |
self.madtpg_disconnect(False) |
| 7063 |
return Error(f"madVR_{endis.capitalize()}3dlut failed") |
| 7064 |
fullscreen = self.madtpg.is_use_fullscreen_button_pressed() |
| 7065 |
if sys.platform == "win32": |
| 7066 |
# Make sure interactive display adjustment window isn't |
| 7067 |
# concealed by temporarily disabling fullscreen if |
| 7068 |
# needed. This is only a problem in single display |
| 7069 |
# configurations. |
| 7070 |
if self.single_real_display(): |
| 7071 |
# We only have one "real" display connected |
| 7072 |
if cmdname == get_argyll_utilname("dispcal") or ( |
| 7073 |
self.dispread_after_dispcal |
| 7074 |
and cmdname == get_argyll_utilname("dispread") |
| 7075 |
and self._detecting_video_levels |
| 7076 |
): |
| 7077 |
if ( |
| 7078 |
getcfg("calibration.interactive_display_adjustment") |
| 7079 |
and not getcfg("calibration.update") |
| 7080 |
and fullscreen |
| 7081 |
): |
| 7082 |
# Disable fullscreen |
| 7083 |
if self.madtpg.set_use_fullscreen_button(False): |
| 7084 |
self.log( |
| 7085 |
"Temporarily leaving madTPG fullscreen" |
| 7086 |
) |
| 7087 |
self.madtpg_previous_fullscreen = fullscreen |
| 7088 |
else: |
| 7089 |
self.log( |
| 7090 |
"Warning - couldn't " |
| 7091 |
"temporarily leave madTPG " |
| 7092 |
"fullscreen" |
| 7093 |
) |
| 7094 |
elif ( |
| 7095 |
getattr(self, "madtpg_previous_fullscreen", None) |
| 7096 |
and cmdname == get_argyll_utilname("dispread") |
| 7097 |
and self.dispread_after_dispcal |
| 7098 |
): |
| 7099 |
# Restore fullscreen |
| 7100 |
if self.madtpg.set_use_fullscreen_button(True): |
| 7101 |
self.log("Restored madTPG fullscreen") |
| 7102 |
self.madtpg_previous_fullscreen = None |
| 7103 |
else: |
| 7104 |
self.log( |
| 7105 |
"Warning - couldn't restore madTPG fullscreen" |
| 7106 |
) |
| 7107 |
self.madtpg_fullscreen = ( |
| 7108 |
self.madtpg.is_use_fullscreen_button_pressed() |
| 7109 |
) |
| 7110 |
# IMPORTANT: When making changes to the instrument on screen |
| 7111 |
# detection, also apply them to appropriate part in |
| 7112 |
# Worker.check_instrument_place_on_screen |
| 7113 |
if ( |
| 7114 |
( |
| 7115 |
not ( |
| 7116 |
cmdname == get_argyll_utilname("dispwin") |
| 7117 |
or self.dispread_after_dispcal |
| 7118 |
) |
| 7119 |
or ( |
| 7120 |
cmdname == get_argyll_utilname("dispcal") |
| 7121 |
and ("-m" in args or "-u" in args) |
| 7122 |
) |
| 7123 |
or self._detecting_video_levels |
| 7124 |
) |
| 7125 |
and self.madtpg_fullscreen |
| 7126 |
and not self.instrument_on_screen |
| 7127 |
): |
| 7128 |
# Show place instrument on screen message with countdown |
| 7129 |
countdown = 15 |
| 7130 |
# We need to show the progress bar to make OSD visible |
| 7131 |
if not self.madtpg.show_progress_bar(countdown): |
| 7132 |
self.madtpg_disconnect() |
| 7133 |
return Error("madVR_ShowProgressBar failed") |
| 7134 |
self.madtpg_osd = ( |
| 7135 |
not self.madtpg.is_disable_osd_button_pressed() |
| 7136 |
) |
| 7137 |
if not self.madtpg_osd: |
| 7138 |
# Enable OSD if disabled |
| 7139 |
if self.madtpg.set_disable_osd_button(False): |
| 7140 |
self.log( |
| 7141 |
"Temporarily enabled madTPG OSD for " |
| 7142 |
"instrument placement countdown" |
| 7143 |
) |
| 7144 |
else: |
| 7145 |
self.log( |
| 7146 |
"Warning - couldn't temporarily enable madTPG OSD" |
| 7147 |
) |
| 7148 |
for i in range(countdown): |
| 7149 |
if self.subprocess_abort: |
| 7150 |
break |
| 7151 |
if not self.madtpg.set_osd_text( |
| 7152 |
lang.getstr( |
| 7153 |
"instrument.place_on_screen.madvr", |
| 7154 |
(countdown - i, self.get_instrument_name()), |
| 7155 |
) |
| 7156 |
): |
| 7157 |
self.madtpg_disconnect() |
| 7158 |
return Error("madVR_SetOsdText failed") |
| 7159 |
ts = time() |
| 7160 |
if i % 2 == 0: |
| 7161 |
# Flash test area red |
| 7162 |
self.madtpg.show_rgb(0.25, 0.10, 0.10) |
| 7163 |
else: |
| 7164 |
self.madtpg.show_rgb(0.15, 0.15, 0.15) |
| 7165 |
delay = time() - ts |
| 7166 |
if delay < 1: |
| 7167 |
sleep(1 - delay) |
| 7168 |
self.instrument_on_screen = True |
| 7169 |
if not self.madtpg_osd: |
| 7170 |
# Disable OSD |
| 7171 |
if self.madtpg.set_disable_osd_button(True): |
| 7172 |
self.log("Restored madTPG 'Disable OSD' button state") |
| 7173 |
self.madtpg_osd = None |
| 7174 |
else: |
| 7175 |
self.log( |
| 7176 |
"Warning - could not restore madTPG " |
| 7177 |
"'Disable OSD' button state" |
| 7178 |
) |
| 7179 |
self.madtpg.set_osd_text("\u25b6") # "Play" symbol |
| 7180 |
self.madtpg.show_rgb(0.5, 0.5, 0.5) |
| 7181 |
# Get black and white level |
| 7182 |
self.madtpg_bw_lvl = self.madtpg.get_black_and_white_level() |
| 7183 |
if not self.madtpg_bw_lvl: |
| 7184 |
self.log("madVR_GetBlackAndWhiteLevel failed") |
| 7185 |
else: |
| 7186 |
self.log("Output levels: {}-{}".format(*self.madtpg_bw_lvl)) |
| 7187 |
# Get pattern config |
| 7188 |
patternconfig = self.madtpg.get_pattern_config() |
| 7189 |
if ( |
| 7190 |
not patternconfig |
| 7191 |
or not isinstance(patternconfig, tuple) |
| 7192 |
or len(patternconfig) != 4 |
| 7193 |
): |
| 7194 |
self.madtpg_disconnect() |
| 7195 |
return Error("madVR_GetPatternConfig failed") |
| 7196 |
self.log(f"Pattern area: {patternconfig[0]:d}%") |
| 7197 |
self.log(f"Background level: {patternconfig[1]:d}%") |
| 7198 |
self.log( |
| 7199 |
"Background mode: {}".format( |
| 7200 |
{0: "Constant", 1: "APL gamma", 2: "APL linear"}.get( |
| 7201 |
patternconfig[2], patternconfig[2] |
| 7202 |
) |
| 7203 |
) |
| 7204 |
) |
| 7205 |
self.log(f"Border width: {patternconfig[3]:d} pixels") |
| 7206 |
if ( |
| 7207 |
isinstance(self.madtpg, madvr.MadTPG_Net) |
| 7208 |
or madvr_use_virtual_display |
| 7209 |
): |
| 7210 |
dindex = args.index("-dmadvr") |
| 7211 |
args.remove("-dmadvr") |
| 7212 |
if madvr_use_virtual_display: |
| 7213 |
args.insert(dindex, f"-d{self.argyll_virtual_display}") |
| 7214 |
else: |
| 7215 |
args.insert(0, "-P1,1,0.01") |
| 7216 |
else: |
| 7217 |
# Only if using native madTPG implementation! |
| 7218 |
if not get_arg("-P", args): |
| 7219 |
# Setup patch size to match pattern config |
| 7220 |
args.insert(0, f"-P0.5,0.5,{math.sqrt(patternconfig[0]):f}") |
| 7221 |
if not patternconfig[1] and self.argyll_version >= [1, 7]: |
| 7222 |
# Setup black background if background level is zero. |
| 7223 |
# Only do this for Argyll >= 1.7 to prevent messing |
| 7224 |
# with pattern area when Argyll 1.6.x is used |
| 7225 |
args.insert(0, "-F") |
| 7226 |
self.log("") |
| 7227 |
else: |
| 7228 |
return Error(lang.getstr("madtpg.launch.failure")) |
| 7229 |
except Exception as exception: |
| 7230 |
if isinstance(getattr(self, "madtpg", None), madvr.MadTPG_Net) or ( |
| 7231 |
getattr(self, "madtpg", None) and madvr_use_virtual_display |
| 7232 |
): |
| 7233 |
self.madtpg_disconnect() |
| 7234 |
return exception |
| 7235 |
# Use mad* net protocol pure python implementation |
| 7236 |
use_madnet = use_madvr and ( |
| 7237 |
isinstance(self.madtpg, madvr.MadTPG_Net) or madvr_use_virtual_display |
| 7238 |
) |
| 7239 |
# Use mad* net protocol pure python implementation as pattern generator |
| 7240 |
self.use_madnet_tpg = use_madnet and cmdname != get_argyll_utilname("dispwin") |
| 7241 |
if self.use_patterngenerator or self.use_madnet_tpg: |
| 7242 |
# Run a dummy command so we can grab the RGB numbers for |
| 7243 |
# the pattern generator from the output |
| 7244 |
carg = get_arg("-C", args, True) |
| 7245 |
if carg: |
| 7246 |
index = min(carg[0] + 1, len(args) - 1) |
| 7247 |
args[index] += " && " |
| 7248 |
else: |
| 7249 |
args.insert(0, "-C") |
| 7250 |
args.insert(1, "") |
| 7251 |
index = 1 |
| 7252 |
python, pythonpath = get_python_and_pythonpath() |
| 7253 |
script_dir = working_dir |
| 7254 |
pythonscript = WAIT_FILE_TEMPLATE.format(script_dir=script_dir) |
| 7255 |
waitfilename = os.path.join(script_dir, ".wait") |
| 7256 |
if sys.platform == "win32": |
| 7257 |
# Avoid problems with encoding |
| 7258 |
python = win32api.GetShortPathName(python) |
| 7259 |
for i, path in enumerate(pythonpath): |
| 7260 |
if os.path.exists(path): |
| 7261 |
pythonpath[i] = win32api.GetShortPathName(path) |
| 7262 |
# Write out .wait.py file |
| 7263 |
scriptfilename = f"{waitfilename}.py" |
| 7264 |
with open(scriptfilename, "w", encoding="utf-8") as scriptfile: |
| 7265 |
scriptfile.write(pythonscript) |
| 7266 |
scriptfilename = win32api.GetShortPathName(scriptfilename) |
| 7267 |
# Write out .wait.cmd file |
| 7268 |
with open(f"{waitfilename}.cmd", "w", encoding="utf-8") as waitfile: |
| 7269 |
waitfile.write("@echo off\n") |
| 7270 |
waitfile.write("echo.\n") |
| 7271 |
waitfile.write("echo Current RGB %*\n") |
| 7272 |
waitfile.write( |
| 7273 |
'set "PYTHONPATH={}"\n'.format( # noqa: UP032 |
| 7274 |
safe_str(os.pathsep.join(pythonpath), ENC) |
| 7275 |
) |
| 7276 |
) |
| 7277 |
waitfile.write( |
| 7278 |
f'"{safe_str(python, ENC)}" ' |
| 7279 |
f'-S "{safe_str(scriptfilename, ENC)}" %*\n' |
| 7280 |
) |
| 7281 |
args[index] += waitfilename |
| 7282 |
else: |
| 7283 |
# Write out .wait file |
| 7284 |
with open(waitfilename, "w") as waitfile: |
| 7285 |
waitfile.write(f"#!/usr/bin/env python3\n{pythonscript}") |
| 7286 |
os.chmod(waitfilename, 0o755) # noqa: S103 |
| 7287 |
args[index] += "{} ./{}".format( |
| 7288 |
strtr(safe_str(python), {'"': r"\"", "$": r"\$"}), |
| 7289 |
os.path.basename(waitfilename), |
| 7290 |
) |
| 7291 |
if (VERBOSE >= 1 or not silent) and (not silent or VERBOSE >= 3): |
| 7292 |
if not silent and dry_run and not self.cmdrun: |
| 7293 |
print(lang.getstr("dry_run")) |
| 7294 |
print("") |
| 7295 |
self.cmdrun = True |
| 7296 |
if working_dir: |
| 7297 |
self.log(lang.getstr("working_dir")) |
| 7298 |
indent = " " |
| 7299 |
for name in working_dir.split(os.path.sep): |
| 7300 |
self.log( |
| 7301 |
textwrap.fill( |
| 7302 |
name + os.path.sep, |
| 7303 |
80, |
| 7304 |
expand_tabs=False, |
| 7305 |
replace_whitespace=False, |
| 7306 |
initial_indent=indent, |
| 7307 |
subsequent_indent=indent, |
| 7308 |
) |
| 7309 |
) |
| 7310 |
indent += " " |
| 7311 |
self.log("") |
| 7312 |
self.log(lang.getstr("commandline")) |
| 7313 |
printcmdline(cmd, args, fn=self.log, cwd=working_dir) |
| 7314 |
self.log("") |
| 7315 |
if not silent and dry_run: |
| 7316 |
if not self.lastcmdname or self.lastcmdname == cmdname: |
| 7317 |
print(lang.getstr("dry_run.end")) |
| 7318 |
if self.owner and hasattr(self.owner, "infoframe_toggle_handler"): |
| 7319 |
wx.CallAfter(self.owner.infoframe_toggle_handler, show=True) |
| 7320 |
if use_madnet: |
| 7321 |
self.madtpg_disconnect() |
| 7322 |
return UnloggedInfo(lang.getstr("dry_run.info")) |
| 7323 |
cmdline = [cmd, *args] |
| 7324 |
for i, item in enumerate(cmdline): |
| 7325 |
if i > 0 and item.find(os.path.sep) > -1: |
| 7326 |
if sys.platform == "win32": |
| 7327 |
item = make_win32_compatible_long_path(item) |
| 7328 |
if ( |
| 7329 |
re.search(r"[^\x20-\x7e]", os.path.basename(item)) |
| 7330 |
and os.path.exists(item) |
| 7331 |
and i < len(cmdline) - 1 |
| 7332 |
): |
| 7333 |
# Avoid problems with encoding under Windows by using |
| 7334 |
# GetShortPathName, but be careful with the last |
| 7335 |
# parameter which may be used as the basename for the |
| 7336 |
# output file |
| 7337 |
item = win32api.GetShortPathName(item) |
| 7338 |
if working_dir and os.path.dirname(cmdline[i]) == working_dir: |
| 7339 |
# Strip the path from all items in the working dir |
| 7340 |
item = os.path.basename(item) |
| 7341 |
if item != cmdline[i]: |
| 7342 |
cmdline[i] = item |
| 7343 |
if ( |
| 7344 |
working_dir |
| 7345 |
and sys.platform == "win32" |
| 7346 |
and re.search(r"[^\x20-\x7e]", working_dir) |
| 7347 |
and os.path.exists(working_dir) |
| 7348 |
): |
| 7349 |
# Avoid problems with encoding |
| 7350 |
working_dir = win32api.GetShortPathName(working_dir) |
| 7351 |
sudo = None |
| 7352 |
if asroot and ( |
| 7353 |
(sys.platform != "win32" and os.geteuid() != 0) |
| 7354 |
or (sys.platform == "win32" and sys.getwindowsversion() >= (6,)) |
| 7355 |
): |
| 7356 |
if sys.platform == "win32": |
| 7357 |
# Vista and later |
| 7358 |
pass |
| 7359 |
else: |
| 7360 |
if not self.auth_timestamp: |
| 7361 |
if hasattr(self, "thread") and self.thread.is_alive(): |
| 7362 |
# Careful: We can only show the auth dialog if running |
| 7363 |
# in the main GUI thread! |
| 7364 |
if use_madnet: |
| 7365 |
self.madtpg_disconnect() |
| 7366 |
return Error("Authentication requested in non-GUI thread") |
| 7367 |
result = self.authenticate(cmd, title, parent) |
| 7368 |
if result is False: |
| 7369 |
if use_madnet: |
| 7370 |
self.madtpg_disconnect() |
| 7371 |
return None |
| 7372 |
if isinstance(result, Exception): |
| 7373 |
if use_madnet: |
| 7374 |
self.madtpg_disconnect() |
| 7375 |
return result |
| 7376 |
sudo = str(self.sudo) |
| 7377 |
if sudo: |
| 7378 |
if not use_pty: |
| 7379 |
# Sudo may need a tty depending on configuration |
| 7380 |
use_pty = True |
| 7381 |
cmdline.insert(0, sudo) |
| 7382 |
if ( |
| 7383 |
cmdname == get_argyll_utilname("dispwin") |
| 7384 |
and sys.platform != "darwin" |
| 7385 |
and self.sudo.availoptions.get("E") |
| 7386 |
and getcfg("sudo.preserve_environment") |
| 7387 |
): |
| 7388 |
# Preserve environment so $DISPLAY is set |
| 7389 |
cmdline.insert(1, "-E") |
| 7390 |
if not use_pty: |
| 7391 |
cmdline.insert(1, "-S") |
| 7392 |
# Set empty string as password prompt to hide it from stderr |
| 7393 |
cmdline.insert(1, "") |
| 7394 |
cmdline.insert(1, "-p") |
| 7395 |
else: |
| 7396 |
# Use a designated prompt |
| 7397 |
cmdline.insert(1, "Password:") |
| 7398 |
cmdline.insert(1, "-p") |
| 7399 |
if ( |
| 7400 |
working_dir |
| 7401 |
and working_basename |
| 7402 |
and not skip_scripts |
| 7403 |
and not getcfg("skip_scripts") |
| 7404 |
): |
| 7405 |
try: |
| 7406 |
cmdfilename = os.path.join( |
| 7407 |
working_dir, f"{working_basename}.{cmdname}{SCRIPT_EXT}" |
| 7408 |
) |
| 7409 |
allfilename = os.path.join( |
| 7410 |
working_dir, f"{working_basename}.all{SCRIPT_EXT}" |
| 7411 |
) |
| 7412 |
first = not os.path.exists(allfilename) |
| 7413 |
last = cmdname == get_argyll_utilname("dispwin") |
| 7414 |
cmdfile = open(cmdfilename, "w") # noqa: SIM115 |
| 7415 |
allfile = open(allfilename, "a") # noqa: SIM115 |
| 7416 |
cmdfiles = Files((cmdfile, allfile)) |
| 7417 |
context = cmdfiles if first else cmdfile |
| 7418 |
if sys.platform == "win32": |
| 7419 |
context.write("@echo off\n") |
| 7420 |
context.write( |
| 7421 |
f"PATH {os.path.dirname(cmd)};%PATH%\n".encode( |
| 7422 |
ENC, "safe_asciize" |
| 7423 |
) |
| 7424 |
) |
| 7425 |
cmdfiles.write('pushd "%~dp0"\n'.encode(ENC, "safe_asciize")) |
| 7426 |
if cmdname in ( |
| 7427 |
get_argyll_utilname("dispcal"), |
| 7428 |
get_argyll_utilname("dispread"), |
| 7429 |
): |
| 7430 |
cmdfiles.write("color 07\n") |
| 7431 |
else: |
| 7432 |
context.write( |
| 7433 |
f"PATH={os.path.dirname(cmd)}:$PATH\n".encode( |
| 7434 |
ENC, "safe_asciize" |
| 7435 |
) |
| 7436 |
) |
| 7437 |
if sys.platform == "darwin" and config.mac_create_app: |
| 7438 |
cmdfiles.write('pushd "`dirname \\"$0\\"`/../../.."\n') |
| 7439 |
else: |
| 7440 |
cmdfiles.write('pushd "`dirname \\"$0\\"`"\n') |
| 7441 |
if ( |
| 7442 |
cmdname |
| 7443 |
in ( |
| 7444 |
get_argyll_utilname("dispcal"), |
| 7445 |
get_argyll_utilname("dispread"), |
| 7446 |
) |
| 7447 |
and sys.platform != "darwin" |
| 7448 |
): |
| 7449 |
cmdfiles.write('echo -e "\\033[40;2;37m" && clear\n') |
| 7450 |
os.chmod(cmdfilename, 0o755) # noqa: S103 |
| 7451 |
os.chmod(allfilename, 0o755) # noqa: S103 |
| 7452 |
cmdfiles.write( |
| 7453 |
" ".join(quote_args(cmdline)) |
| 7454 |
.replace(cmd, cmdname) |
| 7455 |
.encode(ENC, "safe_asciize") |
| 7456 |
+ b"\n" |
| 7457 |
) |
| 7458 |
if sys.platform == "win32": |
| 7459 |
cmdfiles.write("set exitcode=%errorlevel%\n") |
| 7460 |
if cmdname in ( |
| 7461 |
get_argyll_utilname("dispcal"), |
| 7462 |
get_argyll_utilname("dispread"), |
| 7463 |
): |
| 7464 |
# Reset to default commandline shell colors |
| 7465 |
cmdfiles.write("color\n") |
| 7466 |
cmdfiles.write("popd\n") |
| 7467 |
cmdfiles.write("if not %exitcode%==0 exit /B %exitcode%\n") |
| 7468 |
else: |
| 7469 |
cmdfiles.write("exitcode=$?\n") |
| 7470 |
if ( |
| 7471 |
cmdname |
| 7472 |
in ( |
| 7473 |
get_argyll_utilname("dispcal"), |
| 7474 |
get_argyll_utilname("dispread"), |
| 7475 |
) |
| 7476 |
and sys.platform != "darwin" |
| 7477 |
): |
| 7478 |
# reset to default commandline shell colors |
| 7479 |
cmdfiles.write('echo -e "\\033[0m" && clear\n') |
| 7480 |
cmdfiles.write("popd\n") |
| 7481 |
cmdfiles.write("if [ $exitcode -ne 0 ]; then exit $exitcode; fi\n") |
| 7482 |
cmdfiles.close() |
| 7483 |
if sys.platform == "darwin": |
| 7484 |
if config.mac_create_app: |
| 7485 |
# Could also use .command file directly, but using |
| 7486 |
# applescript allows giving focus to the terminal |
| 7487 |
# window automatically after a delay |
| 7488 |
script = ( |
| 7489 |
mac_terminal_do_script() |
| 7490 |
+ mac_terminal_set_colors(do=False) |
| 7491 |
+ [ |
| 7492 |
"-e", |
| 7493 |
"set shellscript to quoted form of " |
| 7494 |
"(POSIX path of (path to resource " |
| 7495 |
'"main.command"))', |
| 7496 |
"-e", |
| 7497 |
'tell app "Terminal"', |
| 7498 |
"-e", |
| 7499 |
"do script shellscript in first window", |
| 7500 |
"-e", |
| 7501 |
"delay 3", |
| 7502 |
"-e", |
| 7503 |
"activate", |
| 7504 |
"-e", |
| 7505 |
"end tell", |
| 7506 |
"-o", |
| 7507 |
] |
| 7508 |
) |
| 7509 |
# Part 1: "cmdfile" |
| 7510 |
appfilename = os.path.join( |
| 7511 |
working_dir, f"{working_basename}.{cmdname}.app" |
| 7512 |
) |
| 7513 |
cmdargs = ["osacompile", *script, appfilename.decode()] |
| 7514 |
p = sp.Popen( |
| 7515 |
cmdargs, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE |
| 7516 |
) |
| 7517 |
p.communicate() |
| 7518 |
shutil.move( |
| 7519 |
cmdfilename, |
| 7520 |
f"{appfilename}/Contents/Resources/main.command", |
| 7521 |
) |
| 7522 |
os.chmod( |
| 7523 |
f"{appfilename}/Contents/Resources/main.command", |
| 7524 |
0o755, # noqa: S103 |
| 7525 |
) |
| 7526 |
# Part 2: "allfile" |
| 7527 |
appfilename = os.path.join( |
| 7528 |
working_dir, working_basename + ".all.app" |
| 7529 |
) |
| 7530 |
cmdargs = ["osacompile", *script, appfilename] |
| 7531 |
p = sp.Popen( |
| 7532 |
cmdargs, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE |
| 7533 |
) |
| 7534 |
p.communicate() |
| 7535 |
shutil.copyfile( |
| 7536 |
allfilename, |
| 7537 |
f"{appfilename}/Contents/Resources/main.command", |
| 7538 |
) |
| 7539 |
os.chmod( |
| 7540 |
f"{appfilename}/Contents/Resources/main.command", |
| 7541 |
0o755, # noqa: S103 |
| 7542 |
) |
| 7543 |
if last: |
| 7544 |
os.remove(allfilename) |
| 7545 |
except Exception as exception: |
| 7546 |
self.log( |
| 7547 |
"Warning - error during shell script creation:", str(exception) |
| 7548 |
) |
| 7549 |
cmdline = [safe_str(arg, FS_ENC) for arg in cmdline] |
| 7550 |
working_dir = working_dir if working_dir else None |
| 7551 |
try: |
| 7552 |
if not self.measure_cmd and self.argyll_version >= [1, 2]: |
| 7553 |
# Argyll tools will no longer respond to keys |
| 7554 |
if DEBUG: |
| 7555 |
self.log("[D] Setting ARGYLL_NOT_INTERACTIVE 1") |
| 7556 |
os.environ["ARGYLL_NOT_INTERACTIVE"] = "1" |
| 7557 |
elif "ARGYLL_NOT_INTERACTIVE" in os.environ: |
| 7558 |
del os.environ["ARGYLL_NOT_INTERACTIVE"] |
| 7559 |
if DEBUG: |
| 7560 |
self.log("[D] argyll_version", self.argyll_version) |
| 7561 |
self.log( |
| 7562 |
"[D] ARGYLL_NOT_INTERACTIVE", |
| 7563 |
os.environ.get("ARGYLL_NOT_INTERACTIVE"), |
| 7564 |
) |
| 7565 |
if self.measure_cmd: |
| 7566 |
if isinstance(self.measurement_sound, audio.DummySound): |
| 7567 |
self._init_sounds(dummy=False) |
| 7568 |
for name, version in ( |
| 7569 |
("MIN_DISPLAY_UPDATE_DELAY_MS", [1, 5]), |
| 7570 |
("DISPLAY_SETTLE_TIME_MULT", [1, 7]), |
| 7571 |
): |
| 7572 |
backup = os.getenv(f"ARGYLL_{name}_BACKUP") |
| 7573 |
value = None |
| 7574 |
if ( |
| 7575 |
getcfg(f"measure.override_{name.lower()}") |
| 7576 |
and self.argyll_version >= version |
| 7577 |
): |
| 7578 |
if backup is None: |
| 7579 |
# Backup current value if any |
| 7580 |
current = os.getenv(f"ARGYLL_{name}", "") |
| 7581 |
os.environ[f"ARGYLL_{name}_BACKUP"] = current |
| 7582 |
else: |
| 7583 |
current = backup |
| 7584 |
if current: |
| 7585 |
self.log(f"{APPNAME}: Overriding ARGYLL_{name} {current}") |
| 7586 |
# Override |
| 7587 |
value = str(getcfg(f"measure.{name.lower()}")) |
| 7588 |
self.log(f"{APPNAME}: Setting ARGYLL_{name} {value}") |
| 7589 |
elif backup is not None: |
| 7590 |
value = backup |
| 7591 |
del os.environ[f"ARGYLL_{name}_BACKUP"] |
| 7592 |
if value: |
| 7593 |
self.log(f"{APPNAME}: Restoring ARGYLL_{name} {value}") |
| 7594 |
elif f"ARGYLL_{name}" in os.environ: |
| 7595 |
del os.environ[f"ARGYLL_{name}"] |
| 7596 |
elif f"ARGYLL_{name}" in os.environ: |
| 7597 |
self.log( |
| 7598 |
f"{APPNAME}: ARGYLL_{name}", |
| 7599 |
os.getenv(f"ARGYLL_{name}"), |
| 7600 |
) |
| 7601 |
if value: |
| 7602 |
os.environ[f"ARGYLL_{name}"] = value |
| 7603 |
elif cmdname in ( |
| 7604 |
get_argyll_utilname("iccgamut"), |
| 7605 |
get_argyll_utilname("tiffgamut"), |
| 7606 |
get_argyll_utilname("viewgam"), |
| 7607 |
get_argyll_utilname("colprof"), |
| 7608 |
get_argyll_utilname("collink"), |
| 7609 |
): |
| 7610 |
os.environ["ARGYLL_3D_DISP_FORMAT"] = "VRML" |
| 7611 |
if sys.platform not in ("darwin", "win32"): |
| 7612 |
os.environ["ENABLE_COLORHUG"] = "1" |
| 7613 |
if sys.platform == "win32": |
| 7614 |
startupinfo = sp.STARTUPINFO() |
| 7615 |
startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW |
| 7616 |
startupinfo.wShowWindow = sp.SW_HIDE |
| 7617 |
else: |
| 7618 |
startupinfo = None |
| 7619 |
if not use_pty: |
| 7620 |
data_encoding = ENC |
| 7621 |
stderr = sp.STDOUT if silent else tempfile.SpooledTemporaryFile() # noqa: SIM115 |
| 7622 |
if capture_output: |
| 7623 |
stdout = tempfile.SpooledTemporaryFile() # noqa: SIM115 |
| 7624 |
elif ( |
| 7625 |
sys.stdout and hasattr(sys.stdout, "isatty") and sys.stdout.isatty() |
| 7626 |
): |
| 7627 |
stdout = sys.stdout |
| 7628 |
else: |
| 7629 |
stdout = sp.PIPE |
| 7630 |
if sudo: |
| 7631 |
stdin = tempfile.SpooledTemporaryFile() # noqa: SIM115 |
| 7632 |
stdin.write(self.pwd.encode(ENC, "replace") + os.linesep) |
| 7633 |
stdin.seek(0) |
| 7634 |
else: |
| 7635 |
stdin = sp.PIPE |
| 7636 |
else: |
| 7637 |
data_encoding = self.pty_encoding |
| 7638 |
kwargs = {"timeout": 20, "cwd": working_dir, "env": os.environ} |
| 7639 |
if sys.platform == "win32": |
| 7640 |
# FIX: stdio cp1252 vs utf-8 (cp65001) issue under Windows 10/11+ |
| 7641 |
# os.environ["PYTHONLEGACYWINDOWSSTDIO"] = "1" |
| 7642 |
kwargs["codepage"] = windll.kernel32.GetACP() |
| 7643 |
# As Windows' console always hard wraps at the |
| 7644 |
# rightmost column, increase the buffer width |
| 7645 |
kwargs["columns"] = 160 |
| 7646 |
stderr = None |
| 7647 |
stdout = EncodedWriter(StringIO(), None, data_encoding) |
| 7648 |
logfiles = [] |
| 7649 |
if ( |
| 7650 |
hasattr(self, "thread") |
| 7651 |
and self.thread.is_alive() |
| 7652 |
and self.interactive |
| 7653 |
and getattr(self, "terminal", None) |
| 7654 |
): |
| 7655 |
logfiles.append( |
| 7656 |
FilteredStream( |
| 7657 |
self.terminal, discard="", triggers=self.triggers |
| 7658 |
) |
| 7659 |
) |
| 7660 |
if log_output: |
| 7661 |
linebuffered_logfiles = [] |
| 7662 |
if ( |
| 7663 |
sys.stdout |
| 7664 |
and hasattr(sys.stdout, "isatty") |
| 7665 |
and sys.stdout.isatty() |
| 7666 |
): |
| 7667 |
linebuffered_logfiles.append(print) |
| 7668 |
else: |
| 7669 |
linebuffered_logfiles.append(LOG) |
| 7670 |
if self.sessionlogfile: |
| 7671 |
linebuffered_logfiles.append(self.sessionlogfile) |
| 7672 |
logfiles.append( |
| 7673 |
LineBufferedStream( |
| 7674 |
FilteredStream( |
| 7675 |
Files(linebuffered_logfiles), |
| 7676 |
data_encoding, |
| 7677 |
discard="", |
| 7678 |
linesep_in="\n", |
| 7679 |
triggers=[], |
| 7680 |
) |
| 7681 |
) |
| 7682 |
) |
| 7683 |
logfiles.append(stdout) |
| 7684 |
if hasattr(self, "thread") and self.thread.is_alive(): |
| 7685 |
logfiles.extend([self.recent, self.lastmsg, self]) |
| 7686 |
logfiles = Files(logfiles) |
| 7687 |
if self.use_patterngenerator: |
| 7688 |
pgname = config.get_display_name() |
| 7689 |
self.setup_patterngenerator(logfiles) |
| 7690 |
if not hasattr(self.patterngenerator, "conn") and hasattr( |
| 7691 |
self.patterngenerator, "wait" |
| 7692 |
): |
| 7693 |
# Wait for connection - blocking |
| 7694 |
self.patterngenerator.wait() |
| 7695 |
if hasattr(self.patterngenerator, "conn"): |
| 7696 |
self.patterngenerator_send( |
| 7697 |
(0.5,) * 3, increase_sent_count=False |
| 7698 |
) |
| 7699 |
else: |
| 7700 |
# User aborted before connection was established |
| 7701 |
return False |
| 7702 |
if pgname == "Prisma": |
| 7703 |
x, y, w, h, size = get_pattern_geometry() |
| 7704 |
if use_3dlut_override: |
| 7705 |
self.patterngenerator.enable_processing(size=size * 100) |
| 7706 |
else: |
| 7707 |
self.patterngenerator.disable_processing(size=size * 100) |
| 7708 |
tries = 1 |
| 7709 |
while tries > 0: |
| 7710 |
if self.subprocess_abort: |
| 7711 |
break |
| 7712 |
if use_pty: |
| 7713 |
if ( |
| 7714 |
self.argyll_version >= [1, 2] |
| 7715 |
and USE_WPOPEN |
| 7716 |
and os.environ.get("ARGYLL_NOT_INTERACTIVE") |
| 7717 |
): |
| 7718 |
self.subprocess = WPopen( |
| 7719 |
cmdline, |
| 7720 |
stdin=sp.PIPE, |
| 7721 |
stdout=tempfile.SpooledTemporaryFile(), # noqa: SIM115 |
| 7722 |
stderr=sp.STDOUT, |
| 7723 |
shell=shell, |
| 7724 |
cwd=working_dir, |
| 7725 |
startupinfo=startupinfo, |
| 7726 |
) |
| 7727 |
else: |
| 7728 |
# Minimum Windows version: XP or Server 2003 |
| 7729 |
if sys.platform == "win32" and sys.getwindowsversion() < (5, 1): |
| 7730 |
raise Error(lang.getstr("windows.version.unsupported")) |
| 7731 |
|
| 7732 |
try: |
| 7733 |
self.subprocess = wexpect.spawn( |
| 7734 |
cmdline[0], cmdline[1:], **kwargs |
| 7735 |
) |
| 7736 |
except wexpect.ExceptionPexpect as exception: |
| 7737 |
self.retcode = -1 |
| 7738 |
raise Error(str(exception)) from exception |
| 7739 |
|
| 7740 |
if sys.platform == "darwin" and self.measure_cmd: |
| 7741 |
# Caffeinate (prevent sleep/screensaver) |
| 7742 |
caffeinate = which("caffeinate") |
| 7743 |
if caffeinate: |
| 7744 |
wait_pid = str(self.subprocess.pid) |
| 7745 |
try: |
| 7746 |
# -d prevent idle display sleep |
| 7747 |
# -i prevent idle system sleep |
| 7748 |
# -w wait for process <pid> to exit |
| 7749 |
caffeinated = sp.Popen( |
| 7750 |
[caffeinate, "-d", "-i", "-w", wait_pid], |
| 7751 |
stdin=sp.PIPE, |
| 7752 |
stdout=sp.PIPE, |
| 7753 |
stderr=sp.PIPE, |
| 7754 |
) |
| 7755 |
except Exception as exception: |
| 7756 |
self.log( |
| 7757 |
f"{APPNAME}: caffeinate could not " |
| 7758 |
"be started - screensaver and " |
| 7759 |
"display/system sleep may still " |
| 7760 |
"occur!" |
| 7761 |
) |
| 7762 |
self.log(exception) |
| 7763 |
else: |
| 7764 |
self.log( |
| 7765 |
f"{APPNAME}: caffeinate started, " |
| 7766 |
"preventing screensaver and " |
| 7767 |
"display/system sleep - waiting " |
| 7768 |
"for {} (PID {}) to exit".format( |
| 7769 |
cmdname, wait_pid |
| 7770 |
) |
| 7771 |
) |
| 7772 |
|
| 7773 |
def caffeinate_wait(proc): |
| 7774 |
proc.wait() |
| 7775 |
self.log( |
| 7776 |
f"{APPNAME}: caffeinate exited " |
| 7777 |
f"with code {proc.returncode}" |
| 7778 |
) |
| 7779 |
|
| 7780 |
wait_thread = threading.Thread( |
| 7781 |
target=partial( |
| 7782 |
caffeinate_wait, proc=caffeinated |
| 7783 |
) |
| 7784 |
) |
| 7785 |
wait_thread.daemon = True |
| 7786 |
wait_thread.start() |
| 7787 |
else: |
| 7788 |
self.log( |
| 7789 |
f"{APPNAME}: caffeinate not found - " |
| 7790 |
"screensaver and display/system sleep " |
| 7791 |
"may still occur!" |
| 7792 |
) |
| 7793 |
if DEBUG >= 9 or (TEST and "-?" not in args): |
| 7794 |
self.subprocess.interact() |
| 7795 |
self.subprocess.logfile_read = logfiles |
| 7796 |
if self.measure_cmd: |
| 7797 |
keyhit_strs = [" or Q to ", r"8\) Exit"] |
| 7798 |
patterns = [*keyhit_strs, "Current", r" \d+ of \d+"] |
| 7799 |
self.log(f"{APPNAME}: Starting interaction with subprocess") |
| 7800 |
else: |
| 7801 |
patterns = [] |
| 7802 |
self.log(f"{APPNAME}: Waiting for EOF") |
| 7803 |
loop = 0 |
| 7804 |
pwdsent = False |
| 7805 |
authfailed = False |
| 7806 |
eof = False |
| 7807 |
while 1: |
| 7808 |
if loop < 1 and sudo: |
| 7809 |
curpatterns = ["Password:", *patterns] |
| 7810 |
else: |
| 7811 |
curpatterns = patterns |
| 7812 |
# NOTE: Using a timeout of None can block indefinitely |
| 7813 |
# and prevent expect() from ever returning! |
| 7814 |
self.subprocess.expect( |
| 7815 |
[*curpatterns, wexpect.EOF, wexpect.TIMEOUT], timeout=1 |
| 7816 |
) |
| 7817 |
if self.subprocess.after is wexpect.EOF: |
| 7818 |
self.log(f"{APPNAME}: Reached EOF (OK)") |
| 7819 |
break |
| 7820 |
if self.subprocess.after is wexpect.TIMEOUT: |
| 7821 |
if not self.subprocess.isalive(): |
| 7822 |
self.log( |
| 7823 |
f"{APPNAME}: Subprocess no longer alive (timeout)" |
| 7824 |
) |
| 7825 |
if eof: |
| 7826 |
break |
| 7827 |
eof = True |
| 7828 |
continue |
| 7829 |
if self.subprocess.after == "Password:" and loop < 1 and sudo: |
| 7830 |
if pwdsent: |
| 7831 |
self.subprocess.sendcontrol("C") |
| 7832 |
authfailed = True |
| 7833 |
self.auth_timestamp = 0 |
| 7834 |
else: |
| 7835 |
self._safe_send( |
| 7836 |
self.pwd + os.linesep, |
| 7837 |
obfuscate=True, |
| 7838 |
) |
| 7839 |
pwdsent = True |
| 7840 |
if not self.subprocess.isalive(): |
| 7841 |
break |
| 7842 |
continue |
| 7843 |
if self.measure_cmd: |
| 7844 |
if [ |
| 7845 |
keyhit_str |
| 7846 |
for keyhit_str in keyhit_strs |
| 7847 |
if re.search(keyhit_str, self.subprocess.after) |
| 7848 |
]: |
| 7849 |
# Wait for the keypress |
| 7850 |
self.log(f"{APPNAME}: Waiting for send buffer") |
| 7851 |
while not self.send_buffer: |
| 7852 |
if not self.subprocess.isalive(): |
| 7853 |
self.log( |
| 7854 |
f"{APPNAME}: Subprocess no longer alive " |
| 7855 |
f"(unknown reason)" |
| 7856 |
) |
| 7857 |
break |
| 7858 |
sleep(0.05) |
| 7859 |
self.log( |
| 7860 |
f"{APPNAME}: Send buffer received: " |
| 7861 |
f"{self.send_buffer}" |
| 7862 |
) |
| 7863 |
if ( |
| 7864 |
self.send_buffer is not None |
| 7865 |
and self.subprocess.isalive() |
| 7866 |
): |
| 7867 |
if ( |
| 7868 |
self.send_buffer == "7" |
| 7869 |
and use_madvr |
| 7870 |
and cmdname == get_argyll_utilname("dispcal") |
| 7871 |
): |
| 7872 |
# Restore madTPG OSD and fullscreen |
| 7873 |
self.madtpg_restore_settings(False) |
| 7874 |
self.log( |
| 7875 |
f"{APPNAME}: Sending buffer: {self.send_buffer}" |
| 7876 |
) |
| 7877 |
self._safe_send(self.send_buffer) |
| 7878 |
self.send_buffer = None |
| 7879 |
if not self.subprocess.isalive(): |
| 7880 |
break |
| 7881 |
loop += 1 |
| 7882 |
# We need to call isalive() to set the exitstatus. |
| 7883 |
# We can't use wait() because it might block in the |
| 7884 |
# case of a timeout |
| 7885 |
if self.subprocess.isalive(): |
| 7886 |
self.log(f"{APPNAME}: Checking subprocess status") |
| 7887 |
while self.subprocess.isalive(): |
| 7888 |
sleep(0.1) |
| 7889 |
self.log(f"{APPNAME}: Subprocess no longer alive (OK)") |
| 7890 |
self.retcode = self.subprocess.exitstatus |
| 7891 |
if authfailed: |
| 7892 |
raise Error(lang.getstr("auth.failed")) |
| 7893 |
else: |
| 7894 |
try: |
| 7895 |
if ( |
| 7896 |
asroot |
| 7897 |
and sys.platform == "win32" |
| 7898 |
and sys.getwindowsversion() >= (6,) |
| 7899 |
): |
| 7900 |
p = run_as_admin(cmd, args, close_process=False, show=False) |
| 7901 |
while not self.subprocess_abort: |
| 7902 |
# Wait for subprocess to exit |
| 7903 |
self.retcode = win32event.WaitForSingleObject( |
| 7904 |
p["hProcess"], 50 |
| 7905 |
) |
| 7906 |
if not self.retcode: |
| 7907 |
break |
| 7908 |
p["hProcess"].Close() |
| 7909 |
return self.retcode == 0 |
| 7910 |
self.subprocess = sp.Popen( |
| 7911 |
cmdline, |
| 7912 |
stdin=stdin, |
| 7913 |
stdout=stdout, |
| 7914 |
stderr=stderr, |
| 7915 |
shell=shell, |
| 7916 |
cwd=working_dir, |
| 7917 |
startupinfo=startupinfo, |
| 7918 |
) |
| 7919 |
except Exception as exception: |
| 7920 |
self.retcode = -1 |
| 7921 |
raise Error(str(exception)) from exception |
| 7922 |
self.retcode = self.subprocess.wait() |
| 7923 |
if stdin != sp.PIPE and not getattr(stdin, "closed", True): |
| 7924 |
stdin.close() |
| 7925 |
if self.is_working() and self.subprocess_abort and self.retcode == 0: |
| 7926 |
self.retcode = -1 |
| 7927 |
self.subprocess = None |
| 7928 |
tries -= 1 |
| 7929 |
if not silent and stderr: |
| 7930 |
stderr.seek(0) |
| 7931 |
errors = stderr.readlines() |
| 7932 |
if not capture_output or stderr is not stdout: |
| 7933 |
stderr.close() |
| 7934 |
if len(errors): |
| 7935 |
for line in errors: |
| 7936 |
if isinstance(line, bytes): |
| 7937 |
line = line.decode() |
| 7938 |
line = line.strip() |
| 7939 |
if ( |
| 7940 |
"Instrument Access Failed" in line |
| 7941 |
and "-N" in cmdline[:-1] |
| 7942 |
): |
| 7943 |
cmdline.remove("-N") |
| 7944 |
tries = 1 |
| 7945 |
break |
| 7946 |
if ( |
| 7947 |
line.find("User Aborted") < 0 |
| 7948 |
and line.find( |
| 7949 |
"XRandR 1.2 is faulty - falling back " |
| 7950 |
"to older extensions" |
| 7951 |
) |
| 7952 |
< 0 |
| 7953 |
): |
| 7954 |
self.errors.append(line) |
| 7955 |
if tries > 0 and not use_pty: |
| 7956 |
stderr = tempfile.SpooledTemporaryFile() # noqa: SIM115 |
| 7957 |
if capture_output or use_pty: |
| 7958 |
stdout.seek(0) |
| 7959 |
stdout_readlines = stdout.readlines() |
| 7960 |
self.output = [] |
| 7961 |
for line in stdout_readlines: |
| 7962 |
if isinstance(line, bytes): |
| 7963 |
line = line.decode() |
| 7964 |
line = line.strip() |
| 7965 |
line = re.sub(r"^\.{4,}\s*$", "", line).strip() |
| 7966 |
self.output.append(line) |
| 7967 |
stdout.close() |
| 7968 |
if len(self.output) and log_output: |
| 7969 |
if not use_pty: |
| 7970 |
self.log("".join(self.output).strip()) |
| 7971 |
if ( |
| 7972 |
display_output |
| 7973 |
and self.owner |
| 7974 |
and hasattr(self.owner, "infoframe_toggle_handler") |
| 7975 |
): |
| 7976 |
wx.CallAfter(self.owner.infoframe_toggle_handler, show=True) |
| 7977 |
if tries > 0 and not use_pty: |
| 7978 |
stdout = tempfile.SpooledTemporaryFile() # noqa: SIM115 |
| 7979 |
if not silent and len(self.errors): |
| 7980 |
errstr = "".join(self.errors).strip() |
| 7981 |
self.log(errstr) |
| 7982 |
except (OSError, Error, RuntimeError) as exception: |
| 7983 |
return exception |
| 7984 |
except Exception: |
| 7985 |
if DEBUG: |
| 7986 |
self.log("[D] working_dir:", working_dir) |
| 7987 |
|
| 7988 |
# TODO: Fix this in the source of the problem, not here!!! |
| 7989 |
new_cmdline = [] |
| 7990 |
for item in cmdline: |
| 7991 |
if isinstance(item, bytes): |
| 7992 |
item = item.decode() |
| 7993 |
new_cmdline.append(item) |
| 7994 |
cmdline = new_cmdline |
| 7995 |
|
| 7996 |
errmsg = " ".join(cmdline) + "\n" + str(traceback.format_exc()) |
| 7997 |
self.retcode = -1 |
| 7998 |
return Error(errmsg) |
| 7999 |
finally: |
| 8000 |
if ( |
| 8001 |
sudo |
| 8002 |
and cmdname not in ("chown", get_argyll_utilname("dispwin")) |
| 8003 |
and working_dir |
| 8004 |
and working_dir == self.tempdir |
| 8005 |
and os.listdir(working_dir) |
| 8006 |
): |
| 8007 |
# We need to take ownership of any files created by commands |
| 8008 |
# run via sudo otherwise we cannot move or remove them from |
| 8009 |
# the temporary directory! |
| 8010 |
errors = self.errors |
| 8011 |
output = self.output |
| 8012 |
retcode = self.retcode |
| 8013 |
self.exec_cmd( |
| 8014 |
"chown", |
| 8015 |
["-R", getpass.getuser().decode(FS_ENC), working_dir], |
| 8016 |
capture_output=capture_output, |
| 8017 |
skip_scripts=True, |
| 8018 |
asroot=True, |
| 8019 |
) |
| 8020 |
self.errors = errors |
| 8021 |
self.output = output |
| 8022 |
self.retcode = retcode |
| 8023 |
finished = ( |
| 8024 |
(self.cmdname == "dispcal" and not self.dispread_after_dispcal) |
| 8025 |
or (self.cmdname == "dispread" and not self._detecting_video_levels) |
| 8026 |
or self.retcode |
| 8027 |
) |
| 8028 |
if self.patterngenerator and hasattr(self.patterngenerator, "conn"): |
| 8029 |
try: |
| 8030 |
if config.get_display_name() == "Resolve": |
| 8031 |
# Send fullscreen black to prevent burn-in |
| 8032 |
if finished: |
| 8033 |
with contextlib.suppress(OSError): |
| 8034 |
self.patterngenerator.send((0,) * 3, x=0, y=0, w=1, h=1) |
| 8035 |
elif isinstance( |
| 8036 |
self.patterngenerator, WebWinHTTPPatternGeneratorServer |
| 8037 |
): |
| 8038 |
# Keep WebWin server alive across setup/test and |
| 8039 |
# interactive adjustment so connected browsers do not |
| 8040 |
# need to reconnect between consecutive operations. |
| 8041 |
pass |
| 8042 |
else: |
| 8043 |
self.patterngenerator.disconnect_client() |
| 8044 |
except Exception as exception: |
| 8045 |
self.log(exception) |
| 8046 |
if hasattr(self, "madtpg") and finished: |
| 8047 |
self.madtpg_disconnect() |
| 8048 |
if ( |
| 8049 |
sys.platform not in ("darwin", "win32") |
| 8050 |
and self.measure_cmd |
| 8051 |
and self._use_patternwindow |
| 8052 |
and (profiling_inhibit or display_profile) |
| 8053 |
and not report_current_cal |
| 8054 |
): |
| 8055 |
# Preliminary Wayland support. This still needs a lot |
| 8056 |
# of work as Argyll doesn't support Wayland natively yet, |
| 8057 |
# so we use virtual display to drive our own patch window. |
| 8058 |
|
| 8059 |
# We need to restore the display profile. |
| 8060 |
if profiling_inhibit: |
| 8061 |
# Use DBus interface to call ProfilingInhibit() |
| 8062 |
try: |
| 8063 |
cd_device.profiling_uninhibit() |
| 8064 |
except Exception as cd_exception: |
| 8065 |
self.log(cd_exception) |
| 8066 |
profiling_inhibit = False |
| 8067 |
else: |
| 8068 |
self.log(f"{APPNAME}: Uninhibited display device") |
| 8069 |
if not profiling_inhibit: |
| 8070 |
# Fallback - restore display profile |
| 8071 |
self.log(f"{APPNAME}: Re-assigning display profile...") |
| 8072 |
cdinstall = self._attempt_install_profile_colord(display_profile) |
| 8073 |
if cdinstall is True: |
| 8074 |
self.log(f"{APPNAME}: Successfully re-assigned display profile") |
| 8075 |
elif not cdinstall: |
| 8076 |
self.log(lang.getstr("calibration.load_error")) |
| 8077 |
# Remove temp sRGB profile |
| 8078 |
try: |
| 8079 |
os.remove( |
| 8080 |
os.path.join( |
| 8081 |
XDG_DATA_HOME, |
| 8082 |
"icc", |
| 8083 |
os.path.basename(self.srgb.filename), |
| 8084 |
) |
| 8085 |
) |
| 8086 |
except Exception as exception: |
| 8087 |
self.log(exception) |
| 8088 |
if not silent: |
| 8089 |
self.log(cmdname, "exitcode:", self.retcode) |
| 8090 |
if self.retcode != 0: |
| 8091 |
if use_pty and VERBOSE >= 1 and not silent: |
| 8092 |
self.log(lang.getstr("aborted")) |
| 8093 |
if use_pty and len(self.output): |
| 8094 |
errmsg = None |
| 8095 |
for i, line in enumerate(self.output): |
| 8096 |
if ( |
| 8097 |
"Calibrate failed with 'User hit Abort Key' (No device error)" |
| 8098 |
in line |
| 8099 |
): |
| 8100 |
break |
| 8101 |
if ( |
| 8102 |
( |
| 8103 |
": Error" in line |
| 8104 |
and "failed with 'User Aborted'" not in line |
| 8105 |
and "returned error code 1" not in line |
| 8106 |
) |
| 8107 |
or ( |
| 8108 |
line.startswith("Failed to") |
| 8109 |
and "Failed to meet target" not in line |
| 8110 |
) |
| 8111 |
or ( |
| 8112 |
"Requested ambient light capability" in line |
| 8113 |
and len(self.output) == i + 2 |
| 8114 |
) |
| 8115 |
or ( |
| 8116 |
"Diagnostic:" in line |
| 8117 |
and ( |
| 8118 |
len(self.output) == i + 1 |
| 8119 |
or self.output[i + 1].startswith("usage:") |
| 8120 |
) |
| 8121 |
) |
| 8122 |
or "communications failure" in line.lower() |
| 8123 |
): |
| 8124 |
# "returned error code 1" == user aborted |
| 8125 |
if ( |
| 8126 |
sys.platform == "win32" |
| 8127 |
and ( |
| 8128 |
"config 1 failed (Operation not supported or " |
| 8129 |
"unimplemented on this platform) (Permissions ?)" |
| 8130 |
) |
| 8131 |
in line |
| 8132 |
): |
| 8133 |
self.output.insert( |
| 8134 |
i, |
| 8135 |
lang.getstr("argyll.instrument.driver.missing") |
| 8136 |
+ "\n\n" |
| 8137 |
+ lang.getstr("argyll.error.detail") |
| 8138 |
+ " ", |
| 8139 |
) |
| 8140 |
if "Diagnostic:" in line: |
| 8141 |
errmsg = line |
| 8142 |
else: |
| 8143 |
errmsg = "".join(self.output[i:]) |
| 8144 |
startpos = errmsg.find(": Error") |
| 8145 |
if startpos > -1: |
| 8146 |
errmsg = errmsg[startpos + 2 :] |
| 8147 |
if errmsg: |
| 8148 |
return UnloggedError(errmsg.strip()) |
| 8149 |
# macOS clobbers a display's VideoLUT to all-black when an ArgyllCMS |
| 8150 |
# display tool exits (issue #694). Recover right here, in the worker |
| 8151 |
# thread, after the tool has finished - this is race-free (sequential) |
| 8152 |
# and independent of whether the GUI stays open, so the screen doesn't |
| 8153 |
# stay black through the subsequent profile-creation steps. |
| 8154 |
if ( |
| 8155 |
sys.platform == "darwin" |
| 8156 |
and not dry_run |
| 8157 |
and args |
| 8158 |
and "-?" not in args |
| 8159 |
and getcfg("profile_loader.macos_reapply_watch") |
| 8160 |
and cmdname |
| 8161 |
in ( |
| 8162 |
get_argyll_utilname("dispcal"), |
| 8163 |
get_argyll_utilname("dispread"), |
| 8164 |
get_argyll_utilname("spotread"), |
| 8165 |
get_argyll_utilname("dispwin"), |
| 8166 |
get_argyll_utilname("colprof"), |
| 8167 |
) |
| 8168 |
): |
| 8169 |
reload_black_videoluts(get_argyll_util("dispwin"), log=self.log) |
| 8170 |
if self.exec_cmd_returnvalue is not None: |
| 8171 |
return self.exec_cmd_returnvalue |
| 8172 |
return self.retcode == 0 |
| 8173 |
|
| 8174 |
def flush(self): |
| 8175 |
"""Flush the output and error streams of the worker.""" |
| 8176 |
|
| 8177 |
def _generic_consumer( |
| 8178 |
self, delayedResult, consumer, continue_next, *args, **kwargs |
| 8179 |
): |
| 8180 |
"""Generic consumer for delayed results. |
| 8181 |
|
| 8182 |
Args: |
| 8183 |
delayedResult (DelayedResult): The delayed result to process. |
| 8184 |
consumer (callable): The consumer function to call with the result. |
| 8185 |
continue_next (bool): Whether to continue to the next step |
| 8186 |
after processing the result. |
| 8187 |
*args: Additional arguments to pass to the consumer. |
| 8188 |
**kwargs: Additional keyword arguments to pass to the consumer. |
| 8189 |
|
| 8190 |
Raises: |
| 8191 |
UnloggedError: If an error occurs during processing. |
| 8192 |
""" |
| 8193 |
# consumer must accept result as first arg |
| 8194 |
result = None |
| 8195 |
try: |
| 8196 |
result = delayedResult.get() |
| 8197 |
except Exception as exception: |
| 8198 |
if ( |
| 8199 |
exception.__class__ is Exception |
| 8200 |
and exception.args |
| 8201 |
and exception.args[0] == "aborted" |
| 8202 |
): |
| 8203 |
# Special case - aborted |
| 8204 |
result = False |
| 8205 |
elif isinstance(exception, (UntracedError, Info)): |
| 8206 |
result = exception |
| 8207 |
else: |
| 8208 |
if hasattr(exception, "originalTraceback"): |
| 8209 |
self.log(exception.originalTraceback) |
| 8210 |
else: |
| 8211 |
self.log(traceback.format_exc()) |
| 8212 |
result = UnloggedError(safe_str(exception)) |
| 8213 |
if self.progress_start_timer.IsRunning(): |
| 8214 |
self.progress_start_timer.Stop() |
| 8215 |
self.finished = True |
| 8216 |
if not continue_next or isinstance(result, Exception) or not result: |
| 8217 |
self.stop_progress() |
| 8218 |
self.subprocess_abort = False |
| 8219 |
self.thread_abort = False |
| 8220 |
self.recent.clear() |
| 8221 |
self.lastmsg.clear() |
| 8222 |
if self.thread.is_alive(): |
| 8223 |
# Consumer may check if thread is still alive. Technically |
| 8224 |
# it shouldn't be at that point when using CallAfter, but e.g. on |
| 8225 |
# OS X there seems to be overlap with the thread counting as |
| 8226 |
# 'alive' even though it already exited |
| 8227 |
self.thread.join() |
| 8228 |
wx.CallAfter(consumer, result, *args, **kwargs) |
| 8229 |
|
| 8230 |
def generate_A2B0(self, profile, clutres=None, logfile=None): |
| 8231 |
"""Generate a profile's A2B0 table (perceptual). |
| 8232 |
|
| 8233 |
Args: |
| 8234 |
profile (Profile): The profile to generate the A2B0 table for. |
| 8235 |
clutres (int, optional): The cLUT resolution to use. If not |
| 8236 |
specified, the resolution of the A2B0 table in the profile |
| 8237 |
will be used. |
| 8238 |
logfile (file-like, optional): A file-like object to write |
| 8239 |
log messages to. If not specified, no logging will be done. |
| 8240 |
|
| 8241 |
Raises: |
| 8242 |
Error: If the profile's connection color space is not XYZ. |
| 8243 |
|
| 8244 |
Returns: |
| 8245 |
bool: True if the A2B0 table was successfully generated, |
| 8246 |
""" |
| 8247 |
# Lab cLUT is currently not implemented and should NOT be used! |
| 8248 |
if profile.connectionColorSpace != b"XYZ": |
| 8249 |
connection_color_space = profile.connectionColorSpace.decode("utf-8") |
| 8250 |
raise Error( |
| 8251 |
lang.getstr( |
| 8252 |
"profile.unsupported", |
| 8253 |
(connection_color_space, connection_color_space), |
| 8254 |
) |
| 8255 |
) |
| 8256 |
|
| 8257 |
if logfile: |
| 8258 |
print("-" * 80) |
| 8259 |
logfile.write("Creating perceptual A2B0 table\n") |
| 8260 |
logfile.write("\n") |
| 8261 |
# Make new A2B0 |
| 8262 |
A2B0 = LUT16Type(None, "A2B0", profile) |
| 8263 |
# Matrix (identity) |
| 8264 |
A2B0.matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] |
| 8265 |
# Input / output curves (linear) |
| 8266 |
channel = [j * 257 for j in range(256)] |
| 8267 |
A2B0.input = [channel for _ in range(3)] |
| 8268 |
A2B0.output = [channel for _ in range(3)] |
| 8269 |
# cLUT |
| 8270 |
if logfile: |
| 8271 |
logfile.write("Generating A2B0 table lookup input values...\n") |
| 8272 |
A2B0.clut = [] |
| 8273 |
if not clutres: |
| 8274 |
clutres = len(profile.tags.A2B0.clut[0]) |
| 8275 |
if logfile: |
| 8276 |
logfile.write(f"cLUT grid res: {clutres:d}\n") |
| 8277 |
vrange = range(clutres) |
| 8278 |
step = 1.0 / (clutres - 1.0) |
| 8279 |
idata = [ |
| 8280 |
[v * step for v in (R, G, B)] |
| 8281 |
for R in vrange |
| 8282 |
for G in vrange |
| 8283 |
for B in vrange |
| 8284 |
] |
| 8285 |
if logfile: |
| 8286 |
logfile.write("Looking up input values through A2B0 table...\n") |
| 8287 |
odata = self.xicclu(profile, idata, pcs="x", logfile=logfile) |
| 8288 |
numrows = len(odata) |
| 8289 |
if numrows != clutres**3: |
| 8290 |
raise ValueError( |
| 8291 |
f"Number of cLUT entries ({numrows}) exceeds cLUT res " |
| 8292 |
f"maximum ({clutres}^3 = {clutres**3})" |
| 8293 |
) |
| 8294 |
XYZbp = list(odata[0]) |
| 8295 |
XYZwp = list(odata[-1]) |
| 8296 |
if logfile: |
| 8297 |
logfile.write("Filling cLUT...\n") |
| 8298 |
for i, (X, Y, Z) in enumerate(odata): |
| 8299 |
if i % clutres == 0: |
| 8300 |
if self.thread_abort: |
| 8301 |
raise Info(lang.getstr("aborted")) |
| 8302 |
A2B0.clut.append([]) |
| 8303 |
if logfile: |
| 8304 |
logfile.write(f"\r{i / (numrows - 1.0):0.0%}") |
| 8305 |
# Apply black point compensation |
| 8306 |
XYZ = colormath.blend_blackpoint(X, Y, Z, XYZbp) |
| 8307 |
XYZ = [v / XYZwp[1] for v in XYZ] |
| 8308 |
A2B0.clut[-1].append([max(v * 32768, 0) for v in XYZ]) |
| 8309 |
if logfile: |
| 8310 |
logfile.write("\n") |
| 8311 |
profile.tags.A2B0 = A2B0 |
| 8312 |
return True |
| 8313 |
|
| 8314 |
def generate_B2A_from_inverse_table( |
| 8315 |
self, |
| 8316 |
profile, |
| 8317 |
clutres=None, |
| 8318 |
source="A2B", |
| 8319 |
tableno=None, |
| 8320 |
bpc=False, |
| 8321 |
smooth=True, |
| 8322 |
rgb_space=None, |
| 8323 |
logfile=None, |
| 8324 |
filename=None, |
| 8325 |
only_input_curves=False, |
| 8326 |
): |
| 8327 |
"""Generate a profile's B2A table by inverting the A2B table. |
| 8328 |
|
| 8329 |
Default A2B1 or A2B0. |
| 8330 |
|
| 8331 |
It is also possible to re-generate a B2A table by interpolating |
| 8332 |
the B2A table itself. |
| 8333 |
|
| 8334 |
Args: |
| 8335 |
profile (Profile): The profile to generate the B2A table for. |
| 8336 |
clutres (int, optional): The cLUT resolution to use. If not |
| 8337 |
specified, the resolution of the A2B table will be used. |
| 8338 |
source (str, optional): The source table to use for generating |
| 8339 |
the B2A table. Can be "A2B" (default) or "B2A". If "B2A", |
| 8340 |
the B2A table will be re-generated by interpolation. |
| 8341 |
tableno (int, optional): The table number to use for the |
| 8342 |
B2A table. If not specified, it will default to 1 if |
| 8343 |
"A2B1" is in the profile's tags, otherwise 0. |
| 8344 |
bpc (bool, optional): Whether to apply black point compensation |
| 8345 |
to the B2A table. Defaults to False. |
| 8346 |
smooth (bool, optional): Whether to apply smoothing to the |
| 8347 |
generated B2A table. Defaults to True. |
| 8348 |
rgb_space (str, optional): The RGB color space to use for the |
| 8349 |
B2A table. If not specified, the RGB color space of the |
| 8350 |
profile will be used. |
| 8351 |
logfile (file-like, optional): A file-like object to write |
| 8352 |
log messages to. If not specified, no logging will be done. |
| 8353 |
filename (str, optional): The filename to save the generated |
| 8354 |
B2A table to. If not specified, the table will not be saved |
| 8355 |
to a file. |
| 8356 |
only_input_curves (bool, optional): If True, only the input |
| 8357 |
curves of the B2A table will be generated, without the |
| 8358 |
cLUT. Defaults to False. |
| 8359 |
|
| 8360 |
Returns: |
| 8361 |
bool: True if the B2A table was successfully generated, |
| 8362 |
False otherwise. |
| 8363 |
""" |
| 8364 |
if tableno is None: |
| 8365 |
tableno = 1 if "A2B1" in profile.tags else 0 |
| 8366 |
if not clutres: |
| 8367 |
if f"B2A{tableno:d}" in profile.tags: |
| 8368 |
tablename = f"B2A{tableno:d}" |
| 8369 |
else: |
| 8370 |
tablename = f"A2B{tableno:d}" |
| 8371 |
clutres = len(profile.tags[tablename].clut[0]) |
| 8372 |
|
| 8373 |
if source == "B2A" and clutres > 23: |
| 8374 |
# B2A interpolation is smoothest when used with a lower cLUT res |
| 8375 |
clutres = 23 |
| 8376 |
|
| 8377 |
if logfile: |
| 8378 |
if source == "A2B": |
| 8379 |
msg = ( |
| 8380 |
f"Generating B2A{tableno:d} table by inverting " |
| 8381 |
f"A2B{tableno:d} table\n" |
| 8382 |
) |
| 8383 |
else: |
| 8384 |
msg = f"Re-generating B2A{tableno:d} table by interpolation\n" |
| 8385 |
logfile.write(msg) |
| 8386 |
logfile.write("\n") |
| 8387 |
|
| 8388 |
cat = profile.guess_cat() or "Bradford" |
| 8389 |
self.log("Using chromatic adaptation transform matrix:", cat) |
| 8390 |
|
| 8391 |
# Note that intent 0 will be colorimetric if no other tables are |
| 8392 |
# present |
| 8393 |
intent = {0: "p", 1: "r", 2: "s"}[tableno] |
| 8394 |
|
| 8395 |
# Lookup RGB -> XYZ for primaries, black- and white point |
| 8396 |
idata = [[0, 0, 0], [1, 1, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]] |
| 8397 |
|
| 8398 |
direction = {"A2B": "f", "B2A": "ib"}[source] |
| 8399 |
odata = self.xicclu(profile, idata, intent, direction, pcs="x") |
| 8400 |
|
| 8401 |
# Scale to Y = 1 |
| 8402 |
XYZwp_abs = odata[1] |
| 8403 |
XYZwpY = odata[1][1] |
| 8404 |
odata = [[n / XYZwpY for n in v] for v in odata] |
| 8405 |
|
| 8406 |
XYZbp = odata[0] |
| 8407 |
XYZwp = odata[1] |
| 8408 |
XYZr = odata[2] |
| 8409 |
XYZg = odata[3] |
| 8410 |
XYZb = odata[4] |
| 8411 |
|
| 8412 |
# Sanity check whitepoint - after normalisation it should be close to |
| 8413 |
# D50 (the ICC PCS white). Use a tolerance rather than an exact rounded |
| 8414 |
# match: a real profile's adapted white is routinely off D50 by ~0.001 |
| 8415 |
# (chromatic adaptation / measurement / 16-bit encoding) and must not be |
| 8416 |
# rejected. The tolerance still catches a grossly wrong white (e.g. from |
| 8417 |
# a failed inverse lookup, which lands far from D50). |
| 8418 |
D50_wp = colormath.get_whitepoint("D50") |
| 8419 |
if ( |
| 8420 |
abs(XYZwp[0] - D50_wp[0]) > 0.01 |
| 8421 |
or abs(XYZwp[1] - D50_wp[1]) > 0.01 |
| 8422 |
or abs(XYZwp[2] - D50_wp[2]) > 0.01 |
| 8423 |
): |
| 8424 |
raise Error( |
| 8425 |
"Argyll CMS xicclu: Invalid white XYZ: {:.4f} {:.4f} {:.4f}".format( |
| 8426 |
*XYZwp_abs |
| 8427 |
) |
| 8428 |
) |
| 8429 |
|
| 8430 |
# Get the primaries |
| 8431 |
XYZrgb = [XYZr, XYZg, XYZb] |
| 8432 |
|
| 8433 |
# Sanity check primaries: |
| 8434 |
# Red Y, Z shall not be higher than X |
| 8435 |
# Green X, Z shall not be higher than Y |
| 8436 |
# Blue X, Y shall not be higher than Z |
| 8437 |
for i, XYZ in enumerate(XYZrgb): |
| 8438 |
for _, v in enumerate(XYZ): |
| 8439 |
if v > XYZ[i]: |
| 8440 |
raise Error( |
| 8441 |
"xicclu: Invalid primary {} XYZ: {:.4f} {:.4f} {:.4f}".format( |
| 8442 |
*("RGB"[i], *XYZ) |
| 8443 |
) |
| 8444 |
) |
| 8445 |
|
| 8446 |
if logfile: |
| 8447 |
logfile.write("Black XYZ: {:.4f} {:.4f} {:.4f}\n".format(*XYZbp)) |
| 8448 |
logfile.write("White XYZ: {:.4f} {:.4f} {:.4f}\n".format(*XYZwp)) |
| 8449 |
for i in range(3): |
| 8450 |
logfile.write( |
| 8451 |
"{} XYZ: {:.4f} {:.4f} {:.4f}\n".format(*("RGB"[i], *XYZrgb[i])) |
| 8452 |
) |
| 8453 |
|
| 8454 |
# Prepare input PCS values |
| 8455 |
if logfile: |
| 8456 |
logfile.write("Generating input curve PCS values...\n") |
| 8457 |
idata = [] |
| 8458 |
numentries = 4096 |
| 8459 |
maxval = numentries - 1.0 |
| 8460 |
vrange = range(numentries) |
| 8461 |
Lbp, abp, bbp = colormath.XYZ2Lab(*[v * 100 for v in XYZbp]) |
| 8462 |
# Method to determine device <-> PCS neutral axis relationship |
| 8463 |
# 0: L* (a*=b*=0) -> RGB |
| 8464 |
# 1: As method 0, but blend a* b* to blackpoint hue |
| 8465 |
# 2: R=G=B -> PCS |
| 8466 |
# 3: As method 0, but blend a* b* to blackpoint hue in XYZ (BPC) |
| 8467 |
method = 2 |
| 8468 |
if method != 2: |
| 8469 |
for i in vrange: |
| 8470 |
L, a, b = i / maxval * 100, 0, 0 |
| 8471 |
if method in (1, 3) and not bpc and XYZbp != [0, 0, 0]: |
| 8472 |
# Blend to blackpoint hue |
| 8473 |
if method == 1: |
| 8474 |
vv = (L - Lbp) / (100.0 - Lbp) # 0 at bp, 1 at wp |
| 8475 |
vv = 1.0 - vv |
| 8476 |
if vv < 0.0: |
| 8477 |
vv = 0.0 |
| 8478 |
elif vv > 1.0: |
| 8479 |
vv = 1.0 |
| 8480 |
vv = math.pow(vv, 40.0) |
| 8481 |
a += vv * abp |
| 8482 |
b += vv * bbp |
| 8483 |
else: |
| 8484 |
X, Y, Z = colormath.Lab2XYZ(L, a, b) |
| 8485 |
XYZ = colormath.blend_blackpoint(X, Y, Z, None, XYZbp) |
| 8486 |
a, b = colormath.XYZ2Lab(*[v * 100 for v in XYZ])[1:] |
| 8487 |
idata.append((L, a, b)) |
| 8488 |
|
| 8489 |
pcs = profile.connectionColorSpace[0:1].lower().decode("utf-8") |
| 8490 |
if source == "B2A": |
| 8491 |
# NOTE: |
| 8492 |
# Argyll's B2A tables are slightly inaccurate: |
| 8493 |
# 0 0 0 PCS -> RGB may give RGB levels > 0 (it should clip |
| 8494 |
# instead). Inversely, 0 0 0 RGB -> PCS (through inverted B2A) |
| 8495 |
# will return PCS values that are too low or zero (ie. not the |
| 8496 |
# black point as expected) |
| 8497 |
|
| 8498 |
# TODO: How to deal with this? |
| 8499 |
# TODO: Erkan Ozgur Yilmaz, please do a research for this issue. |
| 8500 |
pass |
| 8501 |
|
| 8502 |
if method == 2: |
| 8503 |
# lookup RGB -> XYZ values through profile using xicclu to get TRC |
| 8504 |
odata = [] |
| 8505 |
if not bpc: |
| 8506 |
numentries -= 1 |
| 8507 |
maxval -= 1 |
| 8508 |
for i in range(numentries): |
| 8509 |
odata.append([i / maxval] * 3) |
| 8510 |
idata = self.xicclu( |
| 8511 |
profile, odata, intent, {"A2B": "f", "B2A": "ib"}[source], pcs="x" |
| 8512 |
) |
| 8513 |
wY = idata[-1][1] |
| 8514 |
idata = [[v[1] / wY * n for n in XYZwp] for v in idata] |
| 8515 |
# Input curve maps neutral (except near black) XYZ -> RGB |
| 8516 |
idata = [ |
| 8517 |
list( |
| 8518 |
colormath.blend_blackpoint( |
| 8519 |
*v, bp_in=idata[0], bp_out=XYZbp, wp=XYZwp |
| 8520 |
) |
| 8521 |
) |
| 8522 |
for v in idata |
| 8523 |
] |
| 8524 |
if not bpc: |
| 8525 |
numentries += 1 |
| 8526 |
maxval += 1 |
| 8527 |
idata.insert(0, [0, 0, 0]) |
| 8528 |
odata.insert(0, [0, 0, 0]) |
| 8529 |
oXYZ = idata |
| 8530 |
D50 = colormath.get_whitepoint("D50") |
| 8531 |
fpL = [colormath.XYZ2Lab(*[*v, D50])[0] for v in oXYZ] |
| 8532 |
else: |
| 8533 |
oXYZ = [colormath.Lab2XYZ(*v) for v in idata] |
| 8534 |
fpL = [v[0] for v in idata] |
| 8535 |
fpX = [v[0] for v in oXYZ] |
| 8536 |
fpY = [v[1] for v in oXYZ] |
| 8537 |
fpZ = [v[2] for v in oXYZ] |
| 8538 |
|
| 8539 |
if method != 2 and bpc and XYZbp != [0, 0, 0]: |
| 8540 |
if logfile: |
| 8541 |
logfile.write("Applying BPC to input curve PCS values...\n") |
| 8542 |
for i, (L, a, b) in enumerate(idata): |
| 8543 |
X, Y, Z = colormath.Lab2XYZ(L, a, b) |
| 8544 |
X, Y, Z = colormath.blend_blackpoint(X, Y, Z, None, XYZbp) |
| 8545 |
idata[i] = colormath.XYZ2Lab(X * 100, Y * 100, Z * 100) |
| 8546 |
|
| 8547 |
if logfile: |
| 8548 |
logfile.write("Looking up input curve RGB values...\n") |
| 8549 |
|
| 8550 |
direction = {"A2B": "if", "B2A": "b"}[source] |
| 8551 |
|
| 8552 |
if method != 2: |
| 8553 |
# Lookup Lab -> RGB values through profile using xicclu to get TRC |
| 8554 |
odata = self.xicclu( |
| 8555 |
profile, idata, intent, direction, pcs="l", get_clip=True |
| 8556 |
) |
| 8557 |
|
| 8558 |
# Deal with values that got clipped (below black as well as white) |
| 8559 |
do_low_clip = True |
| 8560 |
for i, values in enumerate(odata): |
| 8561 |
if values[3] is True or i == 0: |
| 8562 |
if do_low_clip and (i / maxval * 100 < Lbp or i == 0): |
| 8563 |
# Set to black |
| 8564 |
self.log( |
| 8565 |
"Setting curve entry #{:d} ({:.6f} {:.6f} {:.6f}) to " |
| 8566 |
"black because it got clipped".format(*(i, *values[:3])) |
| 8567 |
) |
| 8568 |
values[:] = [0.0, 0.0, 0.0] |
| 8569 |
elif i == maxval and [round(v, 4) for v in values[:3]] == [1, 1, 1]: |
| 8570 |
# Set to white |
| 8571 |
self.log( |
| 8572 |
"Setting curve entry #{:d} ({:.6f} {:.6f} {:.6f}) to " |
| 8573 |
"white because it got clipped".format(*(i, *values[:3])) |
| 8574 |
) |
| 8575 |
values[:] = [1.0, 1.0, 1.0] |
| 8576 |
else: |
| 8577 |
# First non-clipping value disables low clipping |
| 8578 |
do_low_clip = False |
| 8579 |
if len(values) > 3: |
| 8580 |
values.pop() |
| 8581 |
|
| 8582 |
# Sanity check white |
| 8583 |
if ( |
| 8584 |
round(odata[-1][0], 3) != 1 |
| 8585 |
or round(odata[-1][1], 3) != 1 |
| 8586 |
or round(odata[-1][2], 3) != 1 |
| 8587 |
): |
| 8588 |
wrgb_warning = ( |
| 8589 |
"Warning: xicclu: Suspicious white RGB: " |
| 8590 |
"{:.4f} {:.4f} {:.4f}\n".format(*odata[-1]) |
| 8591 |
) |
| 8592 |
if logfile: |
| 8593 |
logfile.write(wrgb_warning) |
| 8594 |
else: |
| 8595 |
print(wrgb_warning) |
| 8596 |
|
| 8597 |
xpR = [v[0] for v in odata] |
| 8598 |
xpG = [v[1] for v in odata] |
| 8599 |
xpB = [v[2] for v in odata] |
| 8600 |
|
| 8601 |
# Initialize B2A |
| 8602 |
if only_input_curves: |
| 8603 |
# Use existing B2A table |
| 8604 |
itable = profile.tags[f"B2A{tableno:d}"] |
| 8605 |
else: |
| 8606 |
# Create new B2A table |
| 8607 |
itable = LUT16Type(None, f"B2A{tableno:d}", profile) |
| 8608 |
|
| 8609 |
use_cam_clipping = True |
| 8610 |
|
| 8611 |
# Setup matrix |
| 8612 |
scale = 1 + (32767 / 32768.0) |
| 8613 |
m3 = colormath.Matrix3x3(((scale, 0, 0), (0, scale, 0), (0, 0, scale))) |
| 8614 |
|
| 8615 |
matrices = [] |
| 8616 |
|
| 8617 |
if profile.connectionColorSpace == b"Lab": |
| 8618 |
# L*a*b* LUT |
| 8619 |
# Use identity matrix for Lab as mandated by ICC spec |
| 8620 |
itable.matrix = colormath.Matrix3x3([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) |
| 8621 |
m2 = None |
| 8622 |
elif only_input_curves: |
| 8623 |
# Use existing matrix |
| 8624 |
m2 = itable.matrix * m3.inverted() |
| 8625 |
|
| 8626 |
# Scale for BPC |
| 8627 |
XYZbp_relcol = self.xicclu(profile, [[0, 0, 0]], pcs="x")[0] |
| 8628 |
XYZbp_relcol_D50 = [v * XYZbp_relcol[1] for v in XYZwp] |
| 8629 |
m2i = m2.inverted() |
| 8630 |
XYZrgb = [m2i * (1, 0, 0), m2i * (0, 1, 0), m2i * (0, 0, 1)] |
| 8631 |
for i, XYZ in enumerate(XYZrgb): |
| 8632 |
XYZrgb[i] = colormath.apply_bpc( |
| 8633 |
*XYZ, bp_in=(0, 0, 0), bp_out=XYZbp_relcol_D50, wp_out=XYZwp |
| 8634 |
) |
| 8635 |
else: |
| 8636 |
# Use a matrix that scales the profile colorspace into the XYZ |
| 8637 |
# encoding range, to make optimal use of the cLUT grid points |
| 8638 |
|
| 8639 |
xyYrgb = [colormath.XYZ2xyY(*XYZ) for XYZ in XYZrgb] |
| 8640 |
area1 = 0.5 * abs( |
| 8641 |
sum( |
| 8642 |
x0 * y1 - x1 * y0 |
| 8643 |
for ((x0, y0, Y0), (x1, y1, Y1)) in zip( |
| 8644 |
xyYrgb, xyYrgb[1:] + [xyYrgb[0]] |
| 8645 |
) |
| 8646 |
) |
| 8647 |
) |
| 8648 |
|
| 8649 |
if logfile: |
| 8650 |
logfile.write("Setting up matrix\n") |
| 8651 |
|
| 8652 |
# RGB spaces used as PCS candidates. |
| 8653 |
# Six synthetic RGB spaces that are large enough to encompass |
| 8654 |
# display gamuts (except the LaserVue one) found on |
| 8655 |
# http://www.tftcentral.co.uk/articles/pointers_gamut.htm |
| 8656 |
# aswell as a selection of around two dozen profiles from openSUSE |
| 8657 |
# ICC Profile Taxi database aswell as other user contributions |
| 8658 |
rgb_spaces = [] |
| 8659 |
|
| 8660 |
rgb = [ |
| 8661 |
("R", (1.0, 0.0, 0.0)), |
| 8662 |
("G", (0.0, 1.0, 0.0)), |
| 8663 |
("B", (0.0, 0.0, 1.0)), |
| 8664 |
] |
| 8665 |
|
| 8666 |
# Add matrix from just white + 50% gray + black + primaries |
| 8667 |
# as first entry |
| 8668 |
# outname = os.path.splitext(profile.filename)[0] |
| 8669 |
# if not os.path.isfile(outname + ".ti3"): |
| 8670 |
# if isinstance(profile.tags.get("targ"), Text): |
| 8671 |
# with open(outname + ".ti3", "wb") as ti3: |
| 8672 |
# ti3.write(profile.tags.targ) |
| 8673 |
# else: |
| 8674 |
# ti1name = "ti1/d3-e4-s2-g28-m0-b0-f0.ti1" |
| 8675 |
# ti1 = get_data_path(ti1name) |
| 8676 |
# if not ti1: |
| 8677 |
# raise Error(lang.getstr("file.missing", ti1name)) |
| 8678 |
# ti1, ti3, gray = self.ti1_lookup_to_ti3(ti1, profile, |
| 8679 |
# intent="a", |
| 8680 |
# white_patches=1) |
| 8681 |
# outname += "." + ti1name |
| 8682 |
# ti3.write(outname + ".ti3") |
| 8683 |
# result = self._create_matrix_profile(outname, omit="TRC") |
| 8684 |
result = True |
| 8685 |
if isinstance(result, Exception) or not result: |
| 8686 |
if logfile: |
| 8687 |
logfile.write("Warning - could not compute RGBW matrix") |
| 8688 |
if result: |
| 8689 |
logfile.write(": " + str(result)) |
| 8690 |
else: |
| 8691 |
logfile.write("\n") |
| 8692 |
else: |
| 8693 |
comp_rgb_space = [2.2, "D50"] |
| 8694 |
# Oversaturate primaries to add headroom |
| 8695 |
wx, wy = colormath.XYZ2xyY(*XYZwp)[:2] |
| 8696 |
# Determine saturation factor by looking at distance between |
| 8697 |
# Rec. 2020 blue and actual blue primary |
| 8698 |
bx, by, bY = colormath.XYZ2xyY( |
| 8699 |
*colormath.adapt( |
| 8700 |
*colormath.RGB2XYZ(0, 0, 1, "Rec. 2020"), |
| 8701 |
whitepoint_source="D65", |
| 8702 |
cat=cat, |
| 8703 |
) |
| 8704 |
) |
| 8705 |
bx2, by2, bY2 = xyYrgb[2] |
| 8706 |
bu, bv = colormath.xyY2Lu_v_(bx, by, bY)[1:] |
| 8707 |
bu2, bv2 = colormath.xyY2Lu_v_(bx2, by2, bY2)[1:] |
| 8708 |
dist = math.sqrt((bx - bx2) ** 2 + (by - by2) ** 2) |
| 8709 |
sat = 1 + math.ceil(dist * 100) / 100.0 |
| 8710 |
if logfile: |
| 8711 |
logfile.write( |
| 8712 |
"Increasing saturation of actual " |
| 8713 |
"primaries for PCS candidate to " |
| 8714 |
f"{sat:0.0%}...\n".format(round(sat * 100)) |
| 8715 |
) |
| 8716 |
for i, channel in enumerate("rgb"): |
| 8717 |
# x, y, Y = result.tags[channel + "XYZ"].pcs.xyY |
| 8718 |
x, y, Y = xyYrgb[i] |
| 8719 |
if logfile: |
| 8720 |
logfile.write(f"{channel.upper()} xy {x:.6f} {y:.6f} -> ") |
| 8721 |
x, y, Y = colormath.xyYsaturation(x, y, Y, wx, wy, sat) |
| 8722 |
if logfile: |
| 8723 |
logfile.write(f"{x:.6f} {y:.6f}\n") |
| 8724 |
xyYrgb[i] = x, y, Y |
| 8725 |
(rx, ry, rY), (gx, gy, gY), (bx, by, bY) = xyYrgb |
| 8726 |
mtx = colormath.rgb_to_xyz_matrix(rx, ry, gx, gy, bx, by, XYZwp) |
| 8727 |
for _channel, components in rgb: |
| 8728 |
X, Y, Z = mtx * components |
| 8729 |
comp_rgb_space.append(colormath.XYZ2xyY(X, Y, Z)) |
| 8730 |
comp_rgb_space.append("PCS candidate based on actual primaries") |
| 8731 |
rgb_spaces.append(comp_rgb_space) |
| 8732 |
|
| 8733 |
# A colorspace that encompasses Rec709. Uses Rec. 2020 blue. |
| 8734 |
rgb_spaces.append( |
| 8735 |
[ |
| 8736 |
2.2, |
| 8737 |
"D50", |
| 8738 |
[0.68280181011, 0.315096403371, 0.224182128906], |
| 8739 |
[0.310096375087, 0.631250246526, 0.73258972168], |
| 8740 |
[0.129244796433, 0.0471357502953, 0.0432281494141], |
| 8741 |
"Rec709-encompassing, variant 1", |
| 8742 |
] |
| 8743 |
) |
| 8744 |
|
| 8745 |
# A colorspace that encompasses Rec709. Uses slightly different |
| 8746 |
# primaries (based on WLED and B+RG LED) than variant 1. |
| 8747 |
rgb_spaces.append( |
| 8748 |
[ |
| 8749 |
2.2, |
| 8750 |
"D50", |
| 8751 |
[0.664580313612, 0.329336320112, 0.228820800781], |
| 8752 |
[0.318985161632, 0.644740328564, 0.742568969727], |
| 8753 |
[0.143284983488, 0.0303535582465, 0.0286102294922], |
| 8754 |
"Rec709-encompassing, variant 2", |
| 8755 |
] |
| 8756 |
) |
| 8757 |
|
| 8758 |
# A colorspace that encompasses Rec709 with imaginary red and blue |
| 8759 |
rgb_spaces.append( |
| 8760 |
[ |
| 8761 |
2.2, |
| 8762 |
"D50", |
| 8763 |
[0.672053135694, 0.331936091367, 0.250122070312], |
| 8764 |
[0.319028093312, 0.644705491217, 0.710144042969], |
| 8765 |
[0.113899645442, 0.0424325604954, 0.0396270751953], |
| 8766 |
"Rec709-encompassing, variant 3", |
| 8767 |
] |
| 8768 |
) |
| 8769 |
|
| 8770 |
# A colorspace that encompasses Rec709. Uses red and blue from |
| 8771 |
# variant 2, but a slightly different green primary. |
| 8772 |
rgb_spaces.append( |
| 8773 |
[ |
| 8774 |
2.2, |
| 8775 |
"D50", |
| 8776 |
[0.664627993657, 0.329338357942, 0.244033813477], |
| 8777 |
[0.300155771607, 0.640946446796, 0.728302001953], |
| 8778 |
[0.143304213944, 0.0303410650333, 0.0276641845703], |
| 8779 |
"Rec709-encompassing, variant 4", |
| 8780 |
] |
| 8781 |
) |
| 8782 |
|
| 8783 |
# A colorspace with Plasma-like primaries. Uses Rec. 2020 blue. |
| 8784 |
rgb_spaces.append( |
| 8785 |
[ |
| 8786 |
2.2, |
| 8787 |
"D50", |
| 8788 |
[0.692947816539, 0.30857396028, 0.244430541992], |
| 8789 |
[0.284461719244, 0.70017174365, 0.709167480469], |
| 8790 |
[0.129234824405, 0.0471509419335, 0.0464019775391], |
| 8791 |
"SMPTE-431-2/DCI-P3-encompassing, variant 1", |
| 8792 |
] |
| 8793 |
) |
| 8794 |
|
| 8795 |
# A colorspace that encompasses both AdobeRGB and NTSC1953. Uses |
| 8796 |
# Rec. 2020 blue. |
| 8797 |
rgb_spaces.append( |
| 8798 |
[ |
| 8799 |
2.2, |
| 8800 |
"D50", |
| 8801 |
[0.680082575358, 0.319746686121, 0.314331054688], |
| 8802 |
[0.200003470174, 0.730003123156, 0.641983032227], |
| 8803 |
[0.129238369699, 0.0471305063812, 0.0436706542969], |
| 8804 |
"AdobeRGB-NTSC1953-hybrid, variant 1", |
| 8805 |
] |
| 8806 |
) |
| 8807 |
|
| 8808 |
# A colorspace with Plasma-like primaries. Uses Rec. 2020 blue. |
| 8809 |
# More saturated green primary than variant 1. |
| 8810 |
rgb_spaces.append( |
| 8811 |
[ |
| 8812 |
2.2, |
| 8813 |
"D50", |
| 8814 |
[0.692943297796, 0.308579731457, 0.268966674805], |
| 8815 |
[0.249088838269, 0.730263586072, 0.684844970703], |
| 8816 |
[0.129230721306, 0.047147329564, 0.0461883544922], |
| 8817 |
"SMPTE-431-2/DCI-P3-encompassing, variant 2", |
| 8818 |
] |
| 8819 |
) |
| 8820 |
|
| 8821 |
# A colorspace that encompasses both AdobeRGB and NTSC1953. |
| 8822 |
# Different, more saturated primaries than variant 1. |
| 8823 |
rgb_spaces.append( |
| 8824 |
[ |
| 8825 |
2.2, |
| 8826 |
"D50", |
| 8827 |
[0.700603882817, 0.299296301842, 0.274520874023], |
| 8828 |
[0.200006562972, 0.75, 0.697494506836], |
| 8829 |
[0.143956453416, 0.0296952711131, 0.0279693603516], |
| 8830 |
"AdobeRGB-NTSC1953-hybrid, variant 2", |
| 8831 |
] |
| 8832 |
) |
| 8833 |
|
| 8834 |
# A colorspace that encompasses DCI P3 with imaginary red and blue |
| 8835 |
rgb_spaces.append( |
| 8836 |
[ |
| 8837 |
2.2, |
| 8838 |
"D50", |
| 8839 |
[0.699964323939, 0.312334528794, 0.253814697266], |
| 8840 |
[0.284337791321, 0.68212854805, 0.73779296875], |
| 8841 |
[0.098165262763, 0.00937830372063, 0.00839233398438], |
| 8842 |
"SMPTE-431-2/DCI-P3-encompassing, variant 3", |
| 8843 |
] |
| 8844 |
) |
| 8845 |
|
| 8846 |
# A colorspace that encompasses DCI P3 with imaginary red and blue |
| 8847 |
# (red and blue are practically the same as Rec2020-encompassing) |
| 8848 |
rgb_spaces.append( |
| 8849 |
[ |
| 8850 |
2.2, |
| 8851 |
"D50", |
| 8852 |
[0.717267960557, 0.29619267491, 0.231002807617], |
| 8853 |
[0.284277504105, 0.682088122605, 0.760604858398], |
| 8854 |
[0.0981978292034, 0.00940337224384, 0.00840759277344], |
| 8855 |
"SMPTE-431-2/DCI-P3-encompassing, variant 4", |
| 8856 |
] |
| 8857 |
) |
| 8858 |
|
| 8859 |
# Rec. 2020 |
| 8860 |
rgb_spaces.append( |
| 8861 |
[ |
| 8862 |
2.2, |
| 8863 |
"D50", |
| 8864 |
[0.7084978651, 0.293540723619, 0.279037475586], |
| 8865 |
[0.190200063067, 0.775375775201, 0.675354003906], |
| 8866 |
[0.129244405192, 0.0471399056886, 0.0456085205078], |
| 8867 |
"Rec2020", |
| 8868 |
] |
| 8869 |
) |
| 8870 |
|
| 8871 |
# A colorspace that encompasses Rec2020 with imaginary primaries |
| 8872 |
rgb_spaces.append( |
| 8873 |
[ |
| 8874 |
2.2, |
| 8875 |
"D50", |
| 8876 |
[0.71715243505, 0.296225595183, 0.291244506836], |
| 8877 |
[0.191129060214, 0.795212673762, 0.700057983398], |
| 8878 |
[0.0981403936826, 0.00939694681658, 0.00869750976562], |
| 8879 |
"Rec2020-encompassing", |
| 8880 |
] |
| 8881 |
) |
| 8882 |
|
| 8883 |
if rgb_space: |
| 8884 |
rgb_space = list(rgb_space[:5]) |
| 8885 |
rgb_spaces = [*rgb_space, "Custom"] |
| 8886 |
|
| 8887 |
# Find smallest candidate that encompasses space defined by actual |
| 8888 |
# primaries |
| 8889 |
if logfile: |
| 8890 |
logfile.write("Checking for suitable PCS candidate...\n") |
| 8891 |
# pcs_candidate = None |
| 8892 |
pcs_candidates = [] |
| 8893 |
XYZsrgb = [] |
| 8894 |
for _channel, components in rgb: |
| 8895 |
XYZsrgb.append( |
| 8896 |
colormath.adapt( |
| 8897 |
*colormath.RGB2XYZ(*components), |
| 8898 |
whitepoint_source="D65", |
| 8899 |
cat=cat, |
| 8900 |
) |
| 8901 |
) |
| 8902 |
XYZrgb_sequence = [XYZrgb, XYZsrgb] |
| 8903 |
for rgb_space in rgb_spaces: |
| 8904 |
if rgb_space[1] not in ("D50", colormath.get_whitepoint("D50")): |
| 8905 |
# Adapt to D50 |
| 8906 |
for i in range(3): |
| 8907 |
X, Y, Z = colormath.xyY2XYZ(*rgb_space[2 + i]) |
| 8908 |
X, Y, Z = colormath.adapt(X, Y, Z, rgb_space[1], cat=cat) |
| 8909 |
rgb_space[2 + i] = colormath.XYZ2xyY(X, Y, Z) |
| 8910 |
rgb_space[1] = "D50" |
| 8911 |
|
| 8912 |
extremes = [] |
| 8913 |
skip = False |
| 8914 |
for XYZrgb in XYZrgb_sequence: |
| 8915 |
for i, color in enumerate(["red", "green", "blue"]): |
| 8916 |
RGB = colormath.XYZ2RGB( |
| 8917 |
XYZrgb[i][0], |
| 8918 |
XYZrgb[i][1], |
| 8919 |
XYZrgb[i][2], |
| 8920 |
rgb_space=rgb_space, |
| 8921 |
clamp=False, |
| 8922 |
) |
| 8923 |
maxima = max(RGB) |
| 8924 |
minima = min(RGB) |
| 8925 |
if minima < 0: |
| 8926 |
maxima += abs(minima) |
| 8927 |
if XYZrgb is XYZsrgb: |
| 8928 |
if maxima > 1 and color == "blue": |
| 8929 |
# We want our PCS candiate to contain Rec. 709 |
| 8930 |
# blue, which may not be the case for our |
| 8931 |
# candidate based off the actual display |
| 8932 |
# primaries. Blue region is typically the one |
| 8933 |
# where the most artifacts would be visible in |
| 8934 |
# color conversions if the source blue is |
| 8935 |
# clipped |
| 8936 |
if logfile: |
| 8937 |
logfile.write( |
| 8938 |
f"Skipping {rgb_space[-1]} because it does " |
| 8939 |
f"not encompass Rec. 709 {color}\n" |
| 8940 |
) |
| 8941 |
skip = True |
| 8942 |
break |
| 8943 |
else: |
| 8944 |
extremes.append(maxima) |
| 8945 |
if skip: |
| 8946 |
break |
| 8947 |
if skip: |
| 8948 |
continue |
| 8949 |
# Check area % (in xy for simplicity's sake) |
| 8950 |
xyYrgb = rgb_space[2:5] |
| 8951 |
area2 = 0.5 * abs( |
| 8952 |
sum( |
| 8953 |
x0 * y1 - x1 * y0 |
| 8954 |
for ((x0, y0, Y0), (x1, y1, Y1)) in zip( |
| 8955 |
xyYrgb, xyYrgb[1:] + [xyYrgb[0]] |
| 8956 |
) |
| 8957 |
) |
| 8958 |
) |
| 8959 |
if logfile: |
| 8960 |
logfile.write( |
| 8961 |
f"{rgb_space[-1]} " |
| 8962 |
f"fit: {round(1.0 / max(extremes), 2):.2f} " |
| 8963 |
f"(area: {area1 / area2:.2%})\n" |
| 8964 |
) |
| 8965 |
pcs_candidates.append((area1 / area2, 1.0 / max(extremes), rgb_space)) |
| 8966 |
# Check if tested RGB space contains actual primaries |
| 8967 |
if round(max(extremes), 2) <= 1.0: |
| 8968 |
break |
| 8969 |
|
| 8970 |
XYZrgb = [] |
| 8971 |
if False: # if not pcs_candidate: # NEVER? |
| 8972 |
# Create quick medium quality shaper+matrix profile and use the |
| 8973 |
# matrix from that |
| 8974 |
if logfile: |
| 8975 |
logfile.write( |
| 8976 |
"No suitable PCS candidate. Computing best fit matrix...\n" |
| 8977 |
) |
| 8978 |
# Lookup small testchart so profile computation finishes quickly |
| 8979 |
ti1name = "ti1/d3-e4-s5-g52-m5-b0-f0.ti1" |
| 8980 |
ti1 = get_data_path(ti1name) |
| 8981 |
if not ti1: |
| 8982 |
raise Error(lang.getstr("file.missing", ti1name)) |
| 8983 |
ti1, ti3, gray = self.ti1_lookup_to_ti3( |
| 8984 |
ti1, profile, intent="a", white_patches=1 |
| 8985 |
) |
| 8986 |
dirname, basename = os.path.split(profile.filename) |
| 8987 |
basepath = os.path.join( |
| 8988 |
dirname, f".{os.path.splitext(basename)[0]}-MTX.tmp" |
| 8989 |
) |
| 8990 |
ti3.write(f"{basepath}.ti3") |
| 8991 |
# Calculate profile |
| 8992 |
cmd, args = get_argyll_util("colprof"), ["-v", "-qm", "-as", basepath] |
| 8993 |
result = self.exec_cmd( |
| 8994 |
cmd, |
| 8995 |
args, |
| 8996 |
capture_output=True, |
| 8997 |
sessionlogfile=getattr(self, "sessionlogfile", None), |
| 8998 |
) |
| 8999 |
if isinstance(result, Exception): |
| 9000 |
raise result |
| 9001 |
if result: |
| 9002 |
mtx = ICCProfile(f"{basepath}{PROFILE_EXT}") |
| 9003 |
for column in "rgb": |
| 9004 |
tag = mtx.tags.get(column + "XYZ") |
| 9005 |
if isinstance(tag, XYZType): |
| 9006 |
XYZrgb.append(list(tag.values())) |
| 9007 |
# os.remove(basepath + ".ti3") |
| 9008 |
# os.remove(basepath + profile_ext) |
| 9009 |
if not XYZrgb: |
| 9010 |
raise Error( |
| 9011 |
lang.getstr( |
| 9012 |
"profile.required_tags_missing", "rXYZ/gXYZ/bXYZ" |
| 9013 |
) |
| 9014 |
) |
| 9015 |
# pcs_candidate = "BestFit" |
| 9016 |
else: |
| 9017 |
# If clutres is -1 (auto), set it depending on area coverage |
| 9018 |
if clutres == -1: |
| 9019 |
if area1 / area2 <= 0.51: |
| 9020 |
clutres = 45 |
| 9021 |
elif area1 / area2 <= 0.73: |
| 9022 |
clutres = 33 |
| 9023 |
|
| 9024 |
# Use PCS candidate with best fit |
| 9025 |
# (best fit is the smallest fit greater or equal 1 and |
| 9026 |
# largest possible coverage) |
| 9027 |
pcs_candidates.sort(key=lambda row_: (-row_[0], row_[1])) |
| 9028 |
rgb_space = None |
| 9029 |
for _coverage, fit, rgb_space_inner in pcs_candidates: |
| 9030 |
if round(fit, 2) >= 1: |
| 9031 |
rgb_space = rgb_space_inner |
| 9032 |
break |
| 9033 |
if rgb_space is None: |
| 9034 |
if not pcs_candidates: |
| 9035 |
raise Error(lang.getstr("profile.no_suitable_pcs_candidate")) |
| 9036 |
# None of the reference gamuts fully encompass the |
| 9037 |
# display's actual primaries. Fall back to the |
| 9038 |
# candidate that clips the least instead of crashing. |
| 9039 |
rgb_space = max(pcs_candidates, key=lambda row_: row_[1])[2] |
| 9040 |
if logfile: |
| 9041 |
logfile.write(f"Using primaries: {rgb_space[-1]}\n") |
| 9042 |
for _, components in rgb: |
| 9043 |
XYZrgb.append(colormath.RGB2XYZ(*components, rgb_space=rgb_space)) |
| 9044 |
# pcs_candidate = rgb_space[-1] |
| 9045 |
|
| 9046 |
for i in range(3): |
| 9047 |
logfile.write( |
| 9048 |
"Using {} XYZ: {:.4f} {:.4f} {:.4f}\n".format( |
| 9049 |
*("RGB"[i], *XYZrgb[i]) |
| 9050 |
) |
| 9051 |
) |
| 9052 |
|
| 9053 |
if profile.connectionColorSpace == b"XYZ": |
| 9054 |
# Construct the final matrix |
| 9055 |
Xr, Yr, Zr = XYZrgb[0] |
| 9056 |
Xg, Yg, Zg = XYZrgb[1] |
| 9057 |
Xb, Yb, Zb = XYZrgb[2] |
| 9058 |
if logfile: |
| 9059 |
logfile.write( |
| 9060 |
"R+G+B XYZ: " |
| 9061 |
f"{Xr + Xg + Xb:.4f} {Yr + Yg + Yb:.4f} {Zr + Zg + Zb:.4f}\n" |
| 9062 |
) |
| 9063 |
m1 = colormath.Matrix3x3( |
| 9064 |
((Xr, Xg, Xb), (Yr, Yg, Yb), (Zr, Zg, Zb)) |
| 9065 |
).inverted() |
| 9066 |
matrices.append(m1) |
| 9067 |
Sr, Sg, Sb = m1 * XYZwp |
| 9068 |
if logfile: |
| 9069 |
logfile.write(f"Correction factors: {Sr:.4f} {Sg:.4f} {Sb:.4f}\n") |
| 9070 |
m2 = colormath.Matrix3x3( |
| 9071 |
( |
| 9072 |
(Sr * Xr, Sg * Xg, Sb * Xb), |
| 9073 |
(Sr * Yr, Sg * Yg, Sb * Yb), |
| 9074 |
(Sr * Zr, Sg * Zg, Sb * Zb), |
| 9075 |
) |
| 9076 |
).inverted() |
| 9077 |
matrices.append(m2) |
| 9078 |
matrices.append(m3) |
| 9079 |
|
| 9080 |
for m, matrix in enumerate(matrices): |
| 9081 |
if logfile: |
| 9082 |
logfile.write(f"Matrix {m + 1:d}:\n") |
| 9083 |
for row in matrix: |
| 9084 |
logfile.write(f"{row!r}\n") |
| 9085 |
|
| 9086 |
itable.matrix = m2 * m3 |
| 9087 |
if logfile: |
| 9088 |
logfile.write("Final matrix:\n") |
| 9089 |
for row in itable.matrix: |
| 9090 |
logfile.write(f"{row!r}\n") |
| 9091 |
|
| 9092 |
if logfile: |
| 9093 |
logfile.write("Applying matrix to input curve XYZ values...\n") |
| 9094 |
# Apply matrix |
| 9095 |
rX = [] |
| 9096 |
rY = [] |
| 9097 |
rZ = [] |
| 9098 |
for i in vrange: |
| 9099 |
X, Y, Z = fpX[i], fpY[i], fpZ[i] |
| 9100 |
X, Y, Z = m2 * (X, Y, Z) |
| 9101 |
rX.append(X) |
| 9102 |
rY.append(Y) |
| 9103 |
rZ.append(Z) |
| 9104 |
interp = ( |
| 9105 |
colormath.Interp(xpR, rX), |
| 9106 |
colormath.Interp(xpG, rY), |
| 9107 |
colormath.Interp(xpB, rZ), |
| 9108 |
) |
| 9109 |
rinterp = ( |
| 9110 |
colormath.Interp(rX, xpR), |
| 9111 |
colormath.Interp(rY, xpG), |
| 9112 |
colormath.Interp(rZ, xpB), |
| 9113 |
) |
| 9114 |
Linterp = None |
| 9115 |
else: |
| 9116 |
Lscale = 65280.0 / 65535.0 |
| 9117 |
oldmin = (xpR[0] + xpG[0] + xpB[0]) / 3.0 |
| 9118 |
oldmax = (xpR[-1] + xpG[-1] + xpB[-1]) / 3.0 |
| 9119 |
oldrange = oldmax - oldmin |
| 9120 |
newmin = 0.0 |
| 9121 |
newmax = 100 |
| 9122 |
newrange = newmax - newmin |
| 9123 |
xpL = [] |
| 9124 |
for i in vrange: |
| 9125 |
v = (xpR[i] + xpG[i] + xpB[i]) / 3.0 |
| 9126 |
v = max((((v - oldmin) * newrange) / oldrange) + newmin, 0) |
| 9127 |
xpL.append(v) |
| 9128 |
Linterp = colormath.Interp(xpL, fpL) |
| 9129 |
rLinterp = colormath.Interp(fpL, xpL) |
| 9130 |
interp = None |
| 9131 |
# Set input curves |
| 9132 |
# Apply inverse TRC to input values to distribute them |
| 9133 |
# optimally across cLUT grid points |
| 9134 |
if logfile: |
| 9135 |
logfile.write("Generating input curves...\n") |
| 9136 |
itable.input = [[], [], []] |
| 9137 |
for j in vrange: |
| 9138 |
if self.thread_abort: |
| 9139 |
raise Info(lang.getstr("aborted")) |
| 9140 |
if profile.connectionColorSpace == b"XYZ": |
| 9141 |
v = [rinterp[i](j / maxval) for i in range(3)] |
| 9142 |
else: |
| 9143 |
# CIELab PCS encoding |
| 9144 |
v = [rLinterp(j / (maxval * Lscale) * 100) / 100.0] |
| 9145 |
v.extend([j / maxval] * 2) |
| 9146 |
for i in range(len(itable.input)): |
| 9147 |
itable.input[i].append(min(v[i] * 65535, 65535)) |
| 9148 |
if logfile and j % math.floor(maxval / 100.0) == 0: |
| 9149 |
logfile.write(f"\r{j / maxval:0.0%}") |
| 9150 |
if logfile: |
| 9151 |
logfile.write("\n") |
| 9152 |
if False: # if method and not bpc: |
| 9153 |
# Force the blackpoint - NEVER |
| 9154 |
if logfile: |
| 9155 |
logfile.write("Forcing B2A input curve blackpoint...\n") |
| 9156 |
XYZbp_m = m2 * XYZbp |
| 9157 |
for i in range(3): |
| 9158 |
black_index = math.ceil(maxval * XYZbp_m[i]) |
| 9159 |
if logfile: |
| 9160 |
logfile.write(f"Channel #{i:d}\n") |
| 9161 |
for j in range(black_index + 1): |
| 9162 |
v = 0 |
| 9163 |
if logfile: |
| 9164 |
logfile.write(f"#{j:d} {itable.input[i][j]:d} -> {v:d}\n") |
| 9165 |
itable.input[i][j] = v |
| 9166 |
|
| 9167 |
if only_input_curves: |
| 9168 |
# We are done |
| 9169 |
return True |
| 9170 |
|
| 9171 |
if clutres == -1: |
| 9172 |
# Auto |
| 9173 |
# Counteract L*a*b* cLUT accuracy loss when smoothing. |
| 9174 |
# With a res of 45, about the same accuracy as when using |
| 9175 |
# colprof B2A with a res of 33 and no smoothing. |
| 9176 |
# This is not necessary with XYZ cLUT as the accuracy is always |
| 9177 |
# higher than colprof baseline due to restricting the XYZ space |
| 9178 |
# with a matrix. |
| 9179 |
clutres = 45 if pcs == "l" and smooth else 33 |
| 9180 |
step = 1.0 / (clutres - 1.0) |
| 9181 |
do_lookup = True |
| 9182 |
if do_lookup: |
| 9183 |
# Generate inverse table lookup input values |
| 9184 |
|
| 9185 |
# Use slightly less than equal the amount of CPUs for workers |
| 9186 |
# for best utilization (each worker has 2 xicclu sub-processes) |
| 9187 |
num_cpus = cpu_count() |
| 9188 |
num_workers = min(max(num_cpus, 1), clutres) |
| 9189 |
if num_cpus > 2: |
| 9190 |
num_workers = int(num_workers * 0.75) |
| 9191 |
|
| 9192 |
if logfile: |
| 9193 |
logfile.write( |
| 9194 |
f"Generating {source}{tableno:d} table lookup input values...\n" |
| 9195 |
) |
| 9196 |
logfile.write(f"cLUT grid res: {clutres:d}\n") |
| 9197 |
logfile.write( |
| 9198 |
"Looking up input values through " |
| 9199 |
f"{source}{tableno:d} table ({num_workers:d} workers)...\n" |
| 9200 |
) |
| 9201 |
logfile.write( |
| 9202 |
"{} CAM Jab for clipping\n".format( |
| 9203 |
(use_cam_clipping and "Using") or "Not using" |
| 9204 |
) |
| 9205 |
) |
| 9206 |
|
| 9207 |
idata = [] |
| 9208 |
odata1 = [] |
| 9209 |
odata2 = [] |
| 9210 |
|
| 9211 |
threshold = int((clutres - 1) * 0.75) |
| 9212 |
threshold2 = int((clutres - 1) / 3) |
| 9213 |
|
| 9214 |
for slices in pool_slice( |
| 9215 |
_mp_generate_B2A_clut, |
| 9216 |
list(range(clutres)), |
| 9217 |
( |
| 9218 |
profile.filename, |
| 9219 |
intent, |
| 9220 |
direction, |
| 9221 |
pcs, |
| 9222 |
use_cam_clipping, |
| 9223 |
clutres, |
| 9224 |
step, |
| 9225 |
threshold, |
| 9226 |
threshold2, |
| 9227 |
interp, |
| 9228 |
Linterp, |
| 9229 |
m2, |
| 9230 |
XYZbp, |
| 9231 |
XYZwp, |
| 9232 |
bpc, |
| 9233 |
lang.getstr("aborted"), |
| 9234 |
), |
| 9235 |
{}, |
| 9236 |
num_workers, |
| 9237 |
self.thread_abort, |
| 9238 |
logfile, |
| 9239 |
num_batches=clutres // 9, |
| 9240 |
): |
| 9241 |
for i, data in enumerate((idata, odata1, odata2)): |
| 9242 |
data.extend(slices[i]) |
| 9243 |
|
| 9244 |
if logfile: |
| 9245 |
logfile.write("\n") |
| 9246 |
if logfile and (pcs == "x" or clutres // 2 != clutres / 2.0): |
| 9247 |
if pcs == "x": |
| 9248 |
iXYZbp = idata[0] |
| 9249 |
iXYZwp = idata[-1] |
| 9250 |
logfile.write(f"Input black XYZ: {iXYZbp}\n") |
| 9251 |
logfile.write(f"Input white XYZ: {iXYZwp}\n") |
| 9252 |
else: |
| 9253 |
iLabbp = idata[clutres * (clutres // 2) + clutres // 2] |
| 9254 |
iLabwp = idata[ |
| 9255 |
( |
| 9256 |
clutres**2 * (clutres - 1) |
| 9257 |
+ clutres * (clutres // 2) |
| 9258 |
+ clutres // 2 |
| 9259 |
) |
| 9260 |
] |
| 9261 |
logfile.write(f"Input black L*a*b*: {iLabbp}\n") |
| 9262 |
logfile.write(f"Input white L*a*b*: {iLabwp}\n") |
| 9263 |
|
| 9264 |
if not use_cam_clipping: |
| 9265 |
odata = odata1 |
| 9266 |
elif pcs == "l": |
| 9267 |
odata = odata2 |
| 9268 |
else: |
| 9269 |
# Linearly interpolate the crossover to CAM Jab clipping region |
| 9270 |
cam_diag = False |
| 9271 |
odata = [] |
| 9272 |
j, k = 0, 0 |
| 9273 |
r = float(threshold - threshold2) |
| 9274 |
for a in range(clutres): |
| 9275 |
for b in range(clutres): |
| 9276 |
for c in range(clutres): |
| 9277 |
if a <= threshold and b <= threshold and c <= threshold: |
| 9278 |
v = odata1[j] |
| 9279 |
j += 1 |
| 9280 |
if a > threshold2 or b > threshold2 or c > threshold2: |
| 9281 |
d = max(a, b, c) |
| 9282 |
if cam_diag: |
| 9283 |
v = [100.0, 100.0, 0.0] |
| 9284 |
v2 = [0.0, 100.0, 100.0] |
| 9285 |
else: |
| 9286 |
v2 = odata2[k] |
| 9287 |
k += 1 |
| 9288 |
for i, _ in enumerate(v): |
| 9289 |
v[i] *= (threshold - d) / r |
| 9290 |
v2[i] *= 1 - (threshold - d) / r |
| 9291 |
v[i] += v2[i] |
| 9292 |
else: |
| 9293 |
v = [100.0, 0.0, 100.0] if cam_diag else odata2[k] |
| 9294 |
k += 1 |
| 9295 |
odata.append(v) |
| 9296 |
numrows = len(odata) |
| 9297 |
if numrows != clutres**3: |
| 9298 |
raise ValueError( |
| 9299 |
f"Number of cLUT entries ({numrows}) exceeds cLUT res " |
| 9300 |
f"maximum ({clutres}^3 = {clutres**3})" |
| 9301 |
) |
| 9302 |
if logfile and (pcs == "x" or clutres // 2 != clutres / 2.0): |
| 9303 |
if pcs == "x": |
| 9304 |
oRGBbp = odata[0] |
| 9305 |
oRGBwp = odata[-1] |
| 9306 |
else: |
| 9307 |
oRGBbp = odata[clutres * (clutres // 2) + clutres // 2] |
| 9308 |
oRGBwp = odata[ |
| 9309 |
( |
| 9310 |
clutres**2 * (clutres - 1) |
| 9311 |
+ clutres * (clutres // 2) |
| 9312 |
+ clutres // 2 |
| 9313 |
) |
| 9314 |
] |
| 9315 |
logfile.write( |
| 9316 |
"Output black RGB: {:.4f} {:.4f} {:.4f}\n".format(*oRGBbp) |
| 9317 |
) |
| 9318 |
logfile.write( |
| 9319 |
"Output white RGB: {:.4f} {:.4f} {:.4f}\n".format(*oRGBwp) |
| 9320 |
) |
| 9321 |
odata = [[n / 100.0 for n in v] for v in odata] |
| 9322 |
|
| 9323 |
# Fill cCLUT |
| 9324 |
itable.clut = [] |
| 9325 |
if logfile: |
| 9326 |
logfile.write("Filling cLUT...\n") |
| 9327 |
if not do_lookup: |
| 9328 |
# Linearly scale RGB |
| 9329 |
for R in range(clutres): |
| 9330 |
if self.thread_abort: |
| 9331 |
raise Info(lang.getstr("aborted")) |
| 9332 |
for G in range(clutres): |
| 9333 |
itable.clut.append([]) |
| 9334 |
for B in range(clutres): |
| 9335 |
itable.clut[-1].append([v * step * 65535 for v in (R, G, B)]) |
| 9336 |
if logfile: |
| 9337 |
logfile.write(f"\r{(R * G * B) / ((clutres - 1.0) ** 3):0.0%}") |
| 9338 |
else: |
| 9339 |
for i, RGB in enumerate(odata): |
| 9340 |
if i % clutres == 0: |
| 9341 |
if self.thread_abort: |
| 9342 |
raise Info(lang.getstr("aborted")) |
| 9343 |
itable.clut.append([]) |
| 9344 |
if logfile: |
| 9345 |
logfile.write(f"\r{i / (numrows - 1.0):0.0%}") |
| 9346 |
# Set RGB black and white explicitly |
| 9347 |
if pcs == "x": |
| 9348 |
if i == 0: |
| 9349 |
RGB = 0, 0, 0 |
| 9350 |
elif i == numrows - 1.0: |
| 9351 |
RGB = 1, 1, 1 |
| 9352 |
elif clutres // 2 != clutres / 2.0: |
| 9353 |
# For CIELab cLUT, white- and black point will only |
| 9354 |
# fall on a cLUT point if uneven cLUT res |
| 9355 |
if i == clutres * (clutres // 2) + clutres // 2: |
| 9356 |
# if raw_input("{:d} {!r}".format(i, RGB)): |
| 9357 |
RGB = 0, 0, 0 |
| 9358 |
elif i == ( |
| 9359 |
clutres**2 * (clutres - 1) |
| 9360 |
+ clutres * (clutres // 2) |
| 9361 |
+ clutres // 2 |
| 9362 |
): |
| 9363 |
# if raw_input("{:d} {!r}".format(i, RGB)): |
| 9364 |
RGB = 1, 1, 1 |
| 9365 |
itable.clut[-1].append([v * 65535 for v in RGB]) |
| 9366 |
if logfile: |
| 9367 |
logfile.write("\n") |
| 9368 |
|
| 9369 |
if getcfg("profile.b2a.hires.diagpng") and filename: |
| 9370 |
# Generate diagnostic images |
| 9371 |
fname, ext = os.path.splitext(filename) |
| 9372 |
for suffix, table in [ |
| 9373 |
("pre", profile.tags.get(f"B2A{tableno}")), |
| 9374 |
("post", itable), |
| 9375 |
]: |
| 9376 |
if table: |
| 9377 |
table.clut_writepng(f"{fname}.B2A{tableno:d}.{suffix}.CLUT.png") |
| 9378 |
|
| 9379 |
# Update profile |
| 9380 |
profile.tags[f"B2A{tableno:d}"] = itable |
| 9381 |
|
| 9382 |
if method == 2: |
| 9383 |
if logfile: |
| 9384 |
logfile.write("Generating output curves...\n") |
| 9385 |
# Output curve maps <clutres> RGB to <numentries> RGB |
| 9386 |
# Lookup neutral (except near black) XYZ -> RGB |
| 9387 |
oRGB = self.xicclu( |
| 9388 |
profile, |
| 9389 |
oXYZ, |
| 9390 |
intent, |
| 9391 |
{"A2B": "if", "B2A": "b"}[source], |
| 9392 |
pcs="x", |
| 9393 |
get_clip=True, |
| 9394 |
) |
| 9395 |
|
| 9396 |
# Deal with values that got clipped (below black as well as white) |
| 9397 |
do_low_clip = True |
| 9398 |
for i, values in enumerate(oRGB): |
| 9399 |
if values[3] is True or i == 0: |
| 9400 |
if do_low_clip: |
| 9401 |
# Set to black |
| 9402 |
self.log( |
| 9403 |
"Setting curve entry #{:d} ({:.6f} {:.6f} {:.6f}) to " |
| 9404 |
"black because it got clipped".format(*(i, *values[:3])) |
| 9405 |
) |
| 9406 |
values[:] = [0.0, 0.0, 0.0] |
| 9407 |
elif i == maxval and [round(v, 4) for v in values[:3]] == [1, 1, 1]: |
| 9408 |
# Set to white |
| 9409 |
self.log( |
| 9410 |
"Setting curve entry #{:d} ({:.6f} {:.6f} {:.6f}) to " |
| 9411 |
"white because it got clipped".format(*(i, *values[:3])) |
| 9412 |
) |
| 9413 |
values[:] = [1.0, 1.0, 1.0] |
| 9414 |
else: |
| 9415 |
# First non-clipping value disables low clipping |
| 9416 |
do_low_clip = False |
| 9417 |
if len(values) > 3: |
| 9418 |
values.pop() |
| 9419 |
|
| 9420 |
ocurves = [[], [], []] |
| 9421 |
for RGB in oRGB: |
| 9422 |
for j, v in enumerate(RGB): |
| 9423 |
ocurves[j].append(v) |
| 9424 |
ointerp = [] |
| 9425 |
for ocurve in ocurves: |
| 9426 |
olen = len(ocurve) |
| 9427 |
ointerp_i = colormath.Interp( |
| 9428 |
[j / (olen - 1.0) for j in range(olen)], ocurve, use_numpy=True |
| 9429 |
) |
| 9430 |
ocurve_i = [ointerp_i(j / (clutres - 1.0)) for j in range(clutres)] |
| 9431 |
ocurve_i = colormath.interp_resize( |
| 9432 |
ocurve_i, len(ocurve), use_numpy=True |
| 9433 |
) |
| 9434 |
ointerp_o = colormath.Interp(ocurve_i, ocurve, use_numpy=True) |
| 9435 |
ointerp.append(ointerp_o) |
| 9436 |
|
| 9437 |
# Set output curves |
| 9438 |
itable.output = [[], [], []] |
| 9439 |
numentries = 256 |
| 9440 |
maxval = numentries - 1.0 |
| 9441 |
for i in range(len(itable.output)): |
| 9442 |
for j in range(numentries): |
| 9443 |
v = j / maxval |
| 9444 |
if method == 2: |
| 9445 |
v = ointerp[i](v) |
| 9446 |
itable.output[i].append(v * 65535) |
| 9447 |
|
| 9448 |
if smooth: |
| 9449 |
self.smooth_B2A( |
| 9450 |
profile, tableno, getcfg("profile.b2a.hires.diagpng"), filename, logfile |
| 9451 |
) |
| 9452 |
|
| 9453 |
return True |
| 9454 |
|
| 9455 |
def smooth_B2A(self, profile, tableno, diagpng=2, filename=None, logfile=None): |
| 9456 |
"""Apply extra smoothing to the cLUT. |
| 9457 |
|
| 9458 |
Args: |
| 9459 |
profile (ICCProfile): The ICC profile to smooth. |
| 9460 |
tableno (int): The table number to smooth. |
| 9461 |
diagpng (int): If 1, generate diagnostic PNGs. |
| 9462 |
filename (str): The filename to use for diagnostic PNGs. |
| 9463 |
logfile (TextIO): The logfile to write to. |
| 9464 |
|
| 9465 |
Returns: |
| 9466 |
bool: True if smoothing was successful, False otherwise. |
| 9467 |
""" |
| 9468 |
itable = profile.tags.get(f"B2A{tableno:d}") |
| 9469 |
if not itable: |
| 9470 |
return False |
| 9471 |
itable.smooth2(diagpng, profile.connectionColorSpace, filename, logfile) |
| 9472 |
return True |
| 9473 |
|
| 9474 |
def get_device_id( |
| 9475 |
self, |
| 9476 |
quirk=False, |
| 9477 |
use_serial_32=True, |
| 9478 |
truncate_edid_strings=False, |
| 9479 |
omit_manufacturer=False, |
| 9480 |
query=False, |
| 9481 |
): |
| 9482 |
"""Get org.freedesktop.ColorManager device key. |
| 9483 |
|
| 9484 |
Args: |
| 9485 |
quirk (bool): If True, use quirked EDID. |
| 9486 |
use_serial_32 (bool): If True, use 32-bit serial number. |
| 9487 |
truncate_edid_strings (bool): If True, truncate EDID strings. |
| 9488 |
omit_manufacturer (bool): If True, omit manufacturer from EDID. |
| 9489 |
query (bool): If True, query the device ID instead of returning |
| 9490 |
the EDID. |
| 9491 |
|
| 9492 |
Returns: |
| 9493 |
str or None: The device ID for the display, or None if no |
| 9494 |
display is configured or the EDID is not available. |
| 9495 |
""" |
| 9496 |
if not self.display_edid or config.is_virtual_display(): |
| 9497 |
return None |
| 9498 |
display_no = max(0, min(len(self.displays) - 1, getcfg("display.number") - 1)) |
| 9499 |
edid = self.display_edid[display_no] |
| 9500 |
if not edid: |
| 9501 |
# Fall back to XrandR name |
| 9502 |
if not ( |
| 9503 |
not quirk |
| 9504 |
and use_serial_32 |
| 9505 |
and not truncate_edid_strings |
| 9506 |
and not omit_manufacturer |
| 9507 |
): |
| 9508 |
return None |
| 9509 |
if real_display_size_mm: |
| 9510 |
display = real_display_size_mm.get_display(display_no) |
| 9511 |
if display: |
| 9512 |
xrandr_name = display.get("xrandr_name") |
| 9513 |
if xrandr_name: |
| 9514 |
edid = {"monitor_name": xrandr_name} |
| 9515 |
elif os.getenv("XDG_SESSION_TYPE") == "wayland": |
| 9516 |
# Preliminary Wayland support under non-GNOME desktops. |
| 9517 |
# This still needs a lot of work. |
| 9518 |
device_ids = colord.get_display_device_ids() |
| 9519 |
if device_ids and display_no < len(device_ids): |
| 9520 |
return device_ids[display_no] |
| 9521 |
return colord.device_id_from_edid( |
| 9522 |
edid, |
| 9523 |
quirk=quirk, |
| 9524 |
use_serial_32=use_serial_32, |
| 9525 |
truncate_edid_strings=truncate_edid_strings, |
| 9526 |
omit_manufacturer=omit_manufacturer, |
| 9527 |
query=query, |
| 9528 |
) |
| 9529 |
|
| 9530 |
def get_display(self): |
| 9531 |
"""Get the currently configured display. |
| 9532 |
|
| 9533 |
Returned is the Argyll CMS dispcal/dispread -d argument. |
| 9534 |
|
| 9535 |
Returns: |
| 9536 |
str: The display identifier for Argyll CMS. |
| 9537 |
""" |
| 9538 |
display_name = config.get_display_name(None, True) |
| 9539 |
if display_name == "Web @ localhost": |
| 9540 |
return "web:{:d}".format(getcfg("webserver.portnumber")) |
| 9541 |
if display_name == "madVR": |
| 9542 |
return "madvr" |
| 9543 |
if display_name == "Untethered": |
| 9544 |
return "0" |
| 9545 |
if display_name == "Resolve": |
| 9546 |
if ( |
| 9547 |
self.argyll_virtual_display |
| 9548 |
# and os.getenv("XDG_SESSION_TYPE") == "wayland" |
| 9549 |
): |
| 9550 |
return self.argyll_virtual_display |
| 9551 |
return "1" |
| 9552 |
if display_name == "Prisma" and not DEFAULTS["patterngenerator.prisma.argyll"]: |
| 9553 |
if self.argyll_virtual_display: |
| 9554 |
return self.argyll_virtual_display |
| 9555 |
return "1" |
| 9556 |
if display_name == "Prisma": |
| 9557 |
host = getcfg("patterngenerator.prisma.host") |
| 9558 |
with contextlib.suppress(OSError): |
| 9559 |
host = socket.gethostbyname(host) |
| 9560 |
return f"prisma:{host}" |
| 9561 |
if display_name.startswith("Chromecast "): |
| 9562 |
return "cc:{}".format(display_name.split(":")[0].split(None, 1)[1].strip()) |
| 9563 |
if display_name.startswith("Prisma "): |
| 9564 |
return "prisma:{}".format(display_name.split("@")[-1].strip()) |
| 9565 |
if self._use_patternwindow: |
| 9566 |
# Preliminary Wayland support. This still needs a lot |
| 9567 |
# of work as Argyll doesn't support Wayland natively, |
| 9568 |
# so we use virtual display to drive our own patch window. |
| 9569 |
return self.argyll_virtual_display |
| 9570 |
display_no = min(len(self.displays), getcfg("display.number")) - 1 |
| 9571 |
display = str(display_no + 1) |
| 9572 |
if ( |
| 9573 |
(sys.platform not in ("darwin", "win32") or TEST) |
| 9574 |
and (self.has_separate_lut_access() or getcfg("use_separate_lut_access")) |
| 9575 |
and ( |
| 9576 |
not getcfg("display_lut.link") |
| 9577 |
or (display_no > -1 and not self.lut_access[display_no]) |
| 9578 |
) |
| 9579 |
): |
| 9580 |
display_lut_no = min(len(self.displays), getcfg("display_lut.number")) - 1 |
| 9581 |
if display_lut_no > -1 and not self.lut_access[display_lut_no]: |
| 9582 |
for i, disp in enumerate(self.lut_access): |
| 9583 |
if disp: |
| 9584 |
display_lut_no = i |
| 9585 |
break |
| 9586 |
display = f"{display},{display_lut_no + 1}" |
| 9587 |
return display |
| 9588 |
|
| 9589 |
def get_display_edid(self): |
| 9590 |
"""Return EDID of currently configured display. |
| 9591 |
|
| 9592 |
Returns: |
| 9593 |
dict: The EDID of the display, or an empty dict if no EDID is |
| 9594 |
available. |
| 9595 |
""" |
| 9596 |
n = getcfg("display.number") - 1 |
| 9597 |
if 0 <= n < len(self.display_edid): |
| 9598 |
return self.display_edid[n] |
| 9599 |
return {} |
| 9600 |
|
| 9601 |
def get_display_name( |
| 9602 |
self, prepend_manufacturer=False, prefer_edid=False, remove_manufacturer=True |
| 9603 |
): |
| 9604 |
"""Return name of currently configured display. |
| 9605 |
|
| 9606 |
Args: |
| 9607 |
prepend_manufacturer (bool): If True, prepend the manufacturer |
| 9608 |
to the display name. |
| 9609 |
prefer_edid (bool): If True, prefer the EDID name over the |
| 9610 |
configured display name. |
| 9611 |
remove_manufacturer (bool): If True, remove the manufacturer |
| 9612 |
from the display name if it is already present. |
| 9613 |
|
| 9614 |
Returns: |
| 9615 |
str: The display name. |
| 9616 |
""" |
| 9617 |
n = getcfg("display.number") - 1 |
| 9618 |
if 0 <= n < len(self.display_names): |
| 9619 |
display = [] |
| 9620 |
manufacturer = None |
| 9621 |
display_name = None |
| 9622 |
if prefer_edid: |
| 9623 |
edid = self.get_display_edid() |
| 9624 |
manufacturer = edid.get("manufacturer") |
| 9625 |
display_name = edid.get( |
| 9626 |
"monitor_name", edid.get("ascii", str(edid.get("product_id") or "")) |
| 9627 |
) |
| 9628 |
if not manufacturer: |
| 9629 |
manufacturer = self.display_manufacturers[n] |
| 9630 |
if not display_name: |
| 9631 |
display_name = self.display_names[n] |
| 9632 |
if manufacturer: |
| 9633 |
manufacturer = colord.quirk_manufacturer(manufacturer) |
| 9634 |
if prepend_manufacturer: |
| 9635 |
if manufacturer.lower() not in display_name.lower(): |
| 9636 |
display.append(manufacturer) |
| 9637 |
elif remove_manufacturer: |
| 9638 |
start = display_name.lower().find(manufacturer.lower()) |
| 9639 |
if start > -1: |
| 9640 |
display_name = ( |
| 9641 |
display_name[:start] |
| 9642 |
+ display_name[start + len(manufacturer) :] |
| 9643 |
).lstrip() |
| 9644 |
display_name = re.sub(r"^[^([{\w]+", "", display_name) |
| 9645 |
display.append(display_name) |
| 9646 |
return " ".join(display) |
| 9647 |
return "" |
| 9648 |
|
| 9649 |
def get_display_name_short(self, prepend_manufacturer=False, prefer_edid=False): |
| 9650 |
"""Return shortened name of configured display (if possible). |
| 9651 |
|
| 9652 |
If name can't be shortened (e.g. because it's already 10 characters |
| 9653 |
or less), return full string. |
| 9654 |
|
| 9655 |
Args: |
| 9656 |
prepend_manufacturer (bool): If True, prepend the manufacturer |
| 9657 |
to the display name. |
| 9658 |
prefer_edid (bool): If True, prefer the EDID name over the |
| 9659 |
configured display name. |
| 9660 |
|
| 9661 |
Returns: |
| 9662 |
str: The shortened display name. |
| 9663 |
""" |
| 9664 |
display_name = self.get_display_name(prepend_manufacturer, prefer_edid) |
| 9665 |
if len(display_name) > 10: |
| 9666 |
maxweight = 0 |
| 9667 |
for part in re.findall( |
| 9668 |
r"[^\s_]+(?:\s*\d+)?", re.sub(r"\([^)]+\)", "", display_name) |
| 9669 |
): |
| 9670 |
digits = re.search(r"\d+", part) |
| 9671 |
if digits: |
| 9672 |
# Weigh parts with digits higher than those without |
| 9673 |
chars = re.sub(r"\d+", "", part) |
| 9674 |
weight = len(chars) + len(digits.group()) * 5 |
| 9675 |
else: |
| 9676 |
# Weigh parts with uppercase letters higher than those without |
| 9677 |
chars = "" |
| 9678 |
for char in part: |
| 9679 |
if char.lower() != char: |
| 9680 |
chars += char |
| 9681 |
weight = len(chars) |
| 9682 |
if chars and weight >= maxweight: |
| 9683 |
# Weigh parts further to the right higher |
| 9684 |
display_name = re.sub(r"^[^([{\w]+", "", part) |
| 9685 |
maxweight = weight |
| 9686 |
|
| 9687 |
# Shortname should not contain any spaces. |
| 9688 |
return re.sub(r"[\s]+", "_", display_name) |
| 9689 |
|
| 9690 |
def get_dispwin_display_profile_argument(self, display_no=0): |
| 9691 |
"""Return argument corresponding to the display profile for use with dispwin. |
| 9692 |
|
| 9693 |
Will either return '-L' (use current profile) or a filename. |
| 9694 |
|
| 9695 |
Args: |
| 9696 |
display_no (int): The display number to get the profile for. |
| 9697 |
|
| 9698 |
Returns: |
| 9699 |
str: The argument for dispwin, either '-L' or a profile filename. |
| 9700 |
""" |
| 9701 |
arg = "-L" |
| 9702 |
try: |
| 9703 |
profile = get_display_profile(display_no) |
| 9704 |
except Exception as exception: |
| 9705 |
print(exception) |
| 9706 |
return arg |
| 9707 |
else: |
| 9708 |
if not profile: |
| 9709 |
return arg |
| 9710 |
if profile.filename: |
| 9711 |
prefix = os.path.basename(profile.filename) |
| 9712 |
else: |
| 9713 |
prefix = ( |
| 9714 |
make_filename_safe(profile.getDescription(), concat=False) |
| 9715 |
+ PROFILE_EXT |
| 9716 |
) |
| 9717 |
prefix += "-" |
| 9718 |
if profile.version >= 4 and not profile.convert_iccv4_tags_to_iccv2(): |
| 9719 |
print( |
| 9720 |
"\n".join( |
| 9721 |
[lang.getstr("profile.iccv4.unsupported"), profile.getDescription()] |
| 9722 |
) |
| 9723 |
) |
| 9724 |
elif not profile.filename: |
| 9725 |
fd, profile.filename = tempfile.mkstemp("", prefix) |
| 9726 |
stream = os.fdopen(fd, "wb") |
| 9727 |
profile.write(stream) |
| 9728 |
stream.close() |
| 9729 |
atexit.register(os.remove, profile.filename) |
| 9730 |
return profile.filename or arg |
| 9731 |
|
| 9732 |
def get_calibration_load_discrepancy(self, dispwin, display_no, profile_arg): |
| 9733 |
"""Return how much a display's loaded calibration differs from a profile. |
| 9734 |
|
| 9735 |
Runs ``dispwin -d{N} -V <profile>`` which compares the VideoLUT contents |
| 9736 |
currently loaded in the hardware against the given profile's calibration |
| 9737 |
and reports the discrepancy as a percentage. A verify-only run does not |
| 9738 |
open a window nor alter the VideoLUT, so this is safe to call freely. |
| 9739 |
Used to detect the macOS "black screen" condition where the OS clobbers |
| 9740 |
the VideoLUT after it was loaded (issue #694): a clobbered/black VideoLUT |
| 9741 |
yields a very large discrepancy (close to 100%), whereas a correctly |
| 9742 |
loaded calibration is at most a few percent off due to quantization. |
| 9743 |
|
| 9744 |
Args: |
| 9745 |
dispwin (str): Path to the dispwin executable. |
| 9746 |
display_no (int): Zero-based display index. |
| 9747 |
profile_arg (str): Profile path to verify against. ``-L`` is not a |
| 9748 |
valid argument here (pass a real profile path). |
| 9749 |
|
| 9750 |
Returns: |
| 9751 |
None | float: The discrepancy in percent (0.0 - 100.0), or None if |
| 9752 |
it could not be determined (e.g. no VideoLUT access). |
| 9753 |
""" |
| 9754 |
self.exec_cmd( |
| 9755 |
dispwin, |
| 9756 |
["-v", f"-d{display_no + 1:d}", "-V", profile_arg], |
| 9757 |
capture_output=True, |
| 9758 |
skip_scripts=True, |
| 9759 |
silent=True, |
| 9760 |
) |
| 9761 |
# The 'Verify: ... (discrepancy X%)' message goes to stdout, |
| 9762 |
# other errors go to stderr. |
| 9763 |
output = "\n".join(self.errors + self.output) |
| 9764 |
if "We don't have access to the VideoLUT" in output: |
| 9765 |
return None |
| 9766 |
match = re.search(r"discrepancy\s+([0-9]+(?:\.[0-9]+)?)%", output) |
| 9767 |
if match: |
| 9768 |
return float(match.group(1)) |
| 9769 |
return None |
| 9770 |
|
| 9771 |
def calibration_is_clobbered(self, dispwin, display_no, profile_arg): |
| 9772 |
"""Return True if a display's loaded calibration looks clobbered/black. |
| 9773 |
|
| 9774 |
See :meth:`get_calibration_load_discrepancy`. Only a discrepancy above |
| 9775 |
``profile_loader.clobbered_discrepancy_threshold`` is treated as |
| 9776 |
clobbered, so benign quantization differences don't trigger needless |
| 9777 |
re-loads (which could themselves re-trigger the macOS bug). |
| 9778 |
|
| 9779 |
Args: |
| 9780 |
dispwin (str): Path to the dispwin executable. |
| 9781 |
display_no (int): Zero-based display index. |
| 9782 |
profile_arg (str): Profile path to verify against. |
| 9783 |
|
| 9784 |
Returns: |
| 9785 |
bool: True if the loaded calibration is considered clobbered. |
| 9786 |
""" |
| 9787 |
discrepancy = self.get_calibration_load_discrepancy( |
| 9788 |
dispwin, display_no, profile_arg |
| 9789 |
) |
| 9790 |
if discrepancy is None: |
| 9791 |
return False |
| 9792 |
threshold = float(getcfg("profile_loader.clobbered_discrepancy_threshold")) |
| 9793 |
return discrepancy > threshold |
| 9794 |
|
| 9795 |
def update_display_name_manufacturer( |
| 9796 |
self, ti3, display_name=None, display_manufacturer=None, write=True |
| 9797 |
): |
| 9798 |
"""Update display name and manufacturer in 'ARGYLL_COLPROF_ARGS' section of a TI3 file. |
| 9799 |
|
| 9800 |
Args: |
| 9801 |
ti3 (CGATS): The CGATS object representing the TI3 file. |
| 9802 |
display_name (str): The display name to set. |
| 9803 |
display_manufacturer (str): The display manufacturer to set. |
| 9804 |
write (bool): If True, write the updated TI3 file back to disk. |
| 9805 |
|
| 9806 |
Returns: |
| 9807 |
list: List of options for colprof command. |
| 9808 |
""" # noqa: E501 |
| 9809 |
options_colprof = [] |
| 9810 |
if not display_name and not display_manufacturer: |
| 9811 |
# Note: Do not mix'n'match display name and manufacturer from |
| 9812 |
# different sources |
| 9813 |
try: |
| 9814 |
ti3_options_colprof = get_options_from_ti3(ti3)[1] |
| 9815 |
except ( |
| 9816 |
OSError, |
| 9817 |
CGATSInvalidError, |
| 9818 |
CGATSInvalidOperationError, |
| 9819 |
CGATSKeyError, |
| 9820 |
CGATSTypeError, |
| 9821 |
CGATSValueError, |
| 9822 |
) as exception: |
| 9823 |
print(exception) |
| 9824 |
ti3_options_colprof = [] |
| 9825 |
for option in ti3_options_colprof: |
| 9826 |
if option[0] == "M": |
| 9827 |
display_name = option.split(None, 1)[-1][1:-1] |
| 9828 |
elif option[0] == "A": |
| 9829 |
display_manufacturer = option.split(None, 1)[-1][1:-1] |
| 9830 |
if not display_name and not display_manufacturer: |
| 9831 |
# Note: Do not mix'n'match display name and manufacturer from |
| 9832 |
# different sources |
| 9833 |
edid = self.display_edid[ |
| 9834 |
max(0, min(len(self.displays), getcfg("display.number")) - 1) |
| 9835 |
] |
| 9836 |
display_name = edid.get( |
| 9837 |
"monitor_name", edid.get("ascii", str(edid.get("product_id") or "")) |
| 9838 |
) |
| 9839 |
display_manufacturer = edid.get("manufacturer") |
| 9840 |
if not display_name and not display_manufacturer: |
| 9841 |
# Note: Do not mix'n'match display name and manufacturer from |
| 9842 |
# different sources |
| 9843 |
display_name = self.get_display_name() |
| 9844 |
if display_name: |
| 9845 |
options_colprof.append("-M") |
| 9846 |
options_colprof.append(display_name) |
| 9847 |
if display_manufacturer: |
| 9848 |
options_colprof.append("-A") |
| 9849 |
options_colprof.append(display_manufacturer) |
| 9850 |
if write: |
| 9851 |
# Add dispcal and colprof arguments to ti3 |
| 9852 |
options_dispcal = [] if is_ccxx_testchart() else self.options_dispcal |
| 9853 |
ti3 = add_options_to_ti3(ti3, options_dispcal, options_colprof) |
| 9854 |
if ti3: |
| 9855 |
ti3.write() |
| 9856 |
return options_colprof |
| 9857 |
|
| 9858 |
def get_instrument_features(self, instrument_name=None): |
| 9859 |
"""Return features of currently configured instrument. |
| 9860 |
|
| 9861 |
Args: |
| 9862 |
instrument_name (str): Name of the instrument to get features for. |
| 9863 |
|
| 9864 |
Returns: |
| 9865 |
dict: Mapping of feature names to their values. |
| 9866 |
""" |
| 9867 |
features = all_instruments.get( |
| 9868 |
instrument_name or self.get_instrument_name(), {} |
| 9869 |
) |
| 9870 |
if TEST_REQUIRE_SENSOR_CAL: |
| 9871 |
features["sensor_cal"] = True |
| 9872 |
features["skip_sensor_cal"] = False |
| 9873 |
return features |
| 9874 |
|
| 9875 |
def get_instrument_measurement_modes( |
| 9876 |
self, instrument_id=None, skip_ccxx_modes=True |
| 9877 |
): |
| 9878 |
"""Enumerate measurement modes supported by the instrument. |
| 9879 |
|
| 9880 |
Args: |
| 9881 |
instrument_id (str): ID of the instrument to get measurement modes |
| 9882 |
for. |
| 9883 |
skip_ccxx_modes (bool): If True, skip modes supplied via CCMX/CCSS. |
| 9884 |
|
| 9885 |
Returns: |
| 9886 |
dict: Mapping of measurement mode selectors to their descriptions. |
| 9887 |
""" |
| 9888 |
if not instrument_id: |
| 9889 |
features = self.get_instrument_features() |
| 9890 |
instrument_id = features.get("id", self.get_instrument_name()) |
| 9891 |
if not instrument_id: |
| 9892 |
return {} |
| 9893 |
measurement_modes = self.measurement_modes.get(instrument_id, {}) |
| 9894 |
if measurement_modes: |
| 9895 |
return measurement_modes |
| 9896 |
result = self.exec_cmd( |
| 9897 |
get_argyll_util("spotread"), |
| 9898 |
["-?"], |
| 9899 |
capture_output=True, |
| 9900 |
skip_scripts=True, |
| 9901 |
silent=True, |
| 9902 |
log_output=False, |
| 9903 |
) |
| 9904 |
if isinstance(result, Exception): |
| 9905 |
print(result) |
| 9906 |
# Need to get and remember output of spotread because calling |
| 9907 |
# self.get_technology_strings() will overwrite self.output |
| 9908 |
output = self.output |
| 9909 |
if TEST: |
| 9910 |
output.extend(INSTRUMENT_MEASUREMENT_MODES_TEST_OUTPUT.splitlines()) |
| 9911 |
measurement_modes_follow = False |
| 9912 |
technology_strings = self.get_technology_strings() |
| 9913 |
for line in output: |
| 9914 |
line = line.strip() |
| 9915 |
if line.startswith("-y "): |
| 9916 |
line = line.lstrip("-y ") |
| 9917 |
measurement_modes_follow = True |
| 9918 |
elif line.startswith("-"): |
| 9919 |
measurement_modes_follow = False |
| 9920 |
parts = [v.strip() for v in line.split(None, 1)] |
| 9921 |
if not measurement_modes_follow or len(parts) != 2: |
| 9922 |
continue |
| 9923 |
measurement_mode, desc = parts |
| 9924 |
if measurement_mode not in (string.digits[1:] + string.ascii_letters): |
| 9925 |
# Ran out of selectors |
| 9926 |
continue |
| 9927 |
measurement_mode_instrument_id, desc = desc.split(":", 1) |
| 9928 |
desc = desc.strip() |
| 9929 |
if measurement_mode_instrument_id != instrument_id: |
| 9930 |
continue |
| 9931 |
# Found a mode for our instrument |
| 9932 |
if ( |
| 9933 |
re.sub(r"\s*\(.*?\)?$", "", desc) in [*technology_strings.values(), ""] |
| 9934 |
and skip_ccxx_modes |
| 9935 |
): |
| 9936 |
# This mode is supplied via CCMX/CCSS, skip |
| 9937 |
continue |
| 9938 |
desc = re.sub(r"\s*(?:File|\[[^\]]*\])", "", desc) |
| 9939 |
measurement_modes[measurement_mode] = desc |
| 9940 |
self.measurement_modes[instrument_id] = measurement_modes |
| 9941 |
return measurement_modes |
| 9942 |
|
| 9943 |
def get_instrument_name(self): |
| 9944 |
"""Return name of currently configured instrument. |
| 9945 |
|
| 9946 |
Returns: |
| 9947 |
str: Name of the instrument, or an empty string if not found. |
| 9948 |
""" |
| 9949 |
try: |
| 9950 |
return self.instruments[getcfg("comport.number") - 1] |
| 9951 |
except IndexError: |
| 9952 |
return "" |
| 9953 |
|
| 9954 |
def get_real_displays(self) -> list[int]: |
| 9955 |
"""Return real (nonvirtual) displays. |
| 9956 |
|
| 9957 |
Return: |
| 9958 |
list[int]: List of display numbers (0-indexed) of real displays. |
| 9959 |
""" |
| 9960 |
return [ |
| 9961 |
display_no |
| 9962 |
for display_no in range(len(self.displays)) |
| 9963 |
if not config.is_virtual_display(display_no) |
| 9964 |
] |
| 9965 |
|
| 9966 |
def get_technology_strings(self): |
| 9967 |
"""Return technology strings mapping (from ccxxmake -??). |
| 9968 |
|
| 9969 |
Returns: |
| 9970 |
dict: Mapping of technology strings to their descriptions. |
| 9971 |
""" |
| 9972 |
if self.argyll_version < [1, 7]: |
| 9973 |
# Argyll ccxxmake before V1.7 didn't have the ability to list |
| 9974 |
# dtechs with -?? |
| 9975 |
# Argyll V1.7 had different keys (we still want to use those for |
| 9976 |
# V1.7) with some duplicates |
| 9977 |
# Use Argyll V1.7.1 mapping (which has no duplicate keys) for |
| 9978 |
# Argyll before V1.7 |
| 9979 |
return { |
| 9980 |
"c": "CRT", |
| 9981 |
"m": "Plasma", |
| 9982 |
"l": "LCD", |
| 9983 |
"1": "LCD CCFL", |
| 9984 |
"2": "LCD CCFL IPS", |
| 9985 |
"3": "LCD CCFL VPA", |
| 9986 |
"4": "LCD CCFL TFT", |
| 9987 |
"L": "LCD CCFL Wide Gamut", |
| 9988 |
"5": "LCD CCFL Wide Gamut IPS", |
| 9989 |
"6": "LCD CCFL Wide Gamut VPA", |
| 9990 |
"7": "LCD CCFL Wide Gamut TFT", |
| 9991 |
"e": "LCD White LED", |
| 9992 |
"8": "LCD White LED IPS", |
| 9993 |
"9": "LCD White LED VPA", |
| 9994 |
"d": "LCD White LED TFT", |
| 9995 |
"b": "LCD RGB LED", |
| 9996 |
"f": "LCD RGB LED IPS", |
| 9997 |
"g": "LCD RGB LED VPA", |
| 9998 |
"i": "LCD RGB LED TFT", |
| 9999 |
"h": "LCD RG Phosphor", |
| 10000 |
"j": "LCD RG Phosphor IPS", |
| 10001 |
"k": "LCD RG Phosphor VPA", |
| 10002 |
"n": "LCD RG Phosphor TFT", |
| 10003 |
"o": "LED OLED", |
| 10004 |
"a": "LED AMOLED", |
| 10005 |
"p": "DLP Projector", |
| 10006 |
"q": "DLP Projector RGB Filter Wheel", |
| 10007 |
"r": "DPL Projector RGBW Filter Wheel", |
| 10008 |
"s": "DLP Projector RGBCMY Filter Wheel", |
| 10009 |
"u": "Unknown", |
| 10010 |
} |
| 10011 |
result = self.exec_cmd( |
| 10012 |
get_argyll_util("ccxxmake"), |
| 10013 |
["-??"], |
| 10014 |
capture_output=True, |
| 10015 |
skip_scripts=True, |
| 10016 |
silent=True, |
| 10017 |
log_output=False, |
| 10018 |
) |
| 10019 |
if isinstance(result, Exception): |
| 10020 |
traceback.print_exc() |
| 10021 |
print(result) |
| 10022 |
return {} |
| 10023 |
technology_strings = {} |
| 10024 |
in_tech = False |
| 10025 |
for line in self.output: |
| 10026 |
if not (parts := line.strip().split(None, 1)): |
| 10027 |
continue |
| 10028 |
if (arg := parts.pop(0)) == "-t": |
| 10029 |
parts = parts[0].split(None, 1) |
| 10030 |
if len(parts) == 2: |
| 10031 |
arg = parts.pop(0) |
| 10032 |
in_tech = True |
| 10033 |
elif arg.startswith("-"): |
| 10034 |
in_tech = False |
| 10035 |
if in_tech and parts: |
| 10036 |
technology_strings[arg] = parts[0] |
| 10037 |
return technology_strings |
| 10038 |
|
| 10039 |
def has_lut_access(self): |
| 10040 |
"""Return True if the current display has LUT access. |
| 10041 |
|
| 10042 |
Returns: |
| 10043 |
bool: True if the current display has LUT access, False otherwise. |
| 10044 |
""" |
| 10045 |
display_no = min(len(self.lut_access), getcfg("display.number")) - 1 |
| 10046 |
return display_no > -1 and bool(self.lut_access[display_no]) |
| 10047 |
|
| 10048 |
def has_separate_lut_access(self): |
| 10049 |
"""Return True if separate LUT access is possible and needed. |
| 10050 |
|
| 10051 |
Returns: |
| 10052 |
bool: True if separate LUT access is available and needed, |
| 10053 |
False otherwise. |
| 10054 |
""" |
| 10055 |
# Filter out Prisma, Resolve and Untethered |
| 10056 |
# IMPORTANT: Also make changes to display filtering in |
| 10057 |
# worker.Worker.enumerate_displays_and_ports |
| 10058 |
lut_access = self.lut_access[:-3] |
| 10059 |
if self.argyll_version >= [1, 6, 0]: |
| 10060 |
# Filter out madVR |
| 10061 |
lut_access = lut_access[:-1] |
| 10062 |
if self.argyll_version >= [1, 4, 0]: |
| 10063 |
# Filter out Web @ localhost |
| 10064 |
lut_access = lut_access[:-1] |
| 10065 |
return len(self.displays) > 1 and False in lut_access and True in lut_access |
| 10066 |
|
| 10067 |
def import_colorimeter_corrections(self, cmd, args=None, asroot=False): |
| 10068 |
"""Import colorimeter corrections. |
| 10069 |
|
| 10070 |
Args: |
| 10071 |
cmd (str): The command to execute for importing corrections. Can be |
| 10072 |
'i1d3ccss', 'spyd4en' or 'oeminst'. |
| 10073 |
args (list, optional): Additional arguments to pass to the command. |
| 10074 |
asroot (bool, optional): Whether to run the command as root. |
| 10075 |
|
| 10076 |
Returns: |
| 10077 |
Exception: If an error occurs during the import. |
| 10078 |
""" |
| 10079 |
if not args: |
| 10080 |
args = [] |
| 10081 |
if (is_superuser() or asroot) and "-Sl" not in args: |
| 10082 |
# If we are root or need root privs anyway, install to local |
| 10083 |
# system scope |
| 10084 |
args.insert(0, "-Sl") |
| 10085 |
return self.exec_cmd( |
| 10086 |
cmd, |
| 10087 |
["-v", *args], |
| 10088 |
capture_output=True, |
| 10089 |
skip_scripts=True, |
| 10090 |
silent=False, |
| 10091 |
asroot=asroot, |
| 10092 |
) |
| 10093 |
|
| 10094 |
def import_edr(self, args=None, asroot=False): |
| 10095 |
"""Import X-Rite .edr files. |
| 10096 |
|
| 10097 |
Args: |
| 10098 |
args (list, optional): Additional arguments to pass to the command. |
| 10099 |
asroot (bool, optional): Whether to run the command as root. |
| 10100 |
|
| 10101 |
Returns: |
| 10102 |
Exception: If an error occurs during the import. |
| 10103 |
""" |
| 10104 |
return self.import_colorimeter_corrections( |
| 10105 |
get_argyll_util("i1d3ccss"), args, asroot |
| 10106 |
) |
| 10107 |
|
| 10108 |
def import_spyd4cal(self, args=None, asroot=False): |
| 10109 |
"""Import Spyder4/5 calibrations to spy4cal.bin. |
| 10110 |
|
| 10111 |
Args: |
| 10112 |
args (list, optional): Additional arguments to pass to the command. |
| 10113 |
asroot (bool, optional): Whether to run the command as root. |
| 10114 |
|
| 10115 |
Returns: |
| 10116 |
Exception: If an error occurs during the import. |
| 10117 |
""" |
| 10118 |
return self.import_colorimeter_corrections( |
| 10119 |
get_argyll_util("spyd4en"), args, asroot |
| 10120 |
) |
| 10121 |
|
| 10122 |
def install_3dlut(self, path, filename=None): |
| 10123 |
"""Install 3D LUT from file. |
| 10124 |
|
| 10125 |
Args: |
| 10126 |
path (str): Path to the 3D LUT file. |
| 10127 |
filename (str, optional): Filename to use for the 3D LUT. If not |
| 10128 |
provided, the filename will be derived from the path. |
| 10129 |
|
| 10130 |
Returns: |
| 10131 |
Exception: If an error occurs during the installation. |
| 10132 |
""" |
| 10133 |
if getcfg("3dlut.format") == "madVR" and madvr: |
| 10134 |
# Install (load) 3D LUT using madTPG |
| 10135 |
print(path) |
| 10136 |
hdr_to_sdr = not getcfg("3dlut.hdr_display") |
| 10137 |
# Get parameters from actual 3D LUT file |
| 10138 |
h3dlut = madvr.H3DLUT(path) |
| 10139 |
xy = h3dlut.parametersData.get("Input_Primaries", []) |
| 10140 |
smpte2084 = h3dlut.parametersData.get("Input_Transfer_Function") == "PQ" |
| 10141 |
if len(xy) < 6: |
| 10142 |
# Should never happen |
| 10143 |
return Error("madVR 3D LUT doesn't contain Input_Primaries") |
| 10144 |
slot, rgb_space_name = h3dlut.source_colorspace |
| 10145 |
if slot is not None: |
| 10146 |
print("Input primaries match", rgb_space_name) |
| 10147 |
else: |
| 10148 |
return Error( |
| 10149 |
lang.getstr( |
| 10150 |
"3dlut.madvr.colorspace.unsupported", |
| 10151 |
[rgb_space_name or lang.getstr("unknown"), *xy[:6]], |
| 10152 |
) |
| 10153 |
) |
| 10154 |
args = [path, True, slot] |
| 10155 |
if smpte2084: |
| 10156 |
methodname = "load_hdr_3dlut_file" |
| 10157 |
args.append(hdr_to_sdr) |
| 10158 |
lut3d_section = "HDR" |
| 10159 |
if hdr_to_sdr: |
| 10160 |
lut3d_section += " to SDR" |
| 10161 |
else: |
| 10162 |
methodname = "load_3dlut_file" |
| 10163 |
lut3d_section = "calibration" |
| 10164 |
print( |
| 10165 |
"Installing madVR 3D LUT for " |
| 10166 |
f"{lut3d_section} slot {slot:d} ({rgb_space_name})..." |
| 10167 |
) |
| 10168 |
try: |
| 10169 |
# Connect & load 3D LUT |
| 10170 |
if self.madtpg_connect() and getattr(self.madtpg, methodname)(*args): |
| 10171 |
raise Info(lang.getstr("3dlut.install.success")) |
| 10172 |
raise Error(lang.getstr("3dlut.install.failure")) |
| 10173 |
except Exception as exception: |
| 10174 |
return exception |
| 10175 |
elif config.get_display_name(None, True) == "Prisma": |
| 10176 |
try: |
| 10177 |
# Use Prisma HTTP REST interface to upload 3D LUT |
| 10178 |
if not self.patterngenerator: |
| 10179 |
self.setup_patterngenerator() |
| 10180 |
self.patterngenerator.connect() |
| 10181 |
# Check preset. If it has a custom LUT assigned, we delete the |
| 10182 |
# currently assigned LUT before uploading, unless its filename |
| 10183 |
# is the same as the LUT to be uploaded, in which case it will |
| 10184 |
# be simply overwritten, and unless the custom LUT is still |
| 10185 |
# assigned to another preset as well. |
| 10186 |
presetname = getcfg("patterngenerator.prisma.preset") |
| 10187 |
if False: |
| 10188 |
# NEVER? |
| 10189 |
# Check all presets for currently assigned LUT |
| 10190 |
# Check the preset we're going to use for the upload last |
| 10191 |
presetnames = [ |
| 10192 |
name |
| 10193 |
for name in config.VALID_VALUES[ |
| 10194 |
"patterngenerator.prisma.preset" |
| 10195 |
] |
| 10196 |
if name != presetname |
| 10197 |
] |
| 10198 |
else: |
| 10199 |
# Check only the preset we're going to use for the upload |
| 10200 |
presetnames = [] |
| 10201 |
presetnames.append(presetname) |
| 10202 |
assigned_luts = {} |
| 10203 |
for presetname in presetnames: |
| 10204 |
self.log("Loading Prisma preset", presetname) |
| 10205 |
preset = self.patterngenerator.load_preset(presetname) |
| 10206 |
assigned_lut = preset["v"].get("cube", "") |
| 10207 |
if assigned_lut not in assigned_luts: |
| 10208 |
assigned_luts[assigned_lut] = 0 |
| 10209 |
assigned_luts[assigned_lut] += 1 |
| 10210 |
# Only remove the currently assigned custom LUT if it's not |
| 10211 |
# assigned to another preset |
| 10212 |
if ( |
| 10213 |
assigned_lut.lower().endswith(".3dl") |
| 10214 |
and assigned_luts[assigned_lut] == 1 |
| 10215 |
): |
| 10216 |
remove = preset["v"]["cube"] |
| 10217 |
else: |
| 10218 |
remove = False |
| 10219 |
# Check total size of installed 3D LUTs. The Prisma has 1 MB of |
| 10220 |
# custom LUT storage, which is enough for 15 67 KB LUTs. |
| 10221 |
maxsize = 1024 * 67 * 15 |
| 10222 |
installed = self.patterngenerator.get_installed_3dluts() |
| 10223 |
rawlen = len(installed["raw"]) |
| 10224 |
size = 0 |
| 10225 |
numinstalled = 0 |
| 10226 |
for table in installed["v"]["tables"]: |
| 10227 |
if table.get("n") != remove: |
| 10228 |
size += table.get("s", 0) |
| 10229 |
numinstalled += 1 |
| 10230 |
else: |
| 10231 |
rawlen -= len( |
| 10232 |
'{{"n":"{}", "s":{:d}}},'.format( |
| 10233 |
table["n"], table.get("s", 0) |
| 10234 |
) |
| 10235 |
) |
| 10236 |
filesize = os.stat(path).st_size |
| 10237 |
size_exceeded = size + filesize > maxsize |
| 10238 |
# NOTE that the total number of 3D LUT slots seems to be limited |
| 10239 |
# to 32, which includes built-in LUTs. |
| 10240 |
maxluts = 32 |
| 10241 |
luts_exceeded = numinstalled >= maxluts |
| 10242 |
if size_exceeded or luts_exceeded: |
| 10243 |
if size_exceeded: |
| 10244 |
missing = size + filesize - maxsize |
| 10245 |
elif luts_exceeded: |
| 10246 |
missing = filesize * (numinstalled + 1 - maxluts) |
| 10247 |
else: |
| 10248 |
missing = size + filesize - 1024 * 67 * 2 |
| 10249 |
raise Error( |
| 10250 |
lang.getstr( |
| 10251 |
"3dlut.holder.out_of_memory", |
| 10252 |
( |
| 10253 |
getcfg("patterngenerator.prisma.host"), |
| 10254 |
round(missing / 1024.0), |
| 10255 |
getcfg("patterngenerator.prisma.host"), |
| 10256 |
"Prisma", |
| 10257 |
), |
| 10258 |
) |
| 10259 |
) |
| 10260 |
if remove and remove != filename: |
| 10261 |
self.log("Removing currently assigned LUT", remove) |
| 10262 |
self.patterngenerator.remove_3dlut(remove) |
| 10263 |
self.log("Uploading LUT", path, "as", filename) |
| 10264 |
self.patterngenerator.load_3dlut_file(path, filename) |
| 10265 |
self.log("Setting LUT", filename) |
| 10266 |
self.patterngenerator.set_3dlut(filename) |
| 10267 |
self.log("Setting PrismaVue to zero") |
| 10268 |
self.patterngenerator.set_prismavue(0) |
| 10269 |
except Exception as exception: |
| 10270 |
return exception |
| 10271 |
return Info(lang.getstr("3dlut.install.success")) |
| 10272 |
else: |
| 10273 |
return Error(lang.getstr("3dlut.install.unsupported")) |
| 10274 |
|
| 10275 |
def install_profile( |
| 10276 |
self, profile_path, capture_output=True, skip_scripts=False, silent=False |
| 10277 |
): |
| 10278 |
"""Install a profile to the system and register it. |
| 10279 |
|
| 10280 |
Args: |
| 10281 |
profile_path (str): Path to the profile file to install. |
| 10282 |
capture_output (bool): Whether to capture output from the installation |
| 10283 |
process. |
| 10284 |
skip_scripts (bool): Whether to skip running scripts during installation. |
| 10285 |
silent (bool): Whether to suppress output messages during installation. |
| 10286 |
|
| 10287 |
Returns: |
| 10288 |
bool | str: True if the installation was successful, a string with |
| 10289 |
the installed profile path if the profile was installed with a |
| 10290 |
different name, or an exception if the installation failed. |
| 10291 |
""" |
| 10292 |
colord_install = None |
| 10293 |
oy_install = None |
| 10294 |
argyll_install = self._install_profile_argyll( |
| 10295 |
profile_path, capture_output, skip_scripts, silent |
| 10296 |
) |
| 10297 |
if isinstance(argyll_install, str): |
| 10298 |
# The installed name may be different due to escaping non-ASCII |
| 10299 |
# chars (see prepare_dispwin), so get the profile path |
| 10300 |
profile_path = argyll_install |
| 10301 |
argyll_install = True |
| 10302 |
if sys.platform == "win32": |
| 10303 |
# Assign profile to active display |
| 10304 |
display_no = min(len(self.displays), getcfg("display.number")) - 1 |
| 10305 |
monitors = util_win.get_real_display_devices_info() |
| 10306 |
moninfo = monitors[display_no] |
| 10307 |
displays = util_win.get_display_devices(moninfo["Device"]) |
| 10308 |
active_display = util_win.get_active_display_device(None, displays) |
| 10309 |
if not active_display: |
| 10310 |
self.log(f"{APPNAME}: Warning - no active display device!") |
| 10311 |
if not displays: |
| 10312 |
self.log( |
| 10313 |
f"{APPNAME}: Warning - could not enumerate " |
| 10314 |
"display devices for {}!".format(moninfo["Device"]) |
| 10315 |
) |
| 10316 |
elif active_display.DeviceKey != displays[0].DeviceKey: |
| 10317 |
self.log(f"{APPNAME}: Setting profile for active display device...") |
| 10318 |
try: |
| 10319 |
set_display_profile( |
| 10320 |
os.path.basename(profile_path), |
| 10321 |
devicekey=active_display.DeviceKey, |
| 10322 |
) |
| 10323 |
except Exception as exception: |
| 10324 |
# Not a critical error. Only log the exception. |
| 10325 |
if ( |
| 10326 |
isinstance(exception, EnvironmentError) |
| 10327 |
and not exception.filename |
| 10328 |
and not os.path.isfile(profile_path) |
| 10329 |
): |
| 10330 |
exception.filename = profile_path |
| 10331 |
self.log( |
| 10332 |
f"{APPNAME}: Warning - could not set profile for " |
| 10333 |
"active display device:", |
| 10334 |
exception, |
| 10335 |
) |
| 10336 |
else: |
| 10337 |
self.log(f"{APPNAME}: ...ok") |
| 10338 |
loader_install = None |
| 10339 |
profile = None |
| 10340 |
try: |
| 10341 |
profile = ICCProfile(profile_path) |
| 10342 |
except (OSError, ICCProfileInvalidError) as exception: |
| 10343 |
return exception |
| 10344 |
device_id = self.get_device_id(quirk=False, query=True) |
| 10345 |
if ( |
| 10346 |
sys.platform not in ("darwin", "win32") |
| 10347 |
and not getcfg("dry_run") |
| 10348 |
and ( |
| 10349 |
argyll_install is not True |
| 10350 |
or self.argyll_version < [1, 6] |
| 10351 |
or not os.getenv("ARGYLL_USE_COLORD") |
| 10352 |
or not dlopen("libcolordcompat.so") |
| 10353 |
) |
| 10354 |
and which("colormgr") |
| 10355 |
): |
| 10356 |
if device_id: |
| 10357 |
result = self._attempt_install_profile_colord(profile, device_id) |
| 10358 |
colord_install = result |
| 10359 |
if not device_id or result is not True: |
| 10360 |
gcm_import = bool(which("gcm-import")) |
| 10361 |
if gcm_import: |
| 10362 |
self._install_profile_gcm(profile) |
| 10363 |
# gcm-import doesn't seem to return a useful exit code or |
| 10364 |
# stderr output, so check for our profile |
| 10365 |
profilename = os.path.basename(profile.filename) |
| 10366 |
for dirname in defaultpaths.ICCPROFILES_HOME: |
| 10367 |
profile_install_path = os.path.join(dirname, profilename) |
| 10368 |
if os.path.isfile(profile_install_path): |
| 10369 |
colord_install = Warn(lang.getstr("profile.import.success")) |
| 10370 |
break |
| 10371 |
if which("oyranos-monitor") and self.check_display_conf_oy_compat( |
| 10372 |
getcfg("display.number") |
| 10373 |
): |
| 10374 |
if device_id: |
| 10375 |
profile_name = re.sub(r"[- ]", "_", device_id.lower()) + ".icc" |
| 10376 |
else: |
| 10377 |
profile_name = None |
| 10378 |
result = self._install_profile_oy( |
| 10379 |
profile_path, profile_name, capture_output, skip_scripts, silent |
| 10380 |
) |
| 10381 |
oy_install = result |
| 10382 |
if argyll_install is not True and ( |
| 10383 |
(colord_install and not isinstance(colord_install, colord.CDError)) |
| 10384 |
or oy_install is True |
| 10385 |
): |
| 10386 |
# Ignore Argyll install errors if colord or Oyranos install was |
| 10387 |
# succesful |
| 10388 |
argyll_install = None |
| 10389 |
# Check if atleast one of our profile install methods did return a |
| 10390 |
# result that is not an error |
| 10391 |
for result in (argyll_install, colord_install, oy_install): |
| 10392 |
check = result is True or isinstance(result, Warning) |
| 10393 |
if check: |
| 10394 |
break |
| 10395 |
# Only go on to create profile loader if profile loading on login |
| 10396 |
# isn't disabled in the config file, and we are not under Mac OS X |
| 10397 |
# (no loader required there), and if atleast one of our profile |
| 10398 |
# install methods did return a result that is not an error |
| 10399 |
if getcfg("profile.load_on_login") and sys.platform != "darwin" and check: |
| 10400 |
# Create profile loader. Failing to create it is a critical error |
| 10401 |
# under Windows if calibration loading isn't handled by the OS |
| 10402 |
# (this is checked), and also under Linux if colord profile install |
| 10403 |
# failed (colord handles loading otherwise) |
| 10404 |
check = sys.platform == "win32" or ( |
| 10405 |
not colord_install or isinstance(colord_install, colord.CDError) |
| 10406 |
) |
| 10407 |
if getcfg("profile.install_scope") == "l" and sys.platform != "win32": |
| 10408 |
# We need a system-wide config file to store the path to |
| 10409 |
# the Argyll binaries for the profile loader |
| 10410 |
if not config.makecfgdir("system", self) or ( |
| 10411 |
not config.writecfg("system", self) and check |
| 10412 |
): |
| 10413 |
# If the system-wide config dir could not be created, |
| 10414 |
# or the system-wide config file could not be written, |
| 10415 |
# error out if under Linux and colord profile install failed |
| 10416 |
return Error(lang.getstr("error.autostart_system")) |
| 10417 |
if sys.platform == "win32": |
| 10418 |
loader_install = self._install_profile_loader_win32(silent) |
| 10419 |
else: |
| 10420 |
loader_install = self._install_profile_loader_xdg(silent) |
| 10421 |
if loader_install is not True and check: |
| 10422 |
return loader_install |
| 10423 |
# Check if atleast one of our profile install methods returned a result |
| 10424 |
for result in (argyll_install, colord_install, oy_install): |
| 10425 |
if result is not None: |
| 10426 |
return argyll_install, colord_install, oy_install, loader_install |
| 10427 |
if not result: |
| 10428 |
# This should never happen |
| 10429 |
result = Error(lang.getstr("profile.install.error")) |
| 10430 |
return result |
| 10431 |
|
| 10432 |
def install_argyll_instrument_conf(self, uninstall=False, filenames=None): |
| 10433 |
"""(Un-)install Argyll CMS instrument configuration under Linux. |
| 10434 |
|
| 10435 |
Args: |
| 10436 |
uninstall (bool): If True, uninstall the configuration. |
| 10437 |
filenames (list[str]): List of filenames to install or uninstall. |
| 10438 |
If None, use the default Argyll instrument configuration files |
| 10439 |
(e.g. 'colord.conf', 'colord.rules', etc.) or uninstall all |
| 10440 |
installed files. |
| 10441 |
|
| 10442 |
Returns: |
| 10443 |
Error, Info, or None: Returns an Error if something went wrong, |
| 10444 |
Info if the operation was successful, or None if no files were |
| 10445 |
installed or uninstalled. |
| 10446 |
""" |
| 10447 |
udevrules = "/etc/udev/rules.d" |
| 10448 |
hotplug = "/etc/hotplug" |
| 10449 |
if not os.path.isdir(udevrules) and not os.path.isdir(hotplug): |
| 10450 |
return Error(lang.getstr("udev_hotplug.unavailable")) |
| 10451 |
if not filenames: |
| 10452 |
filenames = get_argyll_instrument_config("installed" if uninstall else None) |
| 10453 |
if not filenames: |
| 10454 |
return Error( |
| 10455 |
"\n".join( |
| 10456 |
lang.getstr("file.missing", filename) |
| 10457 |
for filename in get_argyll_instrument_config("expected") |
| 10458 |
) |
| 10459 |
) |
| 10460 |
if uninstall: |
| 10461 |
backupbase = os.path.join( |
| 10462 |
config.DATA_HOME, "backup", strftime("%Y%m%dT%H%M%S") |
| 10463 |
) |
| 10464 |
for filename in filenames: |
| 10465 |
dst = udevrules if filename.endswith(".rules") else hotplug |
| 10466 |
if uninstall: |
| 10467 |
# Move file to backup location |
| 10468 |
backupdir = "".join([backupbase, os.path.dirname(filename)]) |
| 10469 |
if not os.path.isdir(backupdir): |
| 10470 |
os.makedirs(backupdir) |
| 10471 |
cmd, args = "mv", [filename, f"{backupbase}{filename}"] |
| 10472 |
else: |
| 10473 |
cmd, args = "cp", ["--remove-destination", filename] |
| 10474 |
args.append(os.path.join(dst, os.path.basename(filename))) |
| 10475 |
result = self.exec_cmd( |
| 10476 |
cmd, args, capture_output=True, skip_scripts=True, asroot=True |
| 10477 |
) |
| 10478 |
if result is not True: |
| 10479 |
break |
| 10480 |
if not uninstall: |
| 10481 |
self.exec_cmd( |
| 10482 |
"chmod", |
| 10483 |
["0644", args[-1]], |
| 10484 |
capture_output=True, |
| 10485 |
skip_scripts=True, |
| 10486 |
asroot=True, |
| 10487 |
) |
| 10488 |
install_result = result |
| 10489 |
paths = ["/sbin", "/usr/sbin"] |
| 10490 |
paths.extend(getenvu("PATH", os.defpath).split(os.pathsep)) |
| 10491 |
if not uninstall: |
| 10492 |
if ( |
| 10493 |
not isinstance(result, Exception) |
| 10494 |
and result |
| 10495 |
and ("colord" not in [g.gr_name for g in grp.getgrall()]) |
| 10496 |
and (groupadd := which("groupadd", paths)) |
| 10497 |
): |
| 10498 |
# Add colord group if it does not exist |
| 10499 |
result = self.exec_cmd( |
| 10500 |
groupadd, |
| 10501 |
["colord"], |
| 10502 |
capture_output=True, |
| 10503 |
skip_scripts=True, |
| 10504 |
asroot=True, |
| 10505 |
) |
| 10506 |
if ( |
| 10507 |
not isinstance(result, Exception) |
| 10508 |
and result |
| 10509 |
and "colord" not in getgroups(getpass.getuser(), True) |
| 10510 |
and (usermod := which("usermod", paths)) |
| 10511 |
): |
| 10512 |
# Add user to colord group if not yet a member |
| 10513 |
result = self.exec_cmd( |
| 10514 |
usermod, |
| 10515 |
["-a", "-G", "colord", getpass.getuser()], |
| 10516 |
capture_output=True, |
| 10517 |
skip_scripts=True, |
| 10518 |
asroot=True, |
| 10519 |
) |
| 10520 |
if ( |
| 10521 |
install_result is True |
| 10522 |
and dst == udevrules |
| 10523 |
and (udevadm := which("udevadm", paths)) |
| 10524 |
): |
| 10525 |
# Reload udev rules |
| 10526 |
result = self.exec_cmd( |
| 10527 |
udevadm, |
| 10528 |
["control", "--reload-rules"], |
| 10529 |
capture_output=True, |
| 10530 |
skip_scripts=True, |
| 10531 |
asroot=True, |
| 10532 |
) |
| 10533 |
return result |
| 10534 |
|
| 10535 |
def install_argyll_instrument_drivers(self, uninstall=False, launch_devman=False): |
| 10536 |
"""(Un-)install the Argyll CMS instrument drivers under Windows. |
| 10537 |
|
| 10538 |
Args: |
| 10539 |
uninstall (bool): If True, uninstall the drivers. |
| 10540 |
launch_devman (bool): If True, launch Device Manager after |
| 10541 |
installing or uninstalling the drivers. |
| 10542 |
|
| 10543 |
Returns: |
| 10544 |
Error, Info, or None: Returns an Error if something went wrong, |
| 10545 |
Info if the operation was successful, or None if no drivers |
| 10546 |
were installed or uninstalled. |
| 10547 |
""" |
| 10548 |
winxp = sys.getwindowsversion() < (6,) |
| 10549 |
if launch_devman: |
| 10550 |
if winxp: |
| 10551 |
cmd = "start" |
| 10552 |
args = ["mmc", "devmgmt.msc"] |
| 10553 |
else: |
| 10554 |
cmd = "mmc" |
| 10555 |
args = ["devmgmt.msc"] |
| 10556 |
self.exec_cmd( |
| 10557 |
cmd, |
| 10558 |
args, |
| 10559 |
capture_output=True, |
| 10560 |
skip_scripts=True, |
| 10561 |
asroot=not winxp, |
| 10562 |
shell=winxp, |
| 10563 |
working_dir=False, |
| 10564 |
) |
| 10565 |
if uninstall: |
| 10566 |
if not winxp: |
| 10567 |
# Windows Vista and newer |
| 10568 |
with win64_disable_file_system_redirection(): |
| 10569 |
pnputil = which("PnPutil.exe") |
| 10570 |
if not pnputil: |
| 10571 |
return Error(lang.getstr("file.missing", "PnPutil.exe")) |
| 10572 |
result = self.exec_cmd( |
| 10573 |
pnputil, |
| 10574 |
["-e"], |
| 10575 |
capture_output=True, |
| 10576 |
log_output=False, |
| 10577 |
silent=True, |
| 10578 |
skip_scripts=True, |
| 10579 |
) |
| 10580 |
if not result: |
| 10581 |
return Error( |
| 10582 |
lang.getstr("argyll.instrument.drivers.uninstall.failure") |
| 10583 |
) |
| 10584 |
if isinstance(result, Exception): |
| 10585 |
return result |
| 10586 |
output = universal_newlines("".join(self.output)) |
| 10587 |
for entry in output.split("\n\n"): |
| 10588 |
entry = [ |
| 10589 |
line.split(":", 1)[-1].strip() for line in entry.split("\n") |
| 10590 |
] |
| 10591 |
for value in entry: |
| 10592 |
if value == "ArgyllCMS": |
| 10593 |
result = self.exec_cmd( |
| 10594 |
pnputil, |
| 10595 |
["-f", "-d", entry[0]], |
| 10596 |
capture_output=True, |
| 10597 |
skip_scripts=True, |
| 10598 |
asroot=True, |
| 10599 |
) |
| 10600 |
else: |
| 10601 |
# Windows XP |
| 10602 |
# Uninstallation not supported |
| 10603 |
pass |
| 10604 |
else: |
| 10605 |
# Install driver using modified 'zadic' command line tool from |
| 10606 |
# https://github.com/fhoech/libwdi |
| 10607 |
|
| 10608 |
result = None |
| 10609 |
|
| 10610 |
# Get Argyll version |
| 10611 |
argyll_version_string = self.argyll_version_string |
| 10612 |
if argyll_version_string == "0.0.0": |
| 10613 |
# Download version info |
| 10614 |
resp = http_request( |
| 10615 |
None, |
| 10616 |
DOMAIN, |
| 10617 |
"GET", |
| 10618 |
"/Argyll/VERSION", |
| 10619 |
failure_msg=lang.getstr("update_check.fail"), |
| 10620 |
silent=True, |
| 10621 |
) |
| 10622 |
if resp: |
| 10623 |
argyll_version_string = resp.read().strip() |
| 10624 |
|
| 10625 |
installer_basename = "ArgyllCMS_install_USB.exe" |
| 10626 |
download_dir = os.path.join(config.DATA_HOME, "dl") |
| 10627 |
installer = os.path.join( |
| 10628 |
download_dir, |
| 10629 |
f"Argyll_V{argyll_version_string}", |
| 10630 |
"usb", |
| 10631 |
installer_basename, |
| 10632 |
) |
| 10633 |
if not os.path.isfile(installer): |
| 10634 |
# Update installer_basename to the one that is used in DisplayCAL.net |
| 10635 |
installer_basename = ( |
| 10636 |
f"Argyll_V{argyll_version_string}_USB_driver_installer.exe" |
| 10637 |
) |
| 10638 |
installer_zip = self.download( |
| 10639 |
f"https://{DOMAIN}/Argyll/{installer_basename}.zip" |
| 10640 |
) |
| 10641 |
if isinstance(installer_zip, Exception): |
| 10642 |
return installer_zip |
| 10643 |
if not installer_zip: |
| 10644 |
# Cancelled |
| 10645 |
return None |
| 10646 |
|
| 10647 |
installer = os.path.splitext(installer_zip)[0] |
| 10648 |
# Open installer ZIP archive |
| 10649 |
try: |
| 10650 |
with zipfile.ZipFile(installer_zip) as z: |
| 10651 |
# Extract installer if it does not exist or if the existing |
| 10652 |
# file is different from the one in the archive |
| 10653 |
if os.path.isfile(installer): |
| 10654 |
with open(installer, "rb") as f: |
| 10655 |
crc = zlib.crc32(f.read()) |
| 10656 |
else: |
| 10657 |
crc = None |
| 10658 |
if ( |
| 10659 |
not os.path.isfile(installer) |
| 10660 |
or crc != z.getinfo(installer_basename).CRC |
| 10661 |
): |
| 10662 |
z.extract( |
| 10663 |
installer_basename, os.path.dirname(installer_zip) |
| 10664 |
) |
| 10665 |
except Exception as exception: |
| 10666 |
return exception |
| 10667 |
|
| 10668 |
# Get supported instruments USB device IDs |
| 10669 |
usb_ids = {} |
| 10670 |
for instrument_name in all_instruments: |
| 10671 |
instrument = all_instruments[instrument_name] |
| 10672 |
if instrument.get("usb_ids"): |
| 10673 |
for entry in instrument.get("usb_ids"): |
| 10674 |
usb_id = (entry["vid"], entry["pid"]) |
| 10675 |
if entry.get("hid"): |
| 10676 |
# Skip HID devices |
| 10677 |
continue |
| 10678 |
usb_ids[usb_id] = usb_ids.get(usb_id, [instrument_name]) |
| 10679 |
usb_ids[usb_id].append(instrument_name) |
| 10680 |
|
| 10681 |
# Check connected USB devices for supported instruments |
| 10682 |
not_main_thread = current_thread() != main_thread() |
| 10683 |
if not_main_thread: |
| 10684 |
# If running in a thread, need to call pythoncom.CoInitialize |
| 10685 |
pythoncom.CoInitialize() |
| 10686 |
try: |
| 10687 |
if not wmi: |
| 10688 |
raise NotImplementedError("WMI not available") |
| 10689 |
wmi_connection = wmi.WMI() |
| 10690 |
query = "Select * From Win32_USBControllerDevice" |
| 10691 |
for item in wmi_connection.query(query): |
| 10692 |
try: |
| 10693 |
device_id = item.Dependent.DeviceID |
| 10694 |
except wmi.x_wmi as exception: |
| 10695 |
self.log(exception) |
| 10696 |
continue |
| 10697 |
for usb_id in usb_ids: |
| 10698 |
instrument_names = usb_ids[usb_id] |
| 10699 |
hardware_id = r"USB\VID_{:04X}&PID_{:04X}".format(*usb_id) |
| 10700 |
if device_id.startswith(hardware_id): |
| 10701 |
# Found supported instrument |
| 10702 |
try: |
| 10703 |
self.log(item.Dependent.Caption) |
| 10704 |
except wmi.x_wmi: |
| 10705 |
self.log(", ".join(instrument_names)) |
| 10706 |
# Install driver for specific device |
| 10707 |
result = self.exec_cmd( |
| 10708 |
installer, |
| 10709 |
[ |
| 10710 |
"--noprompt", |
| 10711 |
"--usealldevices", |
| 10712 |
"--vid", |
| 10713 |
hex(usb_id[0]), |
| 10714 |
"--pid", |
| 10715 |
hex(usb_id[1]), |
| 10716 |
], |
| 10717 |
capture_output=True, |
| 10718 |
skip_scripts=True, |
| 10719 |
asroot=True, |
| 10720 |
) |
| 10721 |
output = universal_newlines("".join(self.output)) |
| 10722 |
if isinstance(result, Exception): |
| 10723 |
return result |
| 10724 |
if not result or "Failed to install driver" in output: |
| 10725 |
return Error( |
| 10726 |
lang.getstr( |
| 10727 |
"argyll.instrument.drivers.install.failure" |
| 10728 |
) |
| 10729 |
) |
| 10730 |
except Exception as exception: |
| 10731 |
self.log(exception) |
| 10732 |
finally: |
| 10733 |
if not_main_thread: |
| 10734 |
# If running in a thread, need to call pythoncom.CoUninitialize |
| 10735 |
pythoncom.CoUninitialize() |
| 10736 |
|
| 10737 |
if not result: |
| 10738 |
# No matching device found. Install driver anyway, doesn't |
| 10739 |
# matter for which specific device as the .inf contains entries |
| 10740 |
# for all supported ones, thus instruments that are connected |
| 10741 |
# later should be recognized |
| 10742 |
usb_id, instrument_names = usb_ids.popitem() |
| 10743 |
result = self.exec_cmd( |
| 10744 |
installer, |
| 10745 |
[ |
| 10746 |
"--noprompt", |
| 10747 |
"--vid", |
| 10748 |
hex(usb_id[0]), |
| 10749 |
"--pid", |
| 10750 |
hex(usb_id[1]), |
| 10751 |
"--create", |
| 10752 |
f"{instrument_names[-1]} (Argyll)", |
| 10753 |
], |
| 10754 |
capture_output=True, |
| 10755 |
skip_scripts=True, |
| 10756 |
asroot=True, |
| 10757 |
) |
| 10758 |
output = universal_newlines("".join(self.output)) |
| 10759 |
if not result or "Failed to install driver" in output: |
| 10760 |
return Error( |
| 10761 |
lang.getstr("argyll.instrument.drivers.install.failure") |
| 10762 |
) |
| 10763 |
|
| 10764 |
return result |
| 10765 |
|
| 10766 |
def _install_profile_argyll( |
| 10767 |
self, profile_path, capture_output=False, skip_scripts=False, silent=False |
| 10768 |
): |
| 10769 |
"""Install profile using dispwin. |
| 10770 |
|
| 10771 |
Args: |
| 10772 |
profile_path (str): The path to the profile to install. |
| 10773 |
capture_output (bool): Whether to capture the output of the |
| 10774 |
command. |
| 10775 |
skip_scripts (bool): Whether to skip running scripts. |
| 10776 |
silent (bool): Whether to suppress output messages. |
| 10777 |
|
| 10778 |
Return: |
| 10779 |
str | bool | Exception: The profile path, an error or False. |
| 10780 |
|
| 10781 |
""" |
| 10782 |
if False: # if sys.platform == "darwin": # NEVER |
| 10783 |
# Alternate way of 'installing' the profile under OS X by just |
| 10784 |
# copying it |
| 10785 |
profiles = os.path.join("Library", "ColorSync", "Profiles") |
| 10786 |
profile_install_path = os.path.join( |
| 10787 |
profiles, os.path.basename(profile_path) |
| 10788 |
) |
| 10789 |
network = os.path.join(os.path.sep, "Network", profiles) |
| 10790 |
if getcfg("profile.install_scope") == "l": |
| 10791 |
profile_install_path = os.path.join(os.path.sep, profile_install_path) |
| 10792 |
elif getcfg("profile.install_scope") == "n" and os.path.isdir(network): |
| 10793 |
profile_install_path = os.path.join(network, profile_install_path) |
| 10794 |
else: |
| 10795 |
profile_install_path = os.path.join( |
| 10796 |
os.path.expanduser("~"), profile_install_path |
| 10797 |
) |
| 10798 |
cmd, args = "cp", ["-f", profile_path, profile_install_path] |
| 10799 |
result = self.exec_cmd( |
| 10800 |
cmd, |
| 10801 |
args, |
| 10802 |
capture_output, |
| 10803 |
low_contrast=False, |
| 10804 |
skip_scripts=skip_scripts, |
| 10805 |
silent=silent, |
| 10806 |
asroot=getcfg("profile.install_scope") in ("l", "n"), |
| 10807 |
title=lang.getstr("profile.install"), |
| 10808 |
) |
| 10809 |
if not isinstance(result, Exception) and result: |
| 10810 |
self.output = ["Installed"] |
| 10811 |
else: |
| 10812 |
cmd, args = self.prepare_dispwin(None, profile_path, True) |
| 10813 |
if not isinstance(cmd, Exception): |
| 10814 |
profile_path = args[-1] |
| 10815 |
if sys.platform == "win32" and sys.getwindowsversion() >= (6,): |
| 10816 |
# Set/unset per-user profiles under Vista / Windows 7 |
| 10817 |
idx = getcfg("display.number") - 1 |
| 10818 |
try: |
| 10819 |
device0 = util_win.get_display_device(idx, exception_cls=None) |
| 10820 |
devicea = util_win.get_display_device(idx, True) |
| 10821 |
except Exception as exception: |
| 10822 |
self.log(f"util_win.get_display_device({idx}):", exception) |
| 10823 |
else: |
| 10824 |
per_user = "-Sl" not in args |
| 10825 |
for i, device in enumerate((device0, devicea)): |
| 10826 |
if not device: |
| 10827 |
self.log( |
| 10828 |
"Warning: There is no {} display " |
| 10829 |
"device to {} per-user profiles".format( |
| 10830 |
"1st" if i == 0 else "active", |
| 10831 |
"enable" if per_user else "disable", |
| 10832 |
) |
| 10833 |
) |
| 10834 |
continue |
| 10835 |
try: |
| 10836 |
util_win.enable_per_user_profiles( |
| 10837 |
per_user, devicekey=device.DeviceKey |
| 10838 |
) |
| 10839 |
except Exception as exception: |
| 10840 |
self.log( |
| 10841 |
f"util_win.enable_per_user_profiles({per_user}, " |
| 10842 |
f"devicekey={device.DeviceKey!r}): " |
| 10843 |
f"{exception}" |
| 10844 |
) |
| 10845 |
if "-Sl" in args and ( |
| 10846 |
sys.platform != "darwin" |
| 10847 |
or intlist(platform.mac_ver()[0].split(".")) >= [10, 6] |
| 10848 |
): |
| 10849 |
# If a 'system' install is requested under Linux, |
| 10850 |
# Mac OS X >= 10.6 or Windows, |
| 10851 |
# install in 'user' scope first because a system-wide install |
| 10852 |
# doesn't also set it as current user profile on those systems |
| 10853 |
# (on Mac OS X < 10.6, we can use ColorSyncScripting to set it). |
| 10854 |
# It has the small drawback under Linux and OS X 10.6 that |
| 10855 |
# it will copy the profile to both the user and system-wide |
| 10856 |
# locations, though, which is not a problem under Windows as |
| 10857 |
# they are the same. |
| 10858 |
args.remove("-Sl") |
| 10859 |
result = self.exec_cmd( |
| 10860 |
cmd, |
| 10861 |
args, |
| 10862 |
capture_output, |
| 10863 |
low_contrast=False, |
| 10864 |
skip_scripts=skip_scripts, |
| 10865 |
silent=silent, |
| 10866 |
title=lang.getstr("profile.install"), |
| 10867 |
) |
| 10868 |
output = list(self.output) |
| 10869 |
args.insert(0, "-Sl") |
| 10870 |
else: |
| 10871 |
output = None |
| 10872 |
result = True |
| 10873 |
if not isinstance(result, Exception) and result: |
| 10874 |
result = self.exec_cmd( |
| 10875 |
cmd, |
| 10876 |
args, |
| 10877 |
capture_output, |
| 10878 |
low_contrast=False, |
| 10879 |
skip_scripts=skip_scripts, |
| 10880 |
silent=silent, |
| 10881 |
title=lang.getstr("profile.install"), |
| 10882 |
) |
| 10883 |
else: |
| 10884 |
result = cmd |
| 10885 |
if not isinstance(result, Exception) and result is not None: |
| 10886 |
result = False |
| 10887 |
for line in output or self.output: |
| 10888 |
if "Installed" in line: |
| 10889 |
if ( |
| 10890 |
sys.platform == "darwin" |
| 10891 |
and "-Sl" in args |
| 10892 |
and intlist(platform.mac_ver()[0].split(".")) < [10, 6] |
| 10893 |
): |
| 10894 |
# The profile has been installed, but we need a little |
| 10895 |
# help from AppleScript to actually make it the default |
| 10896 |
# for the current user. Only works under Mac OS < 10.6 |
| 10897 |
n = getcfg("display.number") |
| 10898 |
path = os.path.join( |
| 10899 |
os.path.sep, |
| 10900 |
"Library", |
| 10901 |
"ColorSync", |
| 10902 |
"Profiles", |
| 10903 |
os.path.basename(args[-1]), |
| 10904 |
) |
| 10905 |
applescript = [ |
| 10906 |
'tell app "ColorSyncScripting"', |
| 10907 |
f'set displayProfile to POSIX file "{path}" as alias', |
| 10908 |
f"set display profile of display {n:d} to displayProfile", |
| 10909 |
"end tell", |
| 10910 |
] |
| 10911 |
try: |
| 10912 |
retcode, output, errors = osascript(applescript) |
| 10913 |
except Exception as exception: |
| 10914 |
self.log(exception) |
| 10915 |
else: |
| 10916 |
if errors.strip(): |
| 10917 |
self.log(f"osascript error: {errors}") |
| 10918 |
else: |
| 10919 |
result = True |
| 10920 |
break |
| 10921 |
if False: # if sys.platform == "darwin": # NEVER |
| 10922 |
# After 'installing' a profile under Mac OS X by just |
| 10923 |
# copying it, show system preferences |
| 10924 |
applescript = [ |
| 10925 |
'tell application "System Preferences"', |
| 10926 |
"activate", |
| 10927 |
"set current pane to pane id " |
| 10928 |
'"com.apple.preference.displays"', |
| 10929 |
"reveal (first anchor of current pane whose name is " |
| 10930 |
'"displaysColorTab")', |
| 10931 |
# This needs access for assistive devices enabled |
| 10932 |
# 'tell application "System Events"', |
| 10933 |
# 'tell process "System Preferences"', |
| 10934 |
# 'select row 2 of table 1 of scroll area 1 of group 1 of ' |
| 10935 |
# 'tab group 1 of window "<Display name from EDID here>"', |
| 10936 |
# 'end tell', |
| 10937 |
# 'end tell', |
| 10938 |
"end tell", |
| 10939 |
] |
| 10940 |
try: |
| 10941 |
retcode, output, errors = osascript(applescript) |
| 10942 |
except Exception as exception: |
| 10943 |
self.log(exception) |
| 10944 |
else: |
| 10945 |
if errors.strip(): |
| 10946 |
self.log(f"osascript error: {errors}") |
| 10947 |
else: |
| 10948 |
result = True |
| 10949 |
else: |
| 10950 |
result = True |
| 10951 |
break |
| 10952 |
if not result and self.errors: |
| 10953 |
result = Error("".join(self.errors).strip()) |
| 10954 |
else: |
| 10955 |
result = profile_path |
| 10956 |
# DO NOT call wrapup() here, it'll remove the profile in the temp |
| 10957 |
# directory before dispwin can get a hold of it when running with UAC |
| 10958 |
# under Windows, because that makes the call to dispwin run in a |
| 10959 |
# separate thread. DisplayCAL.MainFrame.profile_finish_consumer calls |
| 10960 |
# DisplayCAL.MainFrame.start_timers(True) after displaying the result |
| 10961 |
# message which takes care of cleanup. |
| 10962 |
return result |
| 10963 |
|
| 10964 |
def _install_profile_colord(self, profile, device_id): |
| 10965 |
"""Install profile using colord. |
| 10966 |
|
| 10967 |
Args: |
| 10968 |
profile (ICCProfile): The ICCProfile object to install. |
| 10969 |
device_id (str): The device ID to use for installation. |
| 10970 |
|
| 10971 |
Returns: |
| 10972 |
bool | colord.CDError: True if the profile was successfully |
| 10973 |
installed, or a colord.CDError if an error occurred. |
| 10974 |
""" |
| 10975 |
self.log(f"{APPNAME}: Trying device ID {device_id}") |
| 10976 |
try: |
| 10977 |
colord.install_profile(device_id, profile, logfn=self.log) |
| 10978 |
except Exception as exception: |
| 10979 |
self.log(exception) |
| 10980 |
return exception |
| 10981 |
return True |
| 10982 |
|
| 10983 |
def _attempt_install_profile_colord(self, profile, device_id=None): |
| 10984 |
"""Attempt to install a profile using colord with various quirks. |
| 10985 |
|
| 10986 |
Args: |
| 10987 |
profile (ICCProfile): The ICCProfile object to install. |
| 10988 |
device_id (str, optional): The device ID to use for installation. |
| 10989 |
|
| 10990 |
Returns: |
| 10991 |
None | bool | colord.CDError: True if the profile was successfully |
| 10992 |
installed, None if the device ID was not found, or a |
| 10993 |
colord.CDError or colord.CDObjectQueryError if an error |
| 10994 |
occurred. |
| 10995 |
""" |
| 10996 |
if not device_id: |
| 10997 |
device_id = self.get_device_id(quirk=False, query=True) |
| 10998 |
if not device_id: |
| 10999 |
return None |
| 11000 |
result = False |
| 11001 |
# Try a range of possible device IDs |
| 11002 |
device_ids = [ |
| 11003 |
device_id, |
| 11004 |
self.get_device_id(quirk=True, truncate_edid_strings=True), |
| 11005 |
self.get_device_id(quirk=True, use_serial_32=False), |
| 11006 |
self.get_device_id( |
| 11007 |
quirk=True, use_serial_32=False, truncate_edid_strings=True |
| 11008 |
), |
| 11009 |
self.get_device_id(quirk=True), |
| 11010 |
self.get_device_id(quirk=False, truncate_edid_strings=True), |
| 11011 |
self.get_device_id(quirk=False, use_serial_32=False), |
| 11012 |
self.get_device_id( |
| 11013 |
quirk=False, use_serial_32=False, truncate_edid_strings=True |
| 11014 |
), |
| 11015 |
# Try with manufacturer omitted |
| 11016 |
self.get_device_id(omit_manufacturer=True), |
| 11017 |
self.get_device_id(truncate_edid_strings=True, omit_manufacturer=True), |
| 11018 |
self.get_device_id(use_serial_32=False, omit_manufacturer=True), |
| 11019 |
self.get_device_id( |
| 11020 |
use_serial_32=False, |
| 11021 |
truncate_edid_strings=True, |
| 11022 |
omit_manufacturer=True, |
| 11023 |
), |
| 11024 |
] |
| 11025 |
for device_id in dict.fromkeys(device_ids): |
| 11026 |
if not device_id: |
| 11027 |
continue |
| 11028 |
# NOTE: This can block |
| 11029 |
result = self._install_profile_colord(profile, device_id) |
| 11030 |
if isinstance(result, colord.CDObjectQueryError): |
| 11031 |
# Device ID was not found, try next one |
| 11032 |
continue |
| 11033 |
# Either returned ok or there was another error |
| 11034 |
break |
| 11035 |
return result |
| 11036 |
|
| 11037 |
def _install_profile_gcm(self, profile): |
| 11038 |
"""Install profile using gcm-import. |
| 11039 |
|
| 11040 |
Args: |
| 11041 |
profile (ICCProfile): The ICCProfile object to install. |
| 11042 |
|
| 11043 |
Returns: |
| 11044 |
None: If the profile was successfully installed or already exists. |
| 11045 |
""" |
| 11046 |
if which("colormgr"): |
| 11047 |
# Check if profile already exists in database |
| 11048 |
try: |
| 11049 |
colord.get_object_path("icc-" + hexlify(profile.ID).decode(), "profile") |
| 11050 |
except colord.CDObjectQueryError: |
| 11051 |
# Profile not in database |
| 11052 |
pass |
| 11053 |
except colord.CDError as exception: |
| 11054 |
self.log(exception) |
| 11055 |
else: |
| 11056 |
# Profile already in database, nothing to do |
| 11057 |
return |
| 11058 |
# gcm-import will check if the profile is already in the database |
| 11059 |
# (based on profile ID), but will fail to overwrite a profile with the |
| 11060 |
# same name. We need to remove those profiles so gcm-import can work. |
| 11061 |
profilename = os.path.basename(profile.filename) |
| 11062 |
for dirname in defaultpaths.ICCPROFILES_HOME: |
| 11063 |
profile_install_path = os.path.join(dirname, profilename) |
| 11064 |
if ( |
| 11065 |
os.path.isfile(profile_install_path) |
| 11066 |
and profile_install_path != profile.filename |
| 11067 |
): |
| 11068 |
try: |
| 11069 |
send2trash([profile_install_path]) |
| 11070 |
except OSError as exc: |
| 11071 |
self.log(exc) |
| 11072 |
else: |
| 11073 |
# Give colord time to recognize that the profile was |
| 11074 |
# removed, otherwise gcm-import may complain if it's |
| 11075 |
# a profile that was already in the database |
| 11076 |
sleep(3) |
| 11077 |
if self._progress_wnd and not getattr(self._progress_wnd, "dlg", None): |
| 11078 |
self._progress_wnd.dlg = DummyDialog() |
| 11079 |
# Run gcm-import |
| 11080 |
cmd, args = which("gcm-import"), [profile.filename] |
| 11081 |
# gcm-import does not seem to return a useful exit code (it's always 1) |
| 11082 |
# or stderr output |
| 11083 |
self.exec_cmd(cmd, args, capture_output=True, skip_scripts=True) |
| 11084 |
|
| 11085 |
def _install_profile_oy( |
| 11086 |
self, |
| 11087 |
profile_path, |
| 11088 |
profile_name=None, |
| 11089 |
capture_output=False, |
| 11090 |
skip_scripts=False, |
| 11091 |
silent=False, |
| 11092 |
): |
| 11093 |
"""Install profile using oyranos-monitor. |
| 11094 |
|
| 11095 |
Args: |
| 11096 |
profile_path (str): Path to the profile file to install. |
| 11097 |
profile_name (str, optional): Name to use for the installed |
| 11098 |
profile. Defaults to None, in which case the basename of the |
| 11099 |
profile file is used. |
| 11100 |
capture_output (bool, optional): If True, captures the output of |
| 11101 |
the command. Defaults to False. |
| 11102 |
skip_scripts (bool, optional): If True, skips running scripts. |
| 11103 |
Defaults to False. |
| 11104 |
silent (bool, optional): If True, suppresses error messages. |
| 11105 |
|
| 11106 |
Returns: |
| 11107 |
bool or Error: True on success, Error on failure. |
| 11108 |
""" |
| 11109 |
display = self.displays[ |
| 11110 |
max(0, min(len(self.displays) - 1, getcfg("display.number") - 1)) |
| 11111 |
] |
| 11112 |
x, y = [pos.strip() for pos in display.split("@")[-1].split(",")[0:2]] |
| 11113 |
if getcfg("profile.install_scope") == "l": |
| 11114 |
# If system-wide install, copy profile to |
| 11115 |
# /var/lib/color/icc/devices/display |
| 11116 |
var_icc = "/var/lib/color/icc/devices/display" |
| 11117 |
if not profile_name: |
| 11118 |
profile_name = os.path.basename(profile_path) |
| 11119 |
profile_install_path = os.path.join(var_icc, profile_name) |
| 11120 |
result = self.exec_cmd( |
| 11121 |
"mkdir", |
| 11122 |
["-p", os.path.dirname(profile_install_path)], |
| 11123 |
capture_output=True, |
| 11124 |
low_contrast=False, |
| 11125 |
skip_scripts=True, |
| 11126 |
silent=True, |
| 11127 |
asroot=True, |
| 11128 |
) |
| 11129 |
if not isinstance(result, Exception) and result: |
| 11130 |
result = self.exec_cmd( |
| 11131 |
"cp", |
| 11132 |
["-f", profile_path, profile_install_path], |
| 11133 |
capture_output=True, |
| 11134 |
low_contrast=False, |
| 11135 |
skip_scripts=True, |
| 11136 |
silent=True, |
| 11137 |
asroot=True, |
| 11138 |
) |
| 11139 |
else: |
| 11140 |
result = True |
| 11141 |
dirname = None |
| 11142 |
for dirname in defaultpaths.ICCPROFILES_DISPLAY_HOME: |
| 11143 |
if os.path.isdir(dirname): |
| 11144 |
# Use the first one that exists |
| 11145 |
break |
| 11146 |
dirname = None |
| 11147 |
if not dirname: |
| 11148 |
# Create the first one in the list |
| 11149 |
dirname = defaultpaths.ICCPROFILES_DISPLAY_HOME[0] |
| 11150 |
try: |
| 11151 |
os.makedirs(dirname) |
| 11152 |
except Exception as exception: |
| 11153 |
self.log(exception) |
| 11154 |
result = False |
| 11155 |
if result is not False: |
| 11156 |
profile_install_path = os.path.join( |
| 11157 |
dirname, os.path.basename(profile_path) |
| 11158 |
) |
| 11159 |
try: |
| 11160 |
shutil.copyfile(profile_path, profile_install_path) |
| 11161 |
except Exception as exception: |
| 11162 |
self.log(exception) |
| 11163 |
result = False |
| 11164 |
if not isinstance(result, Exception) and result is not False: |
| 11165 |
cmd = which("oyranos-monitor") |
| 11166 |
args = ["-x", x, "-y", y, profile_install_path] |
| 11167 |
result = self.exec_cmd( |
| 11168 |
cmd, |
| 11169 |
args, |
| 11170 |
capture_output, |
| 11171 |
low_contrast=False, |
| 11172 |
skip_scripts=skip_scripts, |
| 11173 |
silent=silent, |
| 11174 |
working_dir=False, |
| 11175 |
) |
| 11176 |
# if getcfg("profile.install_scope") == "l": |
| 11177 |
# result = self.exec_cmd(cmd, args, |
| 11178 |
# capture_output, |
| 11179 |
# low_contrast=False, |
| 11180 |
# skip_scripts=skip_scripts, |
| 11181 |
# silent=silent, |
| 11182 |
# asroot=True, |
| 11183 |
# working_dir=False) |
| 11184 |
if not result and self.errors: |
| 11185 |
result = Error("".join(self.errors).strip()) |
| 11186 |
return result |
| 11187 |
|
| 11188 |
def _install_profile_loader_win32(self, silent=False): |
| 11189 |
"""Install profile loader. |
| 11190 |
|
| 11191 |
Args: |
| 11192 |
silent (bool): If True, suppresses error messages. |
| 11193 |
|
| 11194 |
Returns: |
| 11195 |
bool or Warning: True on success, Warning on error. |
| 11196 |
""" |
| 11197 |
if ( |
| 11198 |
sys.platform == "win32" |
| 11199 |
and sys.getwindowsversion() >= (6, 1) |
| 11200 |
and util_win.calibration_management_isenabled() |
| 11201 |
): |
| 11202 |
self._uninstall_profile_loader_win32() |
| 11203 |
return True |
| 11204 |
# Must return either True on success or an Exception object on error |
| 11205 |
result = True |
| 11206 |
# Remove outdated (pre-0.5.5.9) profile loaders |
| 11207 |
display_no = self.get_display() |
| 11208 |
name = f"{APPNAME} Calibration Loader (Display {display_no})" |
| 11209 |
if AUTOSTART_HOME: |
| 11210 |
loader_v01b = os.path.join(AUTOSTART_HOME, f"dispwin-d{display_no}-c-L.lnk") |
| 11211 |
if os.path.exists(loader_v01b): |
| 11212 |
try: |
| 11213 |
# delete v0.1b loader |
| 11214 |
os.remove(loader_v01b) |
| 11215 |
except Exception as exception: |
| 11216 |
self.log( |
| 11217 |
"Warning - could not remove old " |
| 11218 |
f"v0.1b calibration loader '{loader_v01b}': {exception}" |
| 11219 |
) |
| 11220 |
loader_v02b = os.path.join(AUTOSTART_HOME, f"{name}.lnk") |
| 11221 |
if os.path.exists(loader_v02b): |
| 11222 |
try: |
| 11223 |
# delete v02.b/v0.2.1b loader |
| 11224 |
os.remove(loader_v02b) |
| 11225 |
except Exception as exception: |
| 11226 |
self.log( |
| 11227 |
"Warning - could not remove old " |
| 11228 |
f"v0.2b calibration loader '{loader_v02b}': {exception}" |
| 11229 |
) |
| 11230 |
loader_v0558 = os.path.join(AUTOSTART_HOME, name + ".lnk") |
| 11231 |
if os.path.exists(loader_v0558): |
| 11232 |
try: |
| 11233 |
# delete v0.5.5.8 user loader |
| 11234 |
os.remove(loader_v0558) |
| 11235 |
except Exception as exception: |
| 11236 |
self.log( |
| 11237 |
"Warning - could not remove old " |
| 11238 |
f"v0.2b calibration loader '{loader_v02b}': {exception}" |
| 11239 |
) |
| 11240 |
if AUTOSTART: |
| 11241 |
loader_v0558 = os.path.join(AUTOSTART, f"{name}.lnk") |
| 11242 |
if os.path.exists(loader_v0558): |
| 11243 |
try: |
| 11244 |
# delete v0.5.5.8 system loader |
| 11245 |
os.remove(loader_v0558) |
| 11246 |
except Exception as exception: |
| 11247 |
self.log( |
| 11248 |
"Warning - could not remove old " |
| 11249 |
f"v0.2b calibration loader '{loader_v02b}': {exception}" |
| 11250 |
) |
| 11251 |
# Create unified loader |
| 11252 |
name = f"{APPNAME} Profile Loader" |
| 11253 |
if AUTOSTART: |
| 11254 |
autostart_lnkname = os.path.join(AUTOSTART, name + ".lnk") |
| 11255 |
if AUTOSTART_HOME: |
| 11256 |
autostart_home_lnkname = os.path.join(AUTOSTART_HOME, name + ".lnk") |
| 11257 |
loader_args = [] |
| 11258 |
if os.path.basename(EXE).lower() in ("python.exe", "pythonw.exe"): |
| 11259 |
cmd = os.path.join(EXEDIR, "pythonw.exe") |
| 11260 |
pyw = os.path.normpath( |
| 11261 |
os.path.join(PYDIR, "..", f"{APPNAME}-apply-profiles.pyw") |
| 11262 |
) |
| 11263 |
if os.path.exists(pyw): |
| 11264 |
# Running from source or 0install |
| 11265 |
# Check if this is a 0install implementation, in which |
| 11266 |
# case we want to call 0launch with the appropriate |
| 11267 |
# command |
| 11268 |
if re.match( |
| 11269 |
r"sha\d+(?:new)?", os.path.basename(os.path.dirname(PYDIR)) |
| 11270 |
): |
| 11271 |
cmd = which("0install-win.exe") or "0install-win.exe" |
| 11272 |
loader_args.extend( |
| 11273 |
[ |
| 11274 |
"run", |
| 11275 |
"--batch", |
| 11276 |
"--no-wait", |
| 11277 |
"--offline", |
| 11278 |
"--command=run-apply-profiles", |
| 11279 |
f"http://{DOMAIN}/0install/{APPNAME}.xml", |
| 11280 |
] |
| 11281 |
) |
| 11282 |
else: |
| 11283 |
# Running from source |
| 11284 |
loader_args.append(pyw) |
| 11285 |
else: |
| 11286 |
# Regular install |
| 11287 |
loader_args.append( |
| 11288 |
get_data_path(os.path.join("scripts", f"{APPNAME}-apply-profiles")) |
| 11289 |
) |
| 11290 |
else: |
| 11291 |
cmd = os.path.join(PYDIR, f"{APPNAME}-apply-profiles.exe") |
| 11292 |
|
| 11293 |
not_main_thread = current_thread() != main_thread() |
| 11294 |
if not_main_thread: |
| 11295 |
# If running in a thread, need to call pythoncom.CoInitialize |
| 11296 |
pythoncom.CoInitialize() |
| 11297 |
|
| 11298 |
from DisplayCAL import taskscheduler |
| 11299 |
|
| 11300 |
try: |
| 11301 |
ts = taskscheduler.TaskScheduler() |
| 11302 |
except Exception as exception: |
| 11303 |
print("Warning - could not access task scheduler:", exception) |
| 11304 |
ts = None |
| 11305 |
task = None |
| 11306 |
else: |
| 11307 |
task = ts.query_task(f"{APPNAME} Profile Loader Launcher") |
| 11308 |
|
| 11309 |
elevate = getcfg( |
| 11310 |
"profile.install_scope" |
| 11311 |
) == "l" and sys.getwindowsversion() >= (6,) |
| 11312 |
|
| 11313 |
loader_lockfile = os.path.join( |
| 11314 |
config.CONFIG_HOME, APPBASENAME + "-apply-profiles.lock" |
| 11315 |
) |
| 11316 |
loader_running = os.path.isfile(loader_lockfile) |
| 11317 |
|
| 11318 |
if not loader_running or (not task and elevate): |
| 11319 |
# Launch profile loader if not yet running, or restart if no task |
| 11320 |
# and going to elevate (launching profile loader with elevated |
| 11321 |
# privileges will try to create scheduled task so we can run |
| 11322 |
# elevated at login without UAC prompt) |
| 11323 |
errmsg = "Warning - could not launch profile loader" |
| 11324 |
if elevate: |
| 11325 |
errmsg += " with elevated privileges" |
| 11326 |
try: |
| 11327 |
shell_exec( |
| 11328 |
cmd, |
| 11329 |
[*loader_args, "--skip"], |
| 11330 |
operation="runas" if elevate else "open", |
| 11331 |
wait_for_idle=True, |
| 11332 |
) |
| 11333 |
except pywintypes.error as exception: |
| 11334 |
if exception.args[0] == winerror.ERROR_CANCELLED: |
| 11335 |
errmsg += " (user cancelled)" |
| 11336 |
else: |
| 11337 |
errmsg += " " + safe_str(exception) |
| 11338 |
print(errmsg) |
| 11339 |
|
| 11340 |
if task or (ts and ts.query_task(f"{APPNAME} Profile Loader Launcher")): |
| 11341 |
if not_main_thread: |
| 11342 |
pythoncom.CoUninitialize() |
| 11343 |
return True |
| 11344 |
|
| 11345 |
try: |
| 11346 |
scut = pythoncom.CoCreateInstance( |
| 11347 |
win32com_shell.CLSID_ShellLink, |
| 11348 |
None, |
| 11349 |
pythoncom.CLSCTX_INPROC_SERVER, |
| 11350 |
win32com_shell.IID_IShellLink, |
| 11351 |
) |
| 11352 |
scut.SetPath(cmd) |
| 11353 |
if len(loader_args) == 1: |
| 11354 |
scut.SetWorkingDirectory(PYDIR) |
| 11355 |
if os.path.basename(cmd) == f"{APPNAME}-apply-profiles.exe": |
| 11356 |
scut.SetIconLocation(cmd, 0) |
| 11357 |
else: |
| 11358 |
scut.SetIconLocation( |
| 11359 |
get_data_path( |
| 11360 |
os.path.join("theme", "icons", f"{APPNAME}-apply-profiles.ico") |
| 11361 |
), |
| 11362 |
0, |
| 11363 |
) |
| 11364 |
scut.SetArguments(sp.list2cmdline(loader_args)) |
| 11365 |
scut.SetShowCmd(win32con.SW_SHOWDEFAULT) |
| 11366 |
if is_superuser(): |
| 11367 |
if AUTOSTART: |
| 11368 |
try: |
| 11369 |
scut.QueryInterface(pythoncom.IID_IPersistFile).Save( |
| 11370 |
autostart_lnkname, 0 |
| 11371 |
) |
| 11372 |
except Exception as exception: |
| 11373 |
if not silent: |
| 11374 |
result = Warning( |
| 11375 |
lang.getstr("error.autostart_creation", AUTOSTART) |
| 11376 |
+ "\n" |
| 11377 |
+ str(exception) |
| 11378 |
) |
| 11379 |
# Now try user scope |
| 11380 |
elif not silent: |
| 11381 |
result = Warning(lang.getstr("error.autostart_system")) |
| 11382 |
if AUTOSTART_HOME: |
| 11383 |
if AUTOSTART and os.path.isfile(autostart_lnkname): |
| 11384 |
# Remove existing user loader |
| 11385 |
if os.path.isfile(autostart_home_lnkname): |
| 11386 |
os.remove(autostart_home_lnkname) |
| 11387 |
else: |
| 11388 |
# Only create user loader if no system loader |
| 11389 |
try: |
| 11390 |
scut.QueryInterface(pythoncom.IID_IPersistFile).Save( |
| 11391 |
autostart_home_lnkname, 0 |
| 11392 |
) |
| 11393 |
except Exception as exception: |
| 11394 |
if not silent: |
| 11395 |
result = Warning( |
| 11396 |
lang.getstr("error.autostart_creation", AUTOSTART_HOME) |
| 11397 |
+ "\n" |
| 11398 |
+ str(exception) |
| 11399 |
) |
| 11400 |
elif not silent: |
| 11401 |
result = Warning(lang.getstr("error.autostart_user")) |
| 11402 |
except Exception as exception: |
| 11403 |
if not silent: |
| 11404 |
result = Warning( |
| 11405 |
lang.getstr("error.autostart_creation", AUTOSTART_HOME) |
| 11406 |
+ "\n" |
| 11407 |
+ str(exception) |
| 11408 |
) |
| 11409 |
finally: |
| 11410 |
if not_main_thread: |
| 11411 |
# If running in a thread, need to call pythoncom.CoUninitialize |
| 11412 |
pythoncom.CoUninitialize() |
| 11413 |
return result |
| 11414 |
|
| 11415 |
def _uninstall_profile_loader_win32(self): |
| 11416 |
"""Uninstall profile loader. |
| 11417 |
|
| 11418 |
Returns: |
| 11419 |
bool: True if the uninstallation was successful, False otherwise. |
| 11420 |
""" |
| 11421 |
name = f"{APPNAME} Profile Loader" |
| 11422 |
if AUTOSTART and is_superuser(): |
| 11423 |
autostart_lnkname = os.path.join(AUTOSTART, name + ".lnk") |
| 11424 |
if os.path.exists(autostart_lnkname): |
| 11425 |
try: |
| 11426 |
os.remove(autostart_lnkname) |
| 11427 |
except Exception as exception: |
| 11428 |
self.log(autostart_lnkname, exception) |
| 11429 |
if AUTOSTART_HOME: |
| 11430 |
autostart_home_lnkname = os.path.join(AUTOSTART_HOME, name + ".lnk") |
| 11431 |
if os.path.exists(autostart_home_lnkname): |
| 11432 |
try: |
| 11433 |
os.remove(autostart_home_lnkname) |
| 11434 |
except Exception as exception: |
| 11435 |
self.log(autostart_home_lnkname, exception) |
| 11436 |
return True |
| 11437 |
|
| 11438 |
def _install_profile_loader_xdg(self, silent=False): |
| 11439 |
"""Install profile loader. |
| 11440 |
|
| 11441 |
Args: |
| 11442 |
silent (bool): If True, suppresses error messages. |
| 11443 |
|
| 11444 |
Returns: |
| 11445 |
bool or Warning: True on success, Warning on error. |
| 11446 |
""" |
| 11447 |
# See http://standards.freedesktop.org/autostart-spec |
| 11448 |
# Must return either True on success or an Exception object on error |
| 11449 |
result = True |
| 11450 |
# Remove wrong-cased entry potentially created by DisplayCAL < 3.1.6 |
| 11451 |
name = f"z-{APPNAME}-apply-profiles" |
| 11452 |
desktop_file_path = os.path.join(AUTOSTART_HOME, f"{name}.desktop") |
| 11453 |
if os.path.exists(desktop_file_path): |
| 11454 |
try: |
| 11455 |
os.remove(desktop_file_path) |
| 11456 |
except Exception: |
| 11457 |
result = Warning( |
| 11458 |
lang.getstr("error.autostart_remove_old", desktop_file_path) |
| 11459 |
) |
| 11460 |
# Create unified loader |
| 11461 |
# Prepend 'z' so our loader hopefully loads after |
| 11462 |
# possible nvidia-settings entry (which resets gamma table) |
| 11463 |
name = f"z-{APPNAME.lower()}-apply-profiles" |
| 11464 |
desktop_file_path = os.path.join(AUTOSTART_HOME, f"{name}.desktop") |
| 11465 |
system_desktop_file_path = os.path.join(AUTOSTART, f"{name}.desktop") |
| 11466 |
try: |
| 11467 |
# Create user loader, even if we later try to |
| 11468 |
# move it to the system-wide location so that at least |
| 11469 |
# the user loader is present if the move to the system |
| 11470 |
# dir fails |
| 11471 |
if not os.path.exists(AUTOSTART_HOME): |
| 11472 |
os.makedirs(AUTOSTART_HOME) |
| 11473 |
|
| 11474 |
desktop_file_buffer = [] |
| 11475 |
desktop_file_buffer.append("[Desktop Entry]") |
| 11476 |
desktop_file_buffer.append("Version=1.0") |
| 11477 |
desktop_file_buffer.append("Encoding=UTF-8") |
| 11478 |
desktop_file_buffer.append("Type=Application") |
| 11479 |
desktop_file_buffer.append(f"Name={APPNAME} ICC Profile Loader") |
| 11480 |
desktop_file_buffer.append( |
| 11481 |
"Comment={}".format( |
| 11482 |
lang.getstr("calibrationloader.description", lcode="en") |
| 11483 |
) |
| 11484 |
) |
| 11485 |
if lang.getcode() != "en": |
| 11486 |
desktop_file_buffer.append( |
| 11487 |
"Comment[{}]={}".format( |
| 11488 |
lang.getcode(), |
| 11489 |
lang.getstr("calibrationloader.description"), |
| 11490 |
) |
| 11491 |
) |
| 11492 |
pyw = os.path.normpath( |
| 11493 |
os.path.join(PYDIR, "..", f"{APPNAME}-apply-profiles.pyw") |
| 11494 |
) |
| 11495 |
icon = f"{APPNAME.lower()}-apply-profiles" |
| 11496 |
if os.path.exists(pyw): |
| 11497 |
# Running from source, or 0install/installer install |
| 11498 |
# Check if this is a 0install implementation, in which |
| 11499 |
# case we want to call 0launch with the appropriate |
| 11500 |
# command |
| 11501 |
if re.match( |
| 11502 |
r"sha\d+(?:new)?", os.path.basename(os.path.dirname(PYDIR)) |
| 11503 |
): |
| 11504 |
executable = ( |
| 11505 |
"0launch --console --offline " |
| 11506 |
"--command=run-apply-profiles " |
| 11507 |
f"http://{DOMAIN}/0install/{APPNAME}.xml" |
| 11508 |
) |
| 11509 |
else: |
| 11510 |
icon = os.path.join( |
| 11511 |
PYDIR, |
| 11512 |
"theme", |
| 11513 |
"icons", |
| 11514 |
"256x256", |
| 11515 |
f"{APPNAME.lower()}-apply-profiles.png", |
| 11516 |
) |
| 11517 |
executable = pyw |
| 11518 |
else: |
| 11519 |
# Regular install |
| 11520 |
executable = f"{APPNAME.lower()}-apply-profiles" |
| 11521 |
desktop_file_buffer.append(f"Icon={icon}") |
| 11522 |
desktop_file_buffer.append(f"Exec={executable}") |
| 11523 |
desktop_file_buffer.append("Terminal=false") |
| 11524 |
with open(desktop_file_path, "w") as desktop_file: |
| 11525 |
desktop_file.write("\n".join(desktop_file_buffer)) |
| 11526 |
except Exception as exception: |
| 11527 |
if not silent: |
| 11528 |
result = Warning( |
| 11529 |
lang.getstr("error.autostart_creation", desktop_file_path) |
| 11530 |
+ "\n" |
| 11531 |
+ str(exception) |
| 11532 |
) |
| 11533 |
else: |
| 11534 |
if ( |
| 11535 |
getcfg("profile.install_scope") == "l" |
| 11536 |
and AUTOSTART |
| 11537 |
and ( |
| 11538 |
# Move system-wide loader |
| 11539 |
self.exec_cmd( |
| 11540 |
"mkdir", |
| 11541 |
["-p", AUTOSTART], |
| 11542 |
capture_output=True, |
| 11543 |
low_contrast=False, |
| 11544 |
skip_scripts=True, |
| 11545 |
silent=True, |
| 11546 |
asroot=True, |
| 11547 |
) |
| 11548 |
is not True |
| 11549 |
or self.exec_cmd( |
| 11550 |
"mv", |
| 11551 |
["-f", desktop_file_path, system_desktop_file_path], |
| 11552 |
capture_output=True, |
| 11553 |
low_contrast=False, |
| 11554 |
skip_scripts=True, |
| 11555 |
silent=True, |
| 11556 |
asroot=True, |
| 11557 |
) |
| 11558 |
is not True |
| 11559 |
) |
| 11560 |
and not silent |
| 11561 |
): |
| 11562 |
result = Warning( |
| 11563 |
lang.getstr("error.autostart_creation", system_desktop_file_path) |
| 11564 |
) |
| 11565 |
return result |
| 11566 |
|
| 11567 |
def instrument_supports_ccss(self, instrument_name=None): |
| 11568 |
"""Return whether instrument supports CCSS files or not. |
| 11569 |
|
| 11570 |
Args: |
| 11571 |
instrument_name (str): Optional name of the instrument to check. |
| 11572 |
|
| 11573 |
Returns: |
| 11574 |
bool: True if the instrument supports CCSS, False otherwise. |
| 11575 |
""" |
| 11576 |
if not instrument_name: |
| 11577 |
instrument_name = self.get_instrument_name() |
| 11578 |
return self.get_instrument_features(instrument_name).get("spectral_cal") |
| 11579 |
|
| 11580 |
def create_ccxx(self, args=None, working_dir=None): |
| 11581 |
"""Create CCMX or CCSS. |
| 11582 |
|
| 11583 |
Args: |
| 11584 |
args (list): Additional arguments to pass to `ccxxmake`. |
| 11585 |
working_dir (str): Directory to run the command in. |
| 11586 |
|
| 11587 |
Returns: |
| 11588 |
subprocess.CompletedProcess: The result of the command execution. |
| 11589 |
""" |
| 11590 |
if not args: |
| 11591 |
args = [] |
| 11592 |
cmd = get_argyll_util("ccxxmake") |
| 11593 |
if "-I" not in args: |
| 11594 |
# Display manufacturer & name |
| 11595 |
name = self.get_display_name(True) |
| 11596 |
if name: |
| 11597 |
args.insert(0, "-I") |
| 11598 |
args.insert(1, name) |
| 11599 |
elif "-T" not in args: |
| 11600 |
# Display technology |
| 11601 |
args.insert(0, "-T") |
| 11602 |
displaytech = ["LCD" if getcfg("measurement_mode") == "l" else "CRT"] |
| 11603 |
if self.get_instrument_features().get("projector_mode") and getcfg( |
| 11604 |
"measurement_mode.projector" |
| 11605 |
): |
| 11606 |
displaytech.append("Projector") |
| 11607 |
args.insert(1, " ".join(displaytech)) |
| 11608 |
if not getcfg("ccmx.use_four_color_matrix_method"): |
| 11609 |
args.insert(0, "-v") |
| 11610 |
return self.exec_cmd( |
| 11611 |
cmd, |
| 11612 |
args, |
| 11613 |
capture_output=True, |
| 11614 |
skip_scripts=True, |
| 11615 |
silent=False, |
| 11616 |
working_dir=working_dir, |
| 11617 |
) |
| 11618 |
|
| 11619 |
def create_gamut_views( |
| 11620 |
self, profile_path: str |
| 11621 |
) -> tuple[None, None] | tuple[float, dict]: |
| 11622 |
"""Generate gamut views (VRML files). |
| 11623 |
|
| 11624 |
Also show progress in current progress dialog. |
| 11625 |
|
| 11626 |
Args: |
| 11627 |
profile_path (str): Path to the ICC profile for which to create |
| 11628 |
gamut views. |
| 11629 |
|
| 11630 |
Returns: |
| 11631 |
tuple[None, None] | tuple[float, dict]: A tuple containing the |
| 11632 |
gamut_volume and gamut_coverage or (None, None) if gamut view |
| 11633 |
creation is disabled. |
| 11634 |
""" |
| 11635 |
if getcfg("profile.create_gamut_views"): |
| 11636 |
self.log("-" * 80) |
| 11637 |
self.log(lang.getstr("gamut.view.create")) |
| 11638 |
self.lastmsg.clear() |
| 11639 |
self.recent.clear() |
| 11640 |
self.recent.write(lang.getstr("gamut.view.create")) |
| 11641 |
sleep(0.75) # Allow time for progress window to update |
| 11642 |
return self.calculate_gamut(profile_path) |
| 11643 |
return None, None |
| 11644 |
|
| 11645 |
def create_profile( |
| 11646 |
self, |
| 11647 |
dst_path=None, |
| 11648 |
skip_scripts=False, |
| 11649 |
display_name=None, |
| 11650 |
display_manufacturer=None, |
| 11651 |
tags=None, |
| 11652 |
): |
| 11653 |
"""Create an ICC profile and process the generated file. |
| 11654 |
|
| 11655 |
Args: |
| 11656 |
dst_path (str): Path to save the profile to. If None, uses the |
| 11657 |
default save path and profile name. |
| 11658 |
skip_scripts (bool): If True, skips running scripts after profile |
| 11659 |
creation. |
| 11660 |
display_name (str): Optional display name for the profile. |
| 11661 |
display_manufacturer (str): Optional manufacturer name for the |
| 11662 |
display. |
| 11663 |
tags (list): Optional list of tags to apply to the profile. |
| 11664 |
|
| 11665 |
Returns: |
| 11666 |
str or Exception: The path to the created profile on success, or an |
| 11667 |
Exception object on error. |
| 11668 |
""" |
| 11669 |
print(lang.getstr("create_profile")) |
| 11670 |
if dst_path is None: |
| 11671 |
dst_path = os.path.join( |
| 11672 |
getcfg("profile.save_path"), |
| 11673 |
getcfg("profile.name.expanded"), |
| 11674 |
getcfg("profile.name.expanded") + PROFILE_EXT, |
| 11675 |
) |
| 11676 |
cmd, args = self.prepare_colprof( |
| 11677 |
os.path.basename(os.path.splitext(dst_path)[0]), |
| 11678 |
display_name, |
| 11679 |
display_manufacturer, |
| 11680 |
tags, |
| 11681 |
) |
| 11682 |
if isinstance(cmd, Exception): |
| 11683 |
result = cmd |
| 11684 |
else: |
| 11685 |
result = True |
| 11686 |
profile = None |
| 11687 |
profile_path = args[-1] + PROFILE_EXT |
| 11688 |
if "-aX" in args: |
| 11689 |
# If profile type is X (XYZ cLUT + matrix), only create the |
| 11690 |
# cLUT, then add the matrix tags later from a forward lookup of |
| 11691 |
# a smaller testchart (faster computation!) |
| 11692 |
args.insert(args.index("-aX"), "-ax") |
| 11693 |
args.remove("-aX") |
| 11694 |
check_for_ti1_match = False |
| 11695 |
is_regular_grid = False |
| 11696 |
is_primaries_only = False |
| 11697 |
ti3 = CGATS(args[-1] + ".ti3") |
| 11698 |
XYZbp = None |
| 11699 |
try: |
| 11700 |
( |
| 11701 |
ti3_extracted, |
| 11702 |
ti3_RGB_XYZ, |
| 11703 |
ti3_remaining, |
| 11704 |
) = extract_device_gray_primaries(ti3, logfn=self.log) |
| 11705 |
except Error as exception: |
| 11706 |
self.log(exception) |
| 11707 |
else: |
| 11708 |
if getcfg("profile.type") in ("X", "x", "S", "s"): |
| 11709 |
# Check if TI3 RGB matches one of our regular grid or |
| 11710 |
# primaries + gray charts |
| 11711 |
check_for_ti1_match = True |
| 11712 |
if ti3_RGB_XYZ[(0, 0, 0)] != (0, 0, 0): |
| 11713 |
# Note: Setting black chroma to zero fixes smoothness |
| 11714 |
# issues on devices with not very neutral black. |
| 11715 |
bpcorr = getcfg("profile.black_point_correction") |
| 11716 |
if False: # getcfg("profile.black_point_compensation"): |
| 11717 |
XYZbp = (0, 0, 0) |
| 11718 |
Labbp = (0, 0, 0) |
| 11719 |
else: |
| 11720 |
# Correct black point a* b* and make neutral hues near |
| 11721 |
# black blend over to the new blackpoint. The correction |
| 11722 |
# factor determines the amount of the measured black hue |
| 11723 |
# that should be retained. |
| 11724 |
# It makes the profile slightly less accurate near |
| 11725 |
# black, but the effect is negligible and the visual |
| 11726 |
# benefit is of greater importance (allows for |
| 11727 |
# calibration blackpoint hue correction to have desired |
| 11728 |
# effect, and makes relcol with BPC visually match |
| 11729 |
# perceptual in Photoshop). |
| 11730 |
XYZwp = ti3_RGB_XYZ[(100, 100, 100)] |
| 11731 |
Labbp = colormath.XYZ2Lab( |
| 11732 |
*ti3_RGB_XYZ[(0, 0, 0)], whitepoint=XYZwp |
| 11733 |
) |
| 11734 |
Labbp = (Labbp[0], Labbp[1] * bpcorr, Labbp[2] * bpcorr) |
| 11735 |
XYZbp = colormath.Lab2XYZ( |
| 11736 |
*Labbp, whitepoint=[v / XYZwp[1] for v in XYZwp] |
| 11737 |
) |
| 11738 |
if XYZbp and bpcorr < 1: |
| 11739 |
ti3.write(args[-1] + ".ti3.backup") |
| 11740 |
if False: # getcfg("profile.black_point_compensation"): |
| 11741 |
logmsg = "Applying black point compensation" |
| 11742 |
else: |
| 11743 |
logmsg = f"Applying {bpcorr:0.0%} black point correction" |
| 11744 |
self.log(f"{logmsg} to TI3") |
| 11745 |
ti3[0].apply_bpc(XYZbp) |
| 11746 |
ti3.write() |
| 11747 |
if check_for_ti1_match: |
| 11748 |
for ti1_name in ( |
| 11749 |
"ti1/d3-e4-s2-g28-m0-b0-f0", # Primaries + gray |
| 11750 |
"ti1/d3-e4-s3-g52-m3-b0-f0", # 3^3 grid |
| 11751 |
"ti1/d3-e4-s4-g52-m4-b0-f0", # 4^3 grid |
| 11752 |
"ti1/d3-e4-s5-g52-m5-b0-f0", # 5^3 grid |
| 11753 |
"ti1/d3-e4-s9-g52-m9-b0-f0", # 9^3 grid |
| 11754 |
"ti1/d3-e4-s17-g52-m17-b0-f0", |
| 11755 |
): # 17^3 grid |
| 11756 |
ti1_filename = f"{ti1_name}.ti1" |
| 11757 |
ti1_path = get_data_path(ti1_filename) |
| 11758 |
if not ti1_path: |
| 11759 |
if ti1_name in ( |
| 11760 |
"ti1/d3-e4-s2-g28-m0-b0-f0", |
| 11761 |
"ti1/d3-e4-s3-g52-m3-b0-f0", |
| 11762 |
"ti1/d3-e4-s4-g52-m4-b0-f0", |
| 11763 |
"ti1/d3-e4-s5-g52-m5-b0-f0", |
| 11764 |
): |
| 11765 |
return Error(lang.getstr("file.missing", ti1_filename)) |
| 11766 |
continue |
| 11767 |
ti1 = CGATS(ti1_path) |
| 11768 |
( |
| 11769 |
ti1_extracted, |
| 11770 |
ti1_RGB_XYZ, |
| 11771 |
ti1_remaining, |
| 11772 |
) = extract_device_gray_primaries(ti1) |
| 11773 |
# Quantize to 8 bit for comparison |
| 11774 |
# XXX Note that round(50 * 2.55) = 127, but |
| 11775 |
# round(50 / 100 * 255) = 128 (the latter is what we want)! |
| 11776 |
if sorted( |
| 11777 |
tuple(round(v / 100.0 * 255) for v in RGB) |
| 11778 |
for RGB in list(ti3_remaining.keys()) |
| 11779 |
) == sorted( |
| 11780 |
tuple(round(v / 100.0 * 255) for v in RGB) |
| 11781 |
for RGB in list(ti1_remaining.keys()) |
| 11782 |
): |
| 11783 |
if ti1_name == "ti1/d3-e4-s2-g28-m0-b0-f0": |
| 11784 |
is_primaries_only = True |
| 11785 |
if getcfg("profile.type") not in ("S", "s"): |
| 11786 |
options_dispcal = get_options_from_ti3(ti3)[0] |
| 11787 |
setcfg( |
| 11788 |
"profile.type", |
| 11789 |
"S" if get_arg("q", options_dispcal) else "s", |
| 11790 |
) |
| 11791 |
elif getcfg("profile.type") in ("X", "x"): |
| 11792 |
is_regular_grid = True |
| 11793 |
break |
| 11794 |
if not display_name: |
| 11795 |
arg = get_arg("-M", args, True) |
| 11796 |
if arg and len(args) - 1 > arg[0]: |
| 11797 |
display_name = args[arg[0] + 1] |
| 11798 |
if not display_manufacturer: |
| 11799 |
arg = get_arg("-A", args, True) |
| 11800 |
if arg and len(args) - 1 > arg[0]: |
| 11801 |
display_manufacturer = args[arg[0] + 1] |
| 11802 |
if is_regular_grid: |
| 11803 |
# Use our own forward profile code |
| 11804 |
profile = self.create_RGB_XYZ_cLUT_fwd_profile( |
| 11805 |
ti3, |
| 11806 |
os.path.basename(args[-1]), |
| 11807 |
getcfg("copyright"), |
| 11808 |
display_manufacturer, |
| 11809 |
display_name, |
| 11810 |
self.log, |
| 11811 |
) |
| 11812 |
if getcfg("profile.type") == "x" and ( |
| 11813 |
self.argyll_version < [2, 1, 0] or "-aY" in args |
| 11814 |
): |
| 11815 |
# Swapped matrix - need to create it ourselves |
| 11816 |
# Start with sRGB |
| 11817 |
sRGB = profile.from_named_rgb_space("sRGB") |
| 11818 |
for channel in "rgb": |
| 11819 |
tagname = channel + "TRC" |
| 11820 |
profile.tags[tagname] = sRGB.tags[tagname] |
| 11821 |
# Swap RGB -> BRG |
| 11822 |
profile.tags.rXYZ = sRGB.tags.bXYZ |
| 11823 |
profile.tags.gXYZ = sRGB.tags.rXYZ |
| 11824 |
profile.tags.bXYZ = sRGB.tags.gXYZ |
| 11825 |
elif not is_primaries_only: |
| 11826 |
# Use colprof to create profile |
| 11827 |
result = self.exec_cmd( |
| 11828 |
cmd, args, low_contrast=False, skip_scripts=skip_scripts |
| 11829 |
) |
| 11830 |
if not isinstance(result, Exception) and result: |
| 11831 |
try: |
| 11832 |
profile = ICCProfile(profile_path) |
| 11833 |
except (OSError, ICCProfileInvalidError): |
| 11834 |
result = Error( |
| 11835 |
lang.getstr("profile.invalid") + "\n" + profile_path |
| 11836 |
) |
| 11837 |
if not isinstance(result, Exception) and result: |
| 11838 |
if getcfg("profile.type") == "X" or is_primaries_only: |
| 11839 |
# Use our own accurate matrix |
| 11840 |
cat = "Bradford" |
| 11841 |
if not is_primaries_only: |
| 11842 |
cat = profile.guess_cat() or cat |
| 11843 |
mtx = self._create_simple_matrix_profile( |
| 11844 |
ti3_RGB_XYZ, |
| 11845 |
ti3_remaining, |
| 11846 |
os.path.basename(args[-1]), |
| 11847 |
getcfg("copyright"), |
| 11848 |
display_manufacturer, |
| 11849 |
display_name, |
| 11850 |
( |
| 11851 |
getcfg("profile.type") in ("X", "x") |
| 11852 |
and getcfg("profile.b2a.hires") |
| 11853 |
) |
| 11854 |
or getcfg("profile.black_point_compensation"), |
| 11855 |
cat, |
| 11856 |
) |
| 11857 |
if is_primaries_only: |
| 11858 |
# Use matrix profile |
| 11859 |
profile = mtx |
| 11860 |
|
| 11861 |
# Add luminance tag |
| 11862 |
luminance_XYZ_cdm2 = ti3.queryv1("LUMINANCE_XYZ_CDM2") |
| 11863 |
if luminance_XYZ_cdm2: |
| 11864 |
profile.tags.lumi = XYZType(profile=profile) |
| 11865 |
profile.tags.lumi.Y = float(luminance_XYZ_cdm2.split()[1]) |
| 11866 |
|
| 11867 |
# Add blackpoint tag |
| 11868 |
profile.tags.bkpt = XYZType(profile=profile) |
| 11869 |
black_XYZ = XYZbp if XYZbp else (0, 0, 0) |
| 11870 |
( |
| 11871 |
profile.tags.bkpt.X, |
| 11872 |
profile.tags.bkpt.Y, |
| 11873 |
profile.tags.bkpt.Z, |
| 11874 |
) = black_XYZ |
| 11875 |
|
| 11876 |
# Check if we have calibration, if so, add vcgt |
| 11877 |
for cgats in ti3.values(): |
| 11878 |
if cgats.type == b"CAL": |
| 11879 |
profile.tags.vcgt = cal_to_vcgt(cgats) |
| 11880 |
else: |
| 11881 |
# Add matrix tags to cLUT profile |
| 11882 |
for tagcls in ("XYZ", "TRC"): |
| 11883 |
for channel in "rgb": |
| 11884 |
tagname = channel + tagcls |
| 11885 |
profile.tags[tagname] = mtx.tags[tagname] |
| 11886 |
if is_regular_grid or is_primaries_only: |
| 11887 |
# Write profile |
| 11888 |
profile.write(profile_path) |
| 11889 |
if os.path.isfile(args[-1] + ".chrm"): |
| 11890 |
# Get ChromaticityType tag |
| 11891 |
with open(args[-1] + ".chrm", "rb") as blob: |
| 11892 |
chrm = ChromaticityType(blob.read()) |
| 11893 |
else: |
| 11894 |
chrm = None |
| 11895 |
|
| 11896 |
if XYZbp: |
| 11897 |
Ybp = XYZbp[1] |
| 11898 |
XYZbp = colormath.adapt( |
| 11899 |
*XYZbp, |
| 11900 |
whitepoint_source=[v / XYZwp[1] for v in XYZwp], |
| 11901 |
cat=profile.guess_cat() or "Bradford", |
| 11902 |
) |
| 11903 |
XYZbp = tuple(XYZbp) |
| 11904 |
|
| 11905 |
bpc_applied = False |
| 11906 |
profchanged = False |
| 11907 |
if not isinstance(result, Exception) and result: |
| 11908 |
errors = self.errors |
| 11909 |
output = self.output |
| 11910 |
retcode = self.retcode |
| 11911 |
try: |
| 11912 |
if not profile: |
| 11913 |
profile = ICCProfile(profile_path) |
| 11914 |
except (OSError, ICCProfileInvalidError): |
| 11915 |
result = Error(lang.getstr("profile.invalid") + "\n" + profile_path) |
| 11916 |
else: |
| 11917 |
# Do we have a B2A0 table? |
| 11918 |
has_B2A = "B2A0" in profile.tags |
| 11919 |
# Hires CIECAM02 gamut mapping - perceptual and saturation |
| 11920 |
# tables, also colorimetric table for non-RGB profiles |
| 11921 |
# Use collink for smoother result. |
| 11922 |
# Only for XYZ LUT and if source profile is a simple matrix |
| 11923 |
# profile, otherwise CIECAM02 tables will already have been |
| 11924 |
# created by colprof |
| 11925 |
gamap = ( |
| 11926 |
getcfg("gamap_perceptual") or getcfg("gamap_saturation") |
| 11927 |
) and getcfg("gamap_profile") |
| 11928 |
collink = None |
| 11929 |
if ( |
| 11930 |
"A2B0" in profile.tags |
| 11931 |
and profile.connectionColorSpace == b"XYZ" |
| 11932 |
and (gamap or profile.colorSpace != b"RGB") |
| 11933 |
and getcfg("profile.b2a.hires") |
| 11934 |
): |
| 11935 |
collink = get_argyll_util("collink") |
| 11936 |
if not collink: |
| 11937 |
self.log(lang.getstr("argyll.util.not_found", "collink")) |
| 11938 |
gamap_profiles = [] |
| 11939 |
gamap_profile = None |
| 11940 |
if gamap and collink: |
| 11941 |
gamap_profile_filename = getcfg("gamap_profile") |
| 11942 |
try: |
| 11943 |
gamap_profile = ICCProfile(gamap_profile_filename) |
| 11944 |
except (OSError, ICCProfileInvalidError) as exception: |
| 11945 |
self.log(exception) |
| 11946 |
else: |
| 11947 |
if ( |
| 11948 |
"A2B0" not in gamap_profile.tags |
| 11949 |
and "rXYZ" in gamap_profile.tags |
| 11950 |
and "gXYZ" in gamap_profile.tags |
| 11951 |
and "bXYZ" in gamap_profile.tags |
| 11952 |
and "rTRC" in gamap_profile.tags |
| 11953 |
and "gTRC" in gamap_profile.tags |
| 11954 |
and "bTRC" in gamap_profile.tags |
| 11955 |
): |
| 11956 |
# Simple matrix source profile |
| 11957 |
if gamap_profile.convert_iccv4_tags_to_iccv2(): |
| 11958 |
# Write to temp file |
| 11959 |
fd, gamap_profile.filename = mkstemp_bypath( |
| 11960 |
gamap_profile_filename, dirname=self.tempdir |
| 11961 |
) |
| 11962 |
stream = os.fdopen(fd, "wb") |
| 11963 |
gamap_profile.write(stream) |
| 11964 |
stream.close() |
| 11965 |
gamap_profiles.append(gamap_profile) |
| 11966 |
if profile.colorSpace == b"RGB" and has_B2A: |
| 11967 |
# Only table 0 (colorimetric) in display profile. |
| 11968 |
# Assign it to table 1 as per ICC spec to prepare |
| 11969 |
# for adding table 0 (perceptual) and 2 (saturation) |
| 11970 |
profile.tags.B2A1 = profile.tags.B2A0 |
| 11971 |
else: |
| 11972 |
gamap_profile = None |
| 11973 |
tables = [] |
| 11974 |
if gamap_profile or (collink and profile.colorSpace != b"RGB"): |
| 11975 |
self.log("-" * 80) |
| 11976 |
self.log("Creating CIECAM02 gamut mapping using collink") |
| 11977 |
size = getcfg("profile.b2a.hires.size") |
| 11978 |
# Make sure to map 'auto' value (-1) to an actual size |
| 11979 |
size = {-1: 33}.get(size, size) |
| 11980 |
collink_args = [ |
| 11981 |
"-v", |
| 11982 |
"-q" + getcfg("profile.quality"), |
| 11983 |
"-G", |
| 11984 |
f"-r{size:d}", |
| 11985 |
] |
| 11986 |
if is_regular_grid: |
| 11987 |
# Do not preserve output shaper curves in devicelink |
| 11988 |
collink_args.append("-no") |
| 11989 |
if profile.colorSpace == b"RGB" and self.argyll_version >= [1, 7]: |
| 11990 |
# Use RGB->RGB forced black point hack |
| 11991 |
collink_args.append("-b") |
| 11992 |
if gamap_profile: |
| 11993 |
for tableno, cfgname in [ |
| 11994 |
(0, "gamap_perceptual"), |
| 11995 |
(2, "gamap_saturation"), |
| 11996 |
]: |
| 11997 |
if getcfg(cfgname): |
| 11998 |
tables.append((tableno, getcfg(cfgname + "_intent"))) |
| 11999 |
if profile.colorSpace != b"RGB": |
| 12000 |
# Create colorimetric table for non-RGB profile |
| 12001 |
tables.insert(0, (1, "r")) |
| 12002 |
if not gamap_profile: |
| 12003 |
# Create perceptual table with |
| 12004 |
# luminance matched appearance rendering |
| 12005 |
# (similar to rel. col. + BPC) |
| 12006 |
tables.append((0, "la")) |
| 12007 |
# Get inking rules from colprof extra args |
| 12008 |
extra_args = getcfg("extra_args.colprof") |
| 12009 |
inking = re.findall( |
| 12010 |
r"-[Kk](?:[zhxr]|p[0-9.\s]+)|-[Ll][0-9.\s]+", |
| 12011 |
extra_args, |
| 12012 |
) |
| 12013 |
if inking: |
| 12014 |
collink_args.extend(parse_argument_string(" ".join(inking))) |
| 12015 |
# Get rid of lores B2A tables - they affect |
| 12016 |
# collink even in inverse forward lookup mode |
| 12017 |
# (probably because collink tries to determine inking |
| 12018 |
# rules by looking at B2A?) |
| 12019 |
for tableno in range(3): |
| 12020 |
tablename = f"B2A{tableno:d}" |
| 12021 |
if tablename in profile.tags: |
| 12022 |
del profile.tags[tablename] |
| 12023 |
profchanged = True |
| 12024 |
if profchanged: |
| 12025 |
# Need to write updated profile for xicclu/collink |
| 12026 |
profile.write() |
| 12027 |
# Input curve clipping. |
| 12028 |
# Setting to True makes rel. col. + BPC produce a |
| 12029 |
# smoother result, but reduces accuracy of the |
| 12030 |
# colorimetric table |
| 12031 |
input_curve_clipping = False |
| 12032 |
# Determine profile blackpoint |
| 12033 |
if input_curve_clipping: |
| 12034 |
# Figure out profile blackpoint by looking up |
| 12035 |
# neutral values from L* = 0 to L* = 50, |
| 12036 |
# in 0.1 increments |
| 12037 |
idata = [(i / 10.0, 0, 0) for i in range(501)] |
| 12038 |
odata = self.xicclu( |
| 12039 |
profile, |
| 12040 |
idata, |
| 12041 |
intent="r", |
| 12042 |
direction="if", |
| 12043 |
pcs="l", |
| 12044 |
use_cam_clipping=True, |
| 12045 |
get_clip=True, |
| 12046 |
) |
| 12047 |
Labbp = (0, 0, 0) |
| 12048 |
for i, values in enumerate(odata): |
| 12049 |
if not values[-1]: |
| 12050 |
# Not clipped |
| 12051 |
Labbp = idata[i] |
| 12052 |
break |
| 12053 |
ogamap_profile = gamap_profile |
| 12054 |
for tableno, intent in tables: |
| 12055 |
# Create device link(s) |
| 12056 |
gamap_args = [] |
| 12057 |
if tableno == 1: |
| 12058 |
# Use PhotoPrintRGB as PCS if creating colorimetric |
| 12059 |
# table for non-RGB profile. |
| 12060 |
# PhotoPrintRGB is a synthetic L* TRC space |
| 12061 |
# with the Rec2020 red and blue adapted to D50 |
| 12062 |
# and a green of x 0.1292 (same as blue x) y 0.8185 |
| 12063 |
# It almost completely encompasses PhotoGamutRGB |
| 12064 |
pcs = get_data_path("ref/PhotoPrintRGB_Lstar.icc") |
| 12065 |
if pcs: |
| 12066 |
try: |
| 12067 |
gamap_profile = ICCProfile(pcs) |
| 12068 |
except (OSError, ICCProfileInvalidError) as exception: |
| 12069 |
self.log(exception) |
| 12070 |
else: |
| 12071 |
missing = lang.getstr( |
| 12072 |
"file.missing", "ref/PhotoPrintRGB_Lstar.icc" |
| 12073 |
) |
| 12074 |
if gamap_profile: |
| 12075 |
self.log(missing) |
| 12076 |
else: |
| 12077 |
result = Error(missing) |
| 12078 |
break |
| 12079 |
if pcs and input_curve_clipping and Labbp: |
| 12080 |
self.log( |
| 12081 |
"Applying black offset L*a*b* " |
| 12082 |
"{:.2f} {:.2f} {:.2f} to {}...".format( |
| 12083 |
*(*Labbp, gamap_profile.getDescription()) |
| 12084 |
) |
| 12085 |
) |
| 12086 |
XYZbp = colormath.Lab2XYZ(*Labbp) |
| 12087 |
gamap_profile.apply_black_offset(XYZbp) |
| 12088 |
# Write to temp file because file changed |
| 12089 |
fd, gamap_profile.filename = mkstemp_bypath( |
| 12090 |
gamap_profile.filename, dirname=self.tempdir |
| 12091 |
) |
| 12092 |
stream = os.fdopen(fd, "wb") |
| 12093 |
gamap_profile.write(stream) |
| 12094 |
stream.close() |
| 12095 |
gamap_profiles.append(gamap_profile) |
| 12096 |
elif gamap: |
| 12097 |
gamap_profile = ogamap_profile |
| 12098 |
if getcfg("gamap_src_viewcond"): |
| 12099 |
gamap_args.append("-c" + getcfg("gamap_src_viewcond")) |
| 12100 |
if getcfg("gamap_out_viewcond"): |
| 12101 |
gamap_args.append("-d" + getcfg("gamap_out_viewcond")) |
| 12102 |
# Preserve input curves in resulting devicelink? |
| 12103 |
preserve_input_curves = True |
| 12104 |
if gamap_profile and not preserve_input_curves: |
| 12105 |
for channel in "rgb": |
| 12106 |
trc = gamap_profile.tags[channel + "TRC"] |
| 12107 |
trc_len = len(trc) |
| 12108 |
# Do not preserve input shaper curves if nonlinear |
| 12109 |
if trc_len > 1 or trc[0] != 1.0: |
| 12110 |
if trc_len > 1: |
| 12111 |
# Check if nonlinear (10 bit precision) |
| 12112 |
values = [ |
| 12113 |
round(v / 65535.0 * 1023) for v in trc |
| 12114 |
] |
| 12115 |
ivalues = [ |
| 12116 |
round(v / (trc_len - 1.0) * 1023) |
| 12117 |
for v in range(trc_len) |
| 12118 |
] |
| 12119 |
ni = values != ivalues |
| 12120 |
else: |
| 12121 |
# Single gamma != 1.0 (nonlinear) |
| 12122 |
ni = True |
| 12123 |
if ni and "-ni" not in collink_args: |
| 12124 |
# Do not preserve input shaper curves in |
| 12125 |
# devicelink |
| 12126 |
collink_args.append("-ni") |
| 12127 |
break |
| 12128 |
if not ni and "-ni" in collink_args: |
| 12129 |
# Preserve input shaper curves in |
| 12130 |
# devicelink |
| 12131 |
collink_args.remove("-ni") |
| 12132 |
break |
| 12133 |
link_profile = tempfile.mktemp(PROFILE_EXT, dir=self.tempdir) # noqa: S306 |
| 12134 |
result = self.exec_cmd( |
| 12135 |
collink, |
| 12136 |
collink_args |
| 12137 |
+ gamap_args |
| 12138 |
+ [ |
| 12139 |
"-i" + intent, |
| 12140 |
gamap_profile.filename, |
| 12141 |
profile_path, |
| 12142 |
link_profile, |
| 12143 |
], |
| 12144 |
sessionlogfile=self.sessionlogfile, |
| 12145 |
) |
| 12146 |
if not isinstance(result, Exception) and result: |
| 12147 |
try: |
| 12148 |
link_profile = ICCProfile(link_profile) |
| 12149 |
except (OSError, ICCProfileInvalidError) as exception: |
| 12150 |
self.log(exception) |
| 12151 |
continue |
| 12152 |
table = f"B2A{tableno:d}" |
| 12153 |
profile.tags[table] = link_profile.tags.A2B0 |
| 12154 |
if gamap_profile: |
| 12155 |
# Map B2A input curves to inverse source |
| 12156 |
# profile TRC |
| 12157 |
for i, channel in enumerate("rgb"): |
| 12158 |
curve = profile.tags[table].input[i] |
| 12159 |
trc = gamap_profile.tags[channel + "TRC"] |
| 12160 |
if len(trc) == 1: |
| 12161 |
trc.set_trc(trc[0], len(curve)) |
| 12162 |
elif len(trc) != len(curve): |
| 12163 |
trc = colormath.interp_resize( |
| 12164 |
trc, len(curve), use_numpy=True |
| 12165 |
) |
| 12166 |
interp = colormath.Interp( |
| 12167 |
trc, curve, use_numpy=True |
| 12168 |
) |
| 12169 |
profile.tags[table].input[i] = [ |
| 12170 |
interp(j / 4095.0 * 65535) for j in range(4096) |
| 12171 |
] |
| 12172 |
# Remove temporary link profile |
| 12173 |
os.remove(link_profile.filename) |
| 12174 |
# Update B2A matrix with source profile matrix |
| 12175 |
matrix = colormath.Matrix3x3( |
| 12176 |
[ |
| 12177 |
[ |
| 12178 |
gamap_profile.tags.rXYZ.X, |
| 12179 |
gamap_profile.tags.gXYZ.X, |
| 12180 |
gamap_profile.tags.bXYZ.X, |
| 12181 |
], |
| 12182 |
[ |
| 12183 |
gamap_profile.tags.rXYZ.Y, |
| 12184 |
gamap_profile.tags.gXYZ.Y, |
| 12185 |
gamap_profile.tags.bXYZ.Y, |
| 12186 |
], |
| 12187 |
[ |
| 12188 |
gamap_profile.tags.rXYZ.Z, |
| 12189 |
gamap_profile.tags.gXYZ.Z, |
| 12190 |
gamap_profile.tags.bXYZ.Z, |
| 12191 |
], |
| 12192 |
] |
| 12193 |
) |
| 12194 |
matrix.invert() |
| 12195 |
scale = 1 + (32767 / 32768.0) |
| 12196 |
matrix *= colormath.Matrix3x3( |
| 12197 |
((scale, 0, 0), (0, scale, 0), (0, 0, scale)) |
| 12198 |
) |
| 12199 |
profile.tags[table].matrix = matrix |
| 12200 |
profchanged = True |
| 12201 |
else: |
| 12202 |
break |
| 12203 |
elif ( |
| 12204 |
getcfg("profile.b2a.hires") |
| 12205 |
and getcfg("profile.b2a.hires.smooth") |
| 12206 |
and gamap |
| 12207 |
): |
| 12208 |
# Smooth existing B2A tables |
| 12209 |
linebuffered_logfiles = [] |
| 12210 |
if ( |
| 12211 |
sys.stdout |
| 12212 |
and hasattr(sys.stdout, "isatty") |
| 12213 |
and sys.stdout.isatty() |
| 12214 |
): |
| 12215 |
linebuffered_logfiles.append(print) |
| 12216 |
else: |
| 12217 |
linebuffered_logfiles.append(LOG) |
| 12218 |
if self.sessionlogfile: |
| 12219 |
linebuffered_logfiles.append(self.sessionlogfile) |
| 12220 |
logfiles = Files( |
| 12221 |
[ |
| 12222 |
LineBufferedStream( |
| 12223 |
FilteredStream( |
| 12224 |
Files(linebuffered_logfiles), |
| 12225 |
ENC, |
| 12226 |
discard="", |
| 12227 |
linesep_in="\n", |
| 12228 |
triggers=[], |
| 12229 |
) |
| 12230 |
), |
| 12231 |
self.recent, |
| 12232 |
self.lastmsg, |
| 12233 |
] |
| 12234 |
) |
| 12235 |
smooth_tables = [] |
| 12236 |
for tableno in (0, 2): |
| 12237 |
table = profile.tags.get(f"B2A{tableno:d}") |
| 12238 |
if table in smooth_tables: |
| 12239 |
continue |
| 12240 |
if self.smooth_B2A( |
| 12241 |
profile, |
| 12242 |
tableno, |
| 12243 |
getcfg("profile.b2a.hires.diagpng") and 2, |
| 12244 |
logfile=logfiles, |
| 12245 |
): |
| 12246 |
smooth_tables.append(table) |
| 12247 |
profchanged = True |
| 12248 |
self.errors = errors |
| 12249 |
self.output = output |
| 12250 |
self.retcode = retcode |
| 12251 |
if not isinstance(result, Exception) and result: |
| 12252 |
for gamap_profile in gamap_profiles: |
| 12253 |
if ( |
| 12254 |
gamap_profile |
| 12255 |
and os.path.dirname(gamap_profile.filename) == self.tempdir |
| 12256 |
): |
| 12257 |
# Remove temporary source profile |
| 12258 |
os.remove(gamap_profile.filename) |
| 12259 |
if profchanged and tables: |
| 12260 |
# Make sure we match Argyll colprof i.e. have a complete |
| 12261 |
# set of tables |
| 12262 |
if "A2B1" not in profile.tags: |
| 12263 |
profile.tags.A2B1 = profile.tags.A2B0 |
| 12264 |
if "A2B2" not in profile.tags: |
| 12265 |
profile.tags.A2B2 = profile.tags.A2B0 |
| 12266 |
|
| 12267 |
if ( |
| 12268 |
profile.colorSpace == b"RGB" |
| 12269 |
and profile.connectionColorSpace in (b"XYZ", b"Lab") |
| 12270 |
and "A2B0" in profile.tags |
| 12271 |
and (getcfg("profile.b2a.hires") or "B2A1" in profile.tags) |
| 12272 |
): |
| 12273 |
# Apply BPC to A2B0/A2B2 to match B2A0/B2A2 black |
| 12274 |
|
| 12275 |
if profchanged: |
| 12276 |
# We need to write the changed profile |
| 12277 |
try: |
| 12278 |
profile.write() |
| 12279 |
except Exception as exception: |
| 12280 |
return exception |
| 12281 |
|
| 12282 |
if "A2B1" not in profile.tags: |
| 12283 |
self.log("Generating A2B1 by copying A2B0") |
| 12284 |
profile.tags.A2B1 = profile.tags.A2B0 |
| 12285 |
A2B1 = profile.tags.get("A2B1") |
| 12286 |
a2b_tables = [0] |
| 12287 |
if profile.tags.get("B2A2"): |
| 12288 |
a2b_tables.append(2) |
| 12289 |
|
| 12290 |
D50 = colormath.get_whitepoint("D50") |
| 12291 |
|
| 12292 |
XYZrgb = self.xicclu( |
| 12293 |
profile, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], pcs="x" |
| 12294 |
) |
| 12295 |
Xr, Yr, Zr = XYZrgb[0] |
| 12296 |
Xg, Yg, Zg = XYZrgb[1] |
| 12297 |
Xb, Yb, Zb = XYZrgb[2] |
| 12298 |
m1 = colormath.Matrix3x3( |
| 12299 |
((Xr, Xg, Xb), (Yr, Yg, Yb), (Zr, Zg, Zb)) |
| 12300 |
).inverted() |
| 12301 |
Sr, Sg, Sb = m1 * D50 |
| 12302 |
m2 = colormath.Matrix3x3( |
| 12303 |
( |
| 12304 |
(Sr * Xr, Sg * Xg, Sb * Xb), |
| 12305 |
(Sr * Yr, Sg * Yg, Sb * Yb), |
| 12306 |
(Sr * Zr, Sg * Zg, Sb * Zb), |
| 12307 |
) |
| 12308 |
).inverted() |
| 12309 |
|
| 12310 |
for tableno in a2b_tables: |
| 12311 |
tablename = f"A2B{tableno:d}" |
| 12312 |
table = profile.tags.get(tablename) |
| 12313 |
if not table: |
| 12314 |
continue |
| 12315 |
if tables: |
| 12316 |
# Get inverse B2A0/B2A2 black |
| 12317 |
XYZbp_B2A = self.xicclu( |
| 12318 |
profile, |
| 12319 |
[[0, 0, 0]], |
| 12320 |
intent="prs"[tableno], |
| 12321 |
direction="ib", |
| 12322 |
pcs="x", |
| 12323 |
)[0] |
| 12324 |
XYZbp_B2A = tuple(XYZbp_B2A) |
| 12325 |
else: |
| 12326 |
XYZbp_B2A = (0, 0, 0) |
| 12327 |
Labbp_B2A = colormath.XYZ2Lab(*XYZbp_B2A, scale=1) |
| 12328 |
if XYZbp and (0, 0, 0) not in (XYZbp, XYZbp_B2A): |
| 12329 |
# Make it same hue as relcol black |
| 12330 |
self.log( |
| 12331 |
f"Inverse B2A{tableno:d}", |
| 12332 |
"blackpoint L*a*b* {:.6f} {:.6f} {:.6f}".format( |
| 12333 |
*Labbp_B2A |
| 12334 |
), |
| 12335 |
) |
| 12336 |
if XYZbp_B2A != (0, 0, 0): |
| 12337 |
# Always... |
| 12338 |
continue |
| 12339 |
Labbp_B2A = (Labbp_B2A[0], Labbp[1], Labbp[2]) |
| 12340 |
self.log( |
| 12341 |
"Adjusted", |
| 12342 |
tablename, |
| 12343 |
"blackpoint L*a*b* {:.6f} {:.6f} {:.6f}".format( |
| 12344 |
*Labbp_B2A |
| 12345 |
), |
| 12346 |
) |
| 12347 |
XYZbp_B2A = colormath.Lab2XYZ(*Labbp_B2A) |
| 12348 |
if XYZbp_B2A == XYZbp: |
| 12349 |
continue |
| 12350 |
if table is A2B1 and not getcfg( |
| 12351 |
"profile.black_point_compensation" |
| 12352 |
): |
| 12353 |
# Make A2B0/A2B2 a distinct table |
| 12354 |
self.log("Making distinct", tablename) |
| 12355 |
table = LUT16Type(None, tablename, profile) |
| 12356 |
table.matrix = [] |
| 12357 |
for row in A2B1.matrix: |
| 12358 |
table.matrix.append(list(row)) |
| 12359 |
table.input = [] |
| 12360 |
table.output = [] |
| 12361 |
for curves in ("input", "output"): |
| 12362 |
for channel in getattr(A2B1, curves): |
| 12363 |
getattr(table, curves).append(list(channel)) |
| 12364 |
table.clut = [] |
| 12365 |
for block in A2B1.clut: |
| 12366 |
table.clut.append([]) |
| 12367 |
for row in block: |
| 12368 |
table.clut[-1].append(list(row)) |
| 12369 |
profile.tags[tablename] = table |
| 12370 |
else: |
| 12371 |
table = profile.tags[tablename] |
| 12372 |
# Apply BPC to A2B0/A2B2 |
| 12373 |
self.log( |
| 12374 |
f"Applying black point compensation to {tablename}:", |
| 12375 |
"L*a*b* {:.6f} {:.6f} {:.6f}".format(*Labbp_B2A), |
| 12376 |
) |
| 12377 |
table.apply_black_offset( |
| 12378 |
XYZbp_B2A, None, self.thread_abort, lang.getstr("aborted") |
| 12379 |
) |
| 12380 |
profchanged = True |
| 12381 |
if XYZbp: |
| 12382 |
# Adjust for BPC |
| 12383 |
if XYZbp_B2A != (0, 0, 0): |
| 12384 |
XYZbp_A2B = XYZbp_B2A |
| 12385 |
else: |
| 12386 |
XYZbp_A2B = [v * Ybp for v in D50] |
| 12387 |
XYZtmp = list(XYZrgb) |
| 12388 |
for i, XYZ in enumerate(XYZtmp): |
| 12389 |
XYZtmp[i] = colormath.blend_blackpoint( |
| 12390 |
*XYZ, bp_in=(0, 0, 0), bp_out=XYZbp_A2B |
| 12391 |
) |
| 12392 |
Xr, Yr, Zr = XYZtmp[0] |
| 12393 |
Xg, Yg, Zg = XYZtmp[1] |
| 12394 |
Xb, Yb, Zb = XYZtmp[2] |
| 12395 |
m3 = colormath.Matrix3x3( |
| 12396 |
((Xr, Xg, Xb), (Yr, Yg, Yb), (Zr, Zg, Zb)) |
| 12397 |
).inverted() |
| 12398 |
Sr, Sg, Sb = m3 * D50 |
| 12399 |
m4 = colormath.Matrix3x3( |
| 12400 |
( |
| 12401 |
(Sr * Xr, Sg * Xg, Sb * Xb), |
| 12402 |
(Sr * Yr, Sg * Yg, Sb * Yb), |
| 12403 |
(Sr * Zr, Sg * Zg, Sb * Zb), |
| 12404 |
) |
| 12405 |
) |
| 12406 |
|
| 12407 |
if DEBUG: |
| 12408 |
for i in range(3): |
| 12409 |
self.log( |
| 12410 |
colormath.XYZ2xyY(*XYZrgb[i]), |
| 12411 |
colormath.XYZ2xyY(*XYZtmp[i]), |
| 12412 |
colormath.XYZ2xyY(*m4 * (m2 * XYZrgb[i])), |
| 12413 |
) |
| 12414 |
interp = [] |
| 12415 |
rinterp = [] |
| 12416 |
osize = len(table.output[0]) |
| 12417 |
omaxv = osize - 1.0 |
| 12418 |
orange = [i / omaxv * 65535 for i in range(osize)] |
| 12419 |
for i in range(3): |
| 12420 |
interp.append(colormath.Interp(orange, table.output[i])) |
| 12421 |
rinterp.append( |
| 12422 |
colormath.Interp(table.output[i], orange) |
| 12423 |
) |
| 12424 |
num_workers = 1 if len(table.clut[0]) < 33 else None |
| 12425 |
table.clut = functools.reduce( |
| 12426 |
operator.iadd, |
| 12427 |
pool_slice( |
| 12428 |
_mp_apply, |
| 12429 |
table.clut, |
| 12430 |
( |
| 12431 |
profile.connectionColorSpace, |
| 12432 |
colormath.matmul, |
| 12433 |
(m4, m2), |
| 12434 |
D50, |
| 12435 |
interp, |
| 12436 |
rinterp, |
| 12437 |
lang.getstr("aborted"), |
| 12438 |
), |
| 12439 |
{}, |
| 12440 |
num_workers, |
| 12441 |
self.thread_abort, |
| 12442 |
), |
| 12443 |
[], |
| 12444 |
) |
| 12445 |
|
| 12446 |
# A2B processing |
| 12447 |
process_A2B = ( |
| 12448 |
"A2B0" in profile.tags |
| 12449 |
and profile.colorSpace == b"RGB" |
| 12450 |
and profile.connectionColorSpace in (b"XYZ", b"Lab") |
| 12451 |
and ( |
| 12452 |
getcfg("profile.b2a.hires") |
| 12453 |
or getcfg("profile.quality.b2a") in ("l", "n") |
| 12454 |
or not has_B2A |
| 12455 |
) |
| 12456 |
) |
| 12457 |
if process_A2B and (getcfg("profile.b2a.hires") or not has_B2A): |
| 12458 |
if profchanged: |
| 12459 |
# We need to write the changed profile before |
| 12460 |
# enhancing B2A resolution! |
| 12461 |
try: |
| 12462 |
profile.write() |
| 12463 |
except Exception as exception: |
| 12464 |
return exception |
| 12465 |
result = self.update_profile_B2A(profile) |
| 12466 |
if not isinstance(result, Exception) and result: |
| 12467 |
profchanged = True |
| 12468 |
|
| 12469 |
# All table processing done |
| 12470 |
|
| 12471 |
if not isinstance(result, Exception) and result: |
| 12472 |
if profchanged and tables: |
| 12473 |
# Make sure we match Argyll colprof i.e. have a complete |
| 12474 |
# set of tables |
| 12475 |
if profile.colorSpace != b"RGB": |
| 12476 |
if len(tables) == 1: |
| 12477 |
# We only created a colorimetric table, the |
| 12478 |
# others are still low quality. Assign |
| 12479 |
# colorimetric table |
| 12480 |
profile.tags.B2A0 = profile.tags.B2A1 |
| 12481 |
if len(tables) < 3: |
| 12482 |
# We only created colorimetric and/or perceptual |
| 12483 |
# tables, saturation table is still low quality. |
| 12484 |
# Assign perceptual table |
| 12485 |
profile.tags.B2A2 = profile.tags.B2A0 |
| 12486 |
if "B2A2" not in profile.tags: |
| 12487 |
profile.tags.B2A2 = profile.tags.B2A0 |
| 12488 |
apply_bpc = ( |
| 12489 |
getcfg("profile.black_point_compensation") |
| 12490 |
and "A2B0" not in profile.tags |
| 12491 |
) or (process_A2B and (getcfg("profile.b2a.hires") or not has_B2A)) |
| 12492 |
# If profile type is X (XYZ cLUT + matrix) add the matrix tags |
| 12493 |
# from a lookup of a smaller testchart or A2B/B2A (faster |
| 12494 |
# computation!). If profile is a shaper+matrix profile, |
| 12495 |
# re-generate shaper curves from testchart with only |
| 12496 |
# gray+primaries (better curve smoothness and neutrality) |
| 12497 |
# Make sure we do this *after* all changes on the A2B/B2A tables |
| 12498 |
# are done, because we may end up using them for lookup! |
| 12499 |
if ( |
| 12500 |
getcfg("profile.type") in ("X", "s", "S") |
| 12501 |
and profile.colorSpace == b"RGB" |
| 12502 |
): |
| 12503 |
if getcfg("profile.type") == "X": |
| 12504 |
if ( |
| 12505 |
not isinstance(profile.tags.get("vcgt"), VideoCardGammaType) |
| 12506 |
or profile.tags.vcgt.is_linear() |
| 12507 |
): |
| 12508 |
# Use matrix from 3x shaper curves profile if vcgt |
| 12509 |
# is linear |
| 12510 |
ptype = "s" |
| 12511 |
if profchanged: |
| 12512 |
# We need to write the changed profile before |
| 12513 |
# creating TRC tags because we will be using |
| 12514 |
# lookup through A2B/B2A table! |
| 12515 |
try: |
| 12516 |
profile.write() |
| 12517 |
except Exception as exception: |
| 12518 |
return exception |
| 12519 |
else: |
| 12520 |
# Use matrix from single shaper curve profile if |
| 12521 |
# vcgt is nonlinear |
| 12522 |
ptype = "S" |
| 12523 |
else: |
| 12524 |
ptype = getcfg("profile.type") |
| 12525 |
result = self._create_matrix_profile( |
| 12526 |
args[-1], profile, ptype, "XYZ", apply_bpc |
| 12527 |
) |
| 12528 |
if isinstance(result, ICCProfile): |
| 12529 |
result = True |
| 12530 |
profchanged = True |
| 12531 |
if ( |
| 12532 |
not isinstance(result, Exception) |
| 12533 |
and result |
| 12534 |
and ( |
| 12535 |
"rTRC" in profile.tags |
| 12536 |
and "gTRC" in profile.tags |
| 12537 |
and "bTRC" in profile.tags |
| 12538 |
and isinstance(profile.tags.rTRC, CurveType) |
| 12539 |
and isinstance(profile.tags.gTRC, CurveType) |
| 12540 |
and isinstance(profile.tags.bTRC, CurveType) |
| 12541 |
and apply_bpc |
| 12542 |
and len(profile.tags.rTRC) > 1 |
| 12543 |
and len(profile.tags.gTRC) > 1 |
| 12544 |
and len(profile.tags.bTRC) > 1 |
| 12545 |
and ( |
| 12546 |
profile.tags.rTRC[0] != 0 |
| 12547 |
or profile.tags.gTRC[0] != 0 |
| 12548 |
or profile.tags.bTRC[0] != 0 |
| 12549 |
) |
| 12550 |
) |
| 12551 |
): |
| 12552 |
self.log("-" * 80) |
| 12553 |
for component in ("r", "g", "b"): |
| 12554 |
self.log(f"Applying black point compensation to {component}TRC") |
| 12555 |
profile.apply_black_offset( |
| 12556 |
(0, 0, 0), include_A2B=False, set_blackpoint=False |
| 12557 |
) |
| 12558 |
if getcfg("profile.black_point_compensation"): |
| 12559 |
bpc_applied = True |
| 12560 |
profchanged = True |
| 12561 |
if profchanged and not isinstance(result, Exception) and result: |
| 12562 |
if "bkpt" in profile.tags and bpc_applied: |
| 12563 |
# We need to update the blackpoint tag |
| 12564 |
try: |
| 12565 |
odata = self.xicclu(profile, (0, 0, 0), intent="a", pcs="x") |
| 12566 |
if len(odata) != 1 or len(odata[0]) != 3: |
| 12567 |
raise ValueError(f"Blackpoint is invalid: {odata}") |
| 12568 |
except Exception as exception: |
| 12569 |
self.log(exception) |
| 12570 |
else: |
| 12571 |
( |
| 12572 |
profile.tags.bkpt.X, |
| 12573 |
profile.tags.bkpt.Y, |
| 12574 |
profile.tags.bkpt.Z, |
| 12575 |
) = odata[0] |
| 12576 |
# We need to write the changed profile |
| 12577 |
try: |
| 12578 |
profile.write() |
| 12579 |
except Exception as exception: |
| 12580 |
return exception |
| 12581 |
if os.path.isfile(f"{args[-1]}.ti3.backup") and os.path.isfile( |
| 12582 |
f"{args[-1]}.ti3" |
| 12583 |
): |
| 12584 |
# Restore backed up TI3 |
| 12585 |
os.rename(f"{args[-1]}.ti3", f"{args[-1]}.bpc.ti3") |
| 12586 |
os.rename(f"{args[-1]}.ti3.backup", f"{args[-1]}.ti3") |
| 12587 |
with open(f"{args[-1]}.ti3", "rb") as ti3_file: |
| 12588 |
ti3 = ti3_file.read() |
| 12589 |
elif not is_regular_grid and not is_primaries_only: |
| 12590 |
ti3 = None |
| 12591 |
if not isinstance(result, Exception) and result: |
| 12592 |
# Always explicitly do profile self check |
| 12593 |
self.exec_cmd( |
| 12594 |
get_argyll_util("profcheck"), |
| 12595 |
[args[-1] + ".ti3", args[-1] + PROFILE_EXT], |
| 12596 |
capture_output=True, |
| 12597 |
skip_scripts=True, |
| 12598 |
) |
| 12599 |
# Get profile max and avg err to be later added to metadata |
| 12600 |
# Argyll outputs the following: |
| 12601 |
# Profile check complete, peak err = x.xxxxxx, avg err = x.xxxxxx, RMS = x.xxxxxx # noqa: E501 |
| 12602 |
peak = None |
| 12603 |
avg = None |
| 12604 |
rms = None |
| 12605 |
for line in self.output: |
| 12606 |
if line.startswith("Profile check complete"): |
| 12607 |
peak = re.search(r"(?:peak err|max\.) = (\d+(?:\.\d+))", line) |
| 12608 |
avg = re.search(r"avg(?: err|\.) = (\d+(?:\.\d+))", line) |
| 12609 |
rms = re.search(r"RMS = (\d+(?:\.\d+))", line) |
| 12610 |
if peak: |
| 12611 |
peak = peak.groups()[0] |
| 12612 |
if avg: |
| 12613 |
avg = avg.groups()[0] |
| 12614 |
if rms: |
| 12615 |
rms = rms.groups()[0] |
| 12616 |
break |
| 12617 |
if not isinstance(result, Exception) and result: |
| 12618 |
(gamut_volume, gamut_coverage) = self.create_gamut_views(profile_path) |
| 12619 |
self.log("-" * 80) |
| 12620 |
if not isinstance(result, Exception) and result: |
| 12621 |
result = self.update_profile( |
| 12622 |
profile, |
| 12623 |
ti3, |
| 12624 |
chrm, |
| 12625 |
tags, |
| 12626 |
avg, |
| 12627 |
peak, |
| 12628 |
rms, |
| 12629 |
gamut_volume, |
| 12630 |
gamut_coverage, |
| 12631 |
quality=getcfg("profile.quality"), |
| 12632 |
) |
| 12633 |
result2 = self.wrapup( |
| 12634 |
not isinstance(result, UnloggedInfo) and result, dst_path=dst_path |
| 12635 |
) |
| 12636 |
if isinstance(result2, Exception): |
| 12637 |
if isinstance(result, Exception): |
| 12638 |
result = Error(str(result) + "\n\n" + str(result2)) |
| 12639 |
else: |
| 12640 |
result = result2 |
| 12641 |
elif not isinstance(result, Exception) and result: |
| 12642 |
setcfg("last_cal_or_icc_path", dst_path) |
| 12643 |
setcfg("last_icc_path", dst_path) |
| 12644 |
return result |
| 12645 |
|
| 12646 |
def create_RGB_XYZ_cLUT_fwd_profile( |
| 12647 |
self, |
| 12648 |
ti3, |
| 12649 |
description, |
| 12650 |
copyright_, |
| 12651 |
manufacturer, |
| 12652 |
model, |
| 12653 |
logfn=None, |
| 12654 |
clutres=33, |
| 12655 |
cat="Bradford", |
| 12656 |
): |
| 12657 |
"""Create a RGB to XYZ forward profile. |
| 12658 |
|
| 12659 |
Args: |
| 12660 |
ti3 (dict): The TI3 data. |
| 12661 |
description (str): Profile description. |
| 12662 |
copyright_ (str): Profile copyright. |
| 12663 |
manufacturer (str): Profile manufacturer. |
| 12664 |
model (str): Profile model. |
| 12665 |
logfn (callable, optional): Function to log messages. |
| 12666 |
clutres (int, optional): Resolution of the cLUT. |
| 12667 |
cat (str, optional): Color appearance model. |
| 12668 |
|
| 12669 |
Returns: |
| 12670 |
ICCProfile: The created ICC profile. |
| 12671 |
""" |
| 12672 |
# Extract grays and remaining colors |
| 12673 |
(ti3_extracted, RGB_XYZ, remaining) = extract_device_gray_primaries( |
| 12674 |
ti3, True, logfn |
| 12675 |
) |
| 12676 |
bwd_matrix = colormath.Matrix3x3([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) |
| 12677 |
|
| 12678 |
# Check if we have calibration, if so, add vcgt |
| 12679 |
vcgt = False |
| 12680 |
options_dispcal = [] |
| 12681 |
# is_hq_cal = False |
| 12682 |
for cgats in ti3.values(): |
| 12683 |
if cgats.type == b"CAL": |
| 12684 |
vcgt = cal_to_vcgt(cgats) |
| 12685 |
options_dispcal = get_options_from_cal(cgats)[0] |
| 12686 |
# is_hq_cal = "qh" in options_dispcal |
| 12687 |
|
| 12688 |
dEs = [] |
| 12689 |
RGB_XYZ = dict_sort(RGB_XYZ) |
| 12690 |
for X, Y, Z in RGB_XYZ.values(): |
| 12691 |
if Y >= 1: |
| 12692 |
X, Y, Z = colormath.adapt(X, Y, Z, RGB_XYZ[(100, 100, 100)], cat=cat) |
| 12693 |
L, a, b = colormath.XYZ2Lab(X, Y, Z) |
| 12694 |
dE = colormath.delta(L, 0, 0, L, a, b, "00")["E"] |
| 12695 |
dEs.append(dE) |
| 12696 |
if DEBUG or VERBOSE > 1: |
| 12697 |
self.log(f"L* {L:5.2f} a* {a:5.2f} b* {b:5.2f} dE*00 {dE:4.2f}") |
| 12698 |
dE_avg = sum(dEs) / len(dEs) |
| 12699 |
dE_max = max(dEs) |
| 12700 |
self.log("R=G=B (>= 1% luminance) dE*00 avg", dE_avg, "peak", dE_max) |
| 12701 |
|
| 12702 |
# Create profile |
| 12703 |
profile = ICCProfile() |
| 12704 |
profile.version = 2.2 # Match ArgyllCMS |
| 12705 |
profile.setDescription(description) |
| 12706 |
profile.setCopyright(copyright_) |
| 12707 |
if manufacturer: |
| 12708 |
profile.setDeviceManufacturerDescription(manufacturer) |
| 12709 |
if model: |
| 12710 |
profile.setDeviceModelDescription(model) |
| 12711 |
luminance_XYZ_cdm2 = ti3.queryv1("LUMINANCE_XYZ_CDM2") |
| 12712 |
if luminance_XYZ_cdm2: |
| 12713 |
profile.tags.lumi = XYZType(profile=profile) |
| 12714 |
profile.tags.lumi.Y = float(luminance_XYZ_cdm2.split()[1]) |
| 12715 |
profile.tags.wtpt = XYZType(profile=profile) |
| 12716 |
white_XYZ = [v / 100.0 for v in RGB_XYZ[(100, 100, 100)]] |
| 12717 |
(profile.tags.wtpt.X, profile.tags.wtpt.Y, profile.tags.wtpt.Z) = white_XYZ |
| 12718 |
profile.tags.bkpt = XYZType(profile=profile) |
| 12719 |
black_XYZ = [v / 100.0 for v in RGB_XYZ[(0, 0, 0)]] |
| 12720 |
(profile.tags.bkpt.X, profile.tags.bkpt.Y, profile.tags.bkpt.Z) = black_XYZ |
| 12721 |
profile.tags.arts = ChromaticAdaptionTag() |
| 12722 |
profile.tags.arts.update(colormath.get_cat_matrix(cat)) |
| 12723 |
|
| 12724 |
# Check if we have calibration, if so, add vcgt |
| 12725 |
if vcgt: |
| 12726 |
profile.tags.vcgt = vcgt |
| 12727 |
|
| 12728 |
# Interpolate shaper curves from grays - returned curves are adapted |
| 12729 |
# to D50 |
| 12730 |
self.single_curve = round(dE_max, 2) <= 1.25 and round(dE_avg, 2) <= 0.5 |
| 12731 |
if self.single_curve: |
| 12732 |
self.log( |
| 12733 |
"Got high quality calibration, using single device to PCS " |
| 12734 |
"shaper curve for cLUT" |
| 12735 |
) |
| 12736 |
|
| 12737 |
gray = create_shaper_curves( |
| 12738 |
RGB_XYZ, |
| 12739 |
bwd_matrix, |
| 12740 |
self.single_curve, |
| 12741 |
getcfg("profile.black_point_compensation"), |
| 12742 |
logfn, |
| 12743 |
profile=profile, |
| 12744 |
options_dispcal=options_dispcal, |
| 12745 |
optimize=self.single_curve, |
| 12746 |
cat=cat, |
| 12747 |
) |
| 12748 |
|
| 12749 |
curves = [curve[:] for curve in gray] |
| 12750 |
|
| 12751 |
# Add black back in |
| 12752 |
XYZbp = [ |
| 12753 |
v / 100.0 |
| 12754 |
for v in colormath.adapt( |
| 12755 |
*RGB_XYZ[(0, 0, 0)], whitepoint_source=RGB_XYZ[(100, 100, 100)], cat=cat |
| 12756 |
) |
| 12757 |
] |
| 12758 |
for i in range(len(gray[0])): |
| 12759 |
(gray[0][i], gray[1][i], gray[2][i]) = colormath.apply_bpc( |
| 12760 |
*(curve[i] for curve in gray), bp_in=(0, 0, 0), bp_out=XYZbp |
| 12761 |
) |
| 12762 |
|
| 12763 |
grayinterp = [ |
| 12764 |
colormath.Interp(list(range(len(curve))), curve, use_numpy=True) |
| 12765 |
for curve in gray |
| 12766 |
] |
| 12767 |
|
| 12768 |
def get_XYZ_from_curves(n, m): |
| 12769 |
# Curves are adapted to D50 |
| 12770 |
return [interp((len(interp.xp) - 1.0) / m * n) for interp in grayinterp] |
| 12771 |
|
| 12772 |
# Quantize RGB to make lookup easier |
| 12773 |
# XXX Note that round(50 * 2.55) = 127, but |
| 12774 |
# round(50 / 100 * 255) = 128 (the latter is what we want)! |
| 12775 |
remaining = { |
| 12776 |
tuple(round(k / 100.0 * 255) for k in RGB): XYZ |
| 12777 |
for RGB, XYZ in remaining.items() |
| 12778 |
} |
| 12779 |
|
| 12780 |
# Need to sort so columns increase (fastest to slowest) B G R |
| 12781 |
remaining = dict_sort(remaining) |
| 12782 |
|
| 12783 |
# Build initial cLUT |
| 12784 |
# Try to fill a 5x5x5 or 3x3x3 cLUT |
| 12785 |
clut_actual = 0 |
| 12786 |
for iclutres in (17, 9, 5, 4, 3, 2): |
| 12787 |
clut = [] |
| 12788 |
step = 100 / (iclutres - 1.0) |
| 12789 |
for a in range(iclutres): |
| 12790 |
for b in range(iclutres): |
| 12791 |
clut.append([]) |
| 12792 |
for c in range(iclutres): |
| 12793 |
# XXX Note that round(50 * 2.55) = 127, but |
| 12794 |
# round(50 / 100 * 255) = 128 (the latter is what we want)! |
| 12795 |
RGB = tuple(round((k * step) / 100.0 * 255) for k in (a, b, c)) |
| 12796 |
# Prefer actual measurements over interpolated values |
| 12797 |
XYZ = remaining.get(RGB) |
| 12798 |
if not XYZ: |
| 12799 |
if a == b == c: |
| 12800 |
# Fall back to interpolated values for gray |
| 12801 |
# (already black scaled) |
| 12802 |
XYZ = get_XYZ_from_curves(a, iclutres - 1) |
| 12803 |
# Range 0..1 |
| 12804 |
clut[-1].append(XYZ) |
| 12805 |
elif iclutres > 2: |
| 12806 |
# Try next smaller cLUT res |
| 12807 |
break |
| 12808 |
else: |
| 12809 |
raise ValueError( |
| 12810 |
"Measurement data is missing RGB " |
| 12811 |
"{:.4f} {:.4f} {:.4f}".format(*RGB) |
| 12812 |
) |
| 12813 |
else: |
| 12814 |
clut_actual += 1 |
| 12815 |
X, Y, Z = (v / 100.0 for v in XYZ) |
| 12816 |
# # Need to black scale actual measurements |
| 12817 |
# X, Y, Z = colormath.blend_blackpoint(X, Y, Z, |
| 12818 |
# black_XYZ, None, white_XYZ) |
| 12819 |
# Range 0..1 |
| 12820 |
clut[-1].append( |
| 12821 |
colormath.adapt(X, Y, Z, white_XYZ, cat=cat) |
| 12822 |
) |
| 12823 |
if c < iclutres - 1: |
| 12824 |
break |
| 12825 |
if b < iclutres - 1: |
| 12826 |
break |
| 12827 |
if a == iclutres - 1: |
| 12828 |
break |
| 12829 |
self.log("Initial cLUT resolution {:d}x{:d}x{:d}".format(*(iclutres,) * 3)) |
| 12830 |
|
| 12831 |
profile.tags.A2B0 = create_RGB_A2B_XYZ(curves, clut, self.log) |
| 12832 |
|
| 12833 |
# Interpolate to higher cLUT resolution |
| 12834 |
quality = getcfg("profile.quality") |
| 12835 |
clutres = {"m": 17, "l": 9}.get(quality, clutres) |
| 12836 |
# XXX: Need to implement proper 3D interpolation |
| 12837 |
|
| 12838 |
if clutres > iclutres: |
| 12839 |
# Lookup input RGB to interpolated XYZ |
| 12840 |
# NOTE: step must be (re)computed for the *target* clutres BEFORE |
| 12841 |
# building RGB_in. Otherwise it still holds the previous low-res |
| 12842 |
# iclutres step, so the RGB_in grid coordinates run far past device |
| 12843 |
# 100% (e.g. 32 * 6.25 = 200), which clamps most lookups to the |
| 12844 |
# white corner and produces a grossly corrupt A2B cLUT. |
| 12845 |
step = 100 / (clutres - 1.0) |
| 12846 |
RGB_in = [ |
| 12847 |
[a * step, b * step, c * step] |
| 12848 |
for a in range(clutres) |
| 12849 |
for b in range(clutres) |
| 12850 |
for c in range(clutres) |
| 12851 |
] |
| 12852 |
XYZ_out = self.xicclu(profile, RGB_in, "a", pcs="X", scale=100) |
| 12853 |
profile.filename = None |
| 12854 |
|
| 12855 |
# Create new cLUT |
| 12856 |
clut = [] |
| 12857 |
i = -1 |
| 12858 |
actual = 0 |
| 12859 |
interpolated = 0 |
| 12860 |
for a in range(clutres): |
| 12861 |
for b in range(clutres): |
| 12862 |
clut.append([]) |
| 12863 |
for c in range(clutres): |
| 12864 |
# XXX Note that round(50 * 2.55) = 127, but |
| 12865 |
# round(50 / 100 * 255) = 128 (the latter is what we want)! |
| 12866 |
RGB = tuple(round((k * step) / 100.0 * 255) for k in (a, b, c)) |
| 12867 |
# Prefer actual measurements over interpolated values |
| 12868 |
# prev_actual = actual |
| 12869 |
XYZ = remaining.get(RGB) |
| 12870 |
i += 1 |
| 12871 |
if not XYZ: |
| 12872 |
# Fall back to interpolated values |
| 12873 |
# (already black scaled) |
| 12874 |
if a == b == c: |
| 12875 |
XYZ = get_XYZ_from_curves(a, clutres - 1) |
| 12876 |
# Range 0..1 |
| 12877 |
clut[-1].append(XYZ) |
| 12878 |
continue |
| 12879 |
XYZ = XYZ_out[i] |
| 12880 |
interpolated += 1 |
| 12881 |
else: |
| 12882 |
actual += 1 |
| 12883 |
X, Y, Z = (v / 100.0 for v in XYZ) |
| 12884 |
# if actual > prev_actual: |
| 12885 |
# # Need to black scale actual measurements |
| 12886 |
# X, Y, Z = colormath.blend_blackpoint(X, Y, Z, |
| 12887 |
# black_XYZ, None, white_XYZ) |
| 12888 |
# Range 0..1 |
| 12889 |
clut[-1].append(colormath.adapt(X, Y, Z, white_XYZ, cat=cat)) |
| 12890 |
if actual > clut_actual: |
| 12891 |
# Did we get any additional actual measured cLUT points? |
| 12892 |
self.log( |
| 12893 |
f"cLUT resolution {clutres:d}x{clutres:d}x{clutres:d}: Got " |
| 12894 |
f"{actual - clut_actual:d} additional values from " |
| 12895 |
"actual measurements" |
| 12896 |
) |
| 12897 |
|
| 12898 |
profile.tags.A2B0 = create_RGB_A2B_XYZ(curves, clut, self.log) |
| 12899 |
clut_actual = actual |
| 12900 |
|
| 12901 |
self.log( |
| 12902 |
"Final interpolated cLUT resolution {:d}x{:d}x{:d}".format( |
| 12903 |
*((len(profile.tags.A2B0.clut[0]),) * 3) |
| 12904 |
) |
| 12905 |
) |
| 12906 |
|
| 12907 |
profile.tags.A2B0.profile = profile |
| 12908 |
|
| 12909 |
# # Add black back in |
| 12910 |
# black_XYZ_D50 = colormath.adapt( |
| 12911 |
# *black_XYZ, whitepoint_source=white_XYZ, cat=cat |
| 12912 |
# ) |
| 12913 |
# profile.tags.A2B0.apply_black_offset(black_XYZ_D50) |
| 12914 |
|
| 12915 |
return profile |
| 12916 |
|
| 12917 |
def _create_simple_matrix_profile( |
| 12918 |
self, |
| 12919 |
ti3_RGB_XYZ, |
| 12920 |
ti3_remaining, |
| 12921 |
desc, |
| 12922 |
copyright_="No copyright", |
| 12923 |
display_manufacturer=None, |
| 12924 |
display_name=None, |
| 12925 |
bpc=False, |
| 12926 |
cat="Bradford", |
| 12927 |
): |
| 12928 |
"""Create a simple matrix profile from primaries and gray. |
| 12929 |
|
| 12930 |
Args: |
| 12931 |
ti3_RGB_XYZ (dict): A dictionary with RGB tuples as keys and |
| 12932 |
XYZ tuples as values, representing the RGB to XYZ |
| 12933 |
measurements. |
| 12934 |
ti3_remaining (dict): A dictionary with RGB tuples as keys and |
| 12935 |
XYZ tuples as values, representing the remaining RGB to XYZ |
| 12936 |
measurements. |
| 12937 |
desc (str): The description of the profile. |
| 12938 |
copyright_ (str): The copyright of the profile. |
| 12939 |
display_manufacturer (str, optional): The manufacturer of the |
| 12940 |
display. |
| 12941 |
display_name (str, optional): The name of the display. |
| 12942 |
bpc (bool): If True, black point compensation will be applied. |
| 12943 |
cat (str): The chromatic adaptation transform to use, default is |
| 12944 |
'Bradford'. |
| 12945 |
|
| 12946 |
Returns: |
| 12947 |
ICCProfile: An ICCProfile with fileName set to None, containing |
| 12948 |
the matrix tags created from the primaries and gray. |
| 12949 |
""" |
| 12950 |
self.log("-" * 80) |
| 12951 |
self.log("Creating matrix from primaries") |
| 12952 |
xy = [] |
| 12953 |
XYZbp = ti3_RGB_XYZ[(0, 0, 0)] |
| 12954 |
XYZwp = ti3_RGB_XYZ[(100, 100, 100)] |
| 12955 |
for R, G, B in [(100, 0, 0), (0, 100, 0), (0, 0, 100), (100, 100, 100)]: |
| 12956 |
RGB_XYZ = ti3_RGB_XYZ if R == G == B else ti3_remaining |
| 12957 |
X, Y, Z = RGB_XYZ[(R, G, B)] |
| 12958 |
if XYZbp != (0, 0, 0) and not bpc: |
| 12959 |
# Adjust for black offset |
| 12960 |
X, Y, Z = colormath.blend_blackpoint(X, Y, Z, XYZbp, (0, 0, 0), XYZwp) |
| 12961 |
xy.append(colormath.XYZ2xyY(*(v / 100 for v in (X, Y, Z)))[:2]) |
| 12962 |
self.log("Using chromatic adaptation transform matrix:", cat) |
| 12963 |
return ICCProfile.from_chromaticities( |
| 12964 |
xy[0][0], |
| 12965 |
xy[0][1], |
| 12966 |
xy[1][0], |
| 12967 |
xy[1][1], |
| 12968 |
xy[2][0], |
| 12969 |
xy[2][1], |
| 12970 |
xy[3][0], |
| 12971 |
xy[3][1], |
| 12972 |
2.2, # Will be replaced |
| 12973 |
desc, |
| 12974 |
copyright_, |
| 12975 |
display_manufacturer, |
| 12976 |
display_name, |
| 12977 |
cat=cat, |
| 12978 |
) |
| 12979 |
|
| 12980 |
def _create_matrix_profile( |
| 12981 |
self, outname, profile=None, ptype="s", omit=None, bpc=False, cat="Bradford" |
| 12982 |
): |
| 12983 |
"""Create matrix profile from lookup through ti3. |
| 12984 |
|
| 12985 |
<outname>.ti3 has to exist. |
| 12986 |
If <profile> is given, it has to be an ICCProfile instance, and the |
| 12987 |
matrix tags will be added to this profile. |
| 12988 |
<ptype> should be the type of profile, i.e. one of g, G, s or S. |
| 12989 |
<omit> if given should be the tag to omit, either 'TRC' or 'XYZ'. |
| 12990 |
|
| 12991 |
We use a testchart with only gray + primaries for TRC, |
| 12992 |
and larger testchart for the matrix. This should give the smoothest |
| 12993 |
overall result. |
| 12994 |
|
| 12995 |
Args: |
| 12996 |
outname (str): The base name of the output profile, without |
| 12997 |
extension. |
| 12998 |
profile (ICCProfile, optional): An ICCProfile instance to which the |
| 12999 |
tags will be added. If not given, a new profile will be |
| 13000 |
created. |
| 13001 |
ptype (str): The type of profile to create, one of 'g', 'G', 's', |
| 13002 |
or 'S'. |
| 13003 |
omit (str, optional): If 'XYZ', the XYZ tags will not be created. |
| 13004 |
bpc (bool): If True, black point compensation will be applied. |
| 13005 |
cat (str): The chromatic adaptation transform to use, default is |
| 13006 |
'Bradford'. |
| 13007 |
|
| 13008 |
Returns: |
| 13009 |
ICCProfile: An ICCProfile with fileName set to <outname>.ic[cm]. |
| 13010 |
|
| 13011 |
""" |
| 13012 |
if profile: |
| 13013 |
cat = profile.guess_cat() or cat |
| 13014 |
tags = "shaper" if omit == "XYZ" else "shaper+matrix" |
| 13015 |
self.log("-" * 80) |
| 13016 |
self.log(f"Creating {tags} tags in separate step") |
| 13017 |
self.log("Using chromatic adaptation transform matrix:", cat) |
| 13018 |
fakeread = get_argyll_util("fakeread") |
| 13019 |
if not fakeread: |
| 13020 |
return Error(lang.getstr("argyll.util.not_found", "fakeread")) |
| 13021 |
colprof = get_argyll_util("colprof") |
| 13022 |
if not colprof: |
| 13023 |
return Error(lang.getstr("argyll.util.not_found", "colprof")) |
| 13024 |
# Strip potential CAL from Ti3 |
| 13025 |
try: |
| 13026 |
oti3 = CGATS(outname + ".ti3") |
| 13027 |
except (OSError, CGATSError) as exception: |
| 13028 |
return exception |
| 13029 |
else: |
| 13030 |
if 0 in oti3: |
| 13031 |
ti3 = oti3[0] |
| 13032 |
ti3.filename = oti3.filename # So we can log the name |
| 13033 |
ti3.fix_zero_measurements(logfile=self.get_logfiles(False)) |
| 13034 |
else: |
| 13035 |
return Error( |
| 13036 |
lang.getstr("error.measurement.file_invalid", outname + ".ti3") |
| 13037 |
) |
| 13038 |
for ti1name, tagcls in [("d3-e4-s3-g52-m3-b0-f0", "XYZ"), (None, "TRC")]: |
| 13039 |
if tagcls == omit: |
| 13040 |
continue |
| 13041 |
if tagcls == "TRC" and profile and "A2B0" in profile.tags and ptype == "s": |
| 13042 |
# Create TRC from forward lookup through A2B |
| 13043 |
numentries = 256 |
| 13044 |
maxval = numentries - 1.0 |
| 13045 |
RGBin = [(i / maxval,) * 3 for i in range(numentries)] |
| 13046 |
# Inverse backward if "B2A0" in tags, otherwise forward |
| 13047 |
direction = "ib" if "B2A0" in profile.tags else "f" |
| 13048 |
try: |
| 13049 |
XYZout = self.xicclu(profile, RGBin, "p", direction, pcs="x") |
| 13050 |
except Info as exception: |
| 13051 |
return exception |
| 13052 |
# Get RGB space from already added matrix column tags |
| 13053 |
rgb_space = colormath.get_rgb_space(profile.get_rgb_space("pcs", 1)) |
| 13054 |
mtx = rgb_space[-1].inverted() |
| 13055 |
self.log("-" * 80) |
| 13056 |
for channel in "rgb": |
| 13057 |
tagname = channel + tagcls |
| 13058 |
self.log( |
| 13059 |
"Adding {} from {} lookup to {}".format( |
| 13060 |
tagname, |
| 13061 |
{ |
| 13062 |
"f": "forward A2B0", |
| 13063 |
"ib": "inverse backward B2A0", |
| 13064 |
}.get(direction), |
| 13065 |
profile.getDescription(), |
| 13066 |
) |
| 13067 |
) |
| 13068 |
profile.tags[tagname] = CurveType() |
| 13069 |
for XYZ in XYZout: |
| 13070 |
RGB = mtx * XYZ |
| 13071 |
for i, channel in enumerate("rgb"): |
| 13072 |
tagname = channel + tagcls |
| 13073 |
profile.tags[tagname].append(min(max(RGB[i], 0), 1) * 65535) |
| 13074 |
break |
| 13075 |
if not ti1name: |
| 13076 |
# Extract gray+primaries into new TI3 |
| 13077 |
(ti3, RGB_XYZ, remaining) = extract_device_gray_primaries( |
| 13078 |
ti3, tagcls == "TRC", self.log |
| 13079 |
) |
| 13080 |
ti3.sort_by_rgb() |
| 13081 |
self.log(ti3.DATA) |
| 13082 |
if tagcls == "TRC" and profile: |
| 13083 |
rgb_space = colormath.get_rgb_space(profile.get_rgb_space("pcs", 1)) |
| 13084 |
fwd_mtx = rgb_space[-1] |
| 13085 |
bwd_mtx = fwd_mtx.inverted() |
| 13086 |
|
| 13087 |
self.log("-" * 80) |
| 13088 |
|
| 13089 |
options_dispcal = get_options_from_ti3(oti3)[0] |
| 13090 |
|
| 13091 |
curves = create_shaper_curves( |
| 13092 |
RGB_XYZ, |
| 13093 |
bwd_mtx, |
| 13094 |
ptype == "S", |
| 13095 |
bpc, |
| 13096 |
self.log, |
| 13097 |
profile=profile, |
| 13098 |
options_dispcal=options_dispcal, |
| 13099 |
optimize=ptype == "S", |
| 13100 |
cat=cat, |
| 13101 |
) |
| 13102 |
|
| 13103 |
for i, channel in enumerate("rgb"): |
| 13104 |
tagname = channel + tagcls |
| 13105 |
self.log( |
| 13106 |
f"Adding {tagname} from interpolation " |
| 13107 |
f"to {profile.getDescription()}" |
| 13108 |
) |
| 13109 |
profile.tags[tagname] = trc = CurveType(profile=profile) |
| 13110 |
# Slope limit for 16-bit encoding |
| 13111 |
trc[:] = [ |
| 13112 |
max(v, j / 65535.0) * 65535 for j, v in enumerate(curves[i]) |
| 13113 |
] |
| 13114 |
|
| 13115 |
if not bpc: |
| 13116 |
XYZbp = None |
| 13117 |
for R, G, B in RGB_XYZ: |
| 13118 |
X, Y, Z = RGB_XYZ[(R, G, B)] |
| 13119 |
if R == G == B == 0: |
| 13120 |
XYZbp = [v / 100 for v in (X, Y, Z)] |
| 13121 |
XYZbp = colormath.adapt( |
| 13122 |
*XYZbp, |
| 13123 |
whitepoint_source=RGB_XYZ[(100, 100, 100)], |
| 13124 |
cat=cat, |
| 13125 |
) |
| 13126 |
if XYZbp: |
| 13127 |
# Add black back in |
| 13128 |
profile.apply_black_offset(XYZbp, include_A2B=False) |
| 13129 |
if ptype == "S": |
| 13130 |
# Single curve |
| 13131 |
profile.tags["rTRC"][:] = profile.tags["gTRC"][:] |
| 13132 |
profile.tags["bTRC"][:] = profile.tags["gTRC"][:] |
| 13133 |
|
| 13134 |
break |
| 13135 |
ti3.write(f"{outname}.0.ti3") |
| 13136 |
if ti1name: |
| 13137 |
ti1 = get_data_path(f"ti1/{ti1name}.ti1") |
| 13138 |
if not ti1: |
| 13139 |
return Error(lang.getstr("file.missing", f"ti1/{ti1name}.ti1")) |
| 13140 |
fakeout = f"{outname}.{ti1name}" |
| 13141 |
try: |
| 13142 |
shutil.copyfile(ti1, f"{fakeout}.ti1") |
| 13143 |
except OSError as exception: |
| 13144 |
return exception |
| 13145 |
# Lookup ti1 through ti3 |
| 13146 |
result = self.exec_cmd( |
| 13147 |
fakeread, |
| 13148 |
[f"{outname}.0.ti3", fakeout], |
| 13149 |
capture_output=True, |
| 13150 |
skip_scripts=True, |
| 13151 |
sessionlogfile=self.sessionlogfile, |
| 13152 |
) |
| 13153 |
try: |
| 13154 |
os.remove(f"{fakeout}.ti1") |
| 13155 |
except OSError as exception: |
| 13156 |
self.log(exception) |
| 13157 |
if not result: |
| 13158 |
return UnloggedError("\n".join(self.errors)) |
| 13159 |
if isinstance(result, Exception): |
| 13160 |
return result |
| 13161 |
try: |
| 13162 |
os.remove(f"{outname}.0.ti3") |
| 13163 |
except OSError as exception: |
| 13164 |
self.log(exception) |
| 13165 |
else: |
| 13166 |
# Use gray+primaries from existing ti3 |
| 13167 |
fakeout = f"{outname}.0" |
| 13168 |
result = self.exec_cmd( |
| 13169 |
colprof, |
| 13170 |
["-v", "-q" + getcfg("profile.quality"), "-a" + ptype, fakeout], |
| 13171 |
sessionlogfile=self.sessionlogfile, |
| 13172 |
) |
| 13173 |
try: |
| 13174 |
os.remove(f"{fakeout}.ti3") |
| 13175 |
except OSError as exception: |
| 13176 |
self.log(exception) |
| 13177 |
if isinstance(result, Exception) or not result: |
| 13178 |
return result |
| 13179 |
try: |
| 13180 |
matrix_profile = ICCProfile(fakeout + PROFILE_EXT) |
| 13181 |
except (OSError, ICCProfileInvalidError): |
| 13182 |
return Error( |
| 13183 |
lang.getstr("profile.invalid") + "\n" + fakeout + PROFILE_EXT |
| 13184 |
) |
| 13185 |
if profile: |
| 13186 |
self.log("-" * 80) |
| 13187 |
for channel in "rgb": |
| 13188 |
tagname = channel + tagcls |
| 13189 |
tag = matrix_profile.tags.get(tagname) |
| 13190 |
if tag: |
| 13191 |
self.log( |
| 13192 |
f"Adding {tagname} from matrix profile " |
| 13193 |
f"to {profile.getDescription()}" |
| 13194 |
) |
| 13195 |
profile.tags[tagname] = tag |
| 13196 |
else: |
| 13197 |
self.log(lang.getstr("profile.required_tags_missing", tagname)) |
| 13198 |
else: |
| 13199 |
profile = matrix_profile |
| 13200 |
profile.filename = outname + PROFILE_EXT |
| 13201 |
try: |
| 13202 |
os.remove(fakeout + PROFILE_EXT) |
| 13203 |
except OSError as exception: |
| 13204 |
self.log(exception) |
| 13205 |
return profile |
| 13206 |
|
| 13207 |
def update_profile( |
| 13208 |
self, |
| 13209 |
profile: ICCProfile, |
| 13210 |
ti3: None | CGATS = None, |
| 13211 |
chrm: None | ChromaticityType = None, |
| 13212 |
tags: None | bool | dict = None, |
| 13213 |
avg: None | str = None, |
| 13214 |
peak: None | str = None, |
| 13215 |
rms: None | str = None, |
| 13216 |
gamut_volume: None | float = None, |
| 13217 |
gamut_coverage: None | float = None, |
| 13218 |
quality: None | str = None, |
| 13219 |
): |
| 13220 |
"""Update profile tags and metadata. |
| 13221 |
|
| 13222 |
Args: |
| 13223 |
profile (ICCProfile): The profile to update. |
| 13224 |
ti3 (str or bytes, optional): Original TI3 data to embed. |
| 13225 |
chrm (ChromaticityType, optional): Chromaticity data to add. |
| 13226 |
tags (dict or bool, optional): Custom tags to add or True for default tags. |
| 13227 |
avg (str, optional): Average error from profile check. |
| 13228 |
peak (str, optional): Peak error from profile check. |
| 13229 |
rms (str, optional): RMS error from profile check. |
| 13230 |
gamut_volume (float, optional): Gamut volume of the profile. |
| 13231 |
gamut_coverage (float, optional): Gamut coverage of the profile. |
| 13232 |
quality (str, optional): Quality of the profile, e.g., 'v', 'l', 'm', 'h'. |
| 13233 |
|
| 13234 |
Returns: |
| 13235 |
ICCProfile: The updated profile. |
| 13236 |
""" |
| 13237 |
if isinstance(profile, str): |
| 13238 |
profile_path = profile |
| 13239 |
try: |
| 13240 |
profile = ICCProfile(profile_path) |
| 13241 |
except (OSError, ICCProfileInvalidError): |
| 13242 |
return Error(lang.getstr("profile.invalid") + "\n" + profile_path) |
| 13243 |
else: |
| 13244 |
profile_path = profile.filename |
| 13245 |
if ( |
| 13246 |
profile.profileClass == b"mntr" |
| 13247 |
and profile.colorSpace == b"RGB" |
| 13248 |
and not (self.tempdir and profile_path.startswith(self.tempdir)) |
| 13249 |
): |
| 13250 |
setcfg("last_cal_or_icc_path", profile_path) |
| 13251 |
setcfg("last_icc_path", profile_path) |
| 13252 |
if ti3: |
| 13253 |
# Embed original TI3 |
| 13254 |
profile.tags.targ = profile.tags.DevD = profile.tags.CIED = TextType( |
| 13255 |
b"text\0\0\0\0" + bytes(ti3) + b"\0", b"targ" |
| 13256 |
) |
| 13257 |
if chrm: |
| 13258 |
# Add ChromaticityType tag |
| 13259 |
profile.tags.chrm = chrm |
| 13260 |
# Fixup desc tags - ASCII needs to be 7-bit |
| 13261 |
# also add Unicode strings if different from ASCII |
| 13262 |
if "desc" in profile.tags and isinstance( |
| 13263 |
profile.tags.desc, TextDescriptionType |
| 13264 |
): |
| 13265 |
profile.setDescription(profile.getDescription()) |
| 13266 |
if "dmdd" in profile.tags and isinstance( |
| 13267 |
profile.tags.dmdd, TextDescriptionType |
| 13268 |
): |
| 13269 |
profile.setDeviceModelDescription(profile.getDeviceModelDescription()) |
| 13270 |
if "dmnd" in profile.tags and isinstance( |
| 13271 |
profile.tags.dmnd, TextDescriptionType |
| 13272 |
): |
| 13273 |
profile.setDeviceManufacturerDescription( |
| 13274 |
profile.getDeviceManufacturerDescription() |
| 13275 |
) |
| 13276 |
if tags and tags is not True: |
| 13277 |
# Add custom tags |
| 13278 |
for tagname in tags: |
| 13279 |
tag = tags[tagname] |
| 13280 |
if tagname == "mmod": |
| 13281 |
profile.device["manufacturer"] = ( |
| 13282 |
b"\0\0" + tag["manufacturer"][1] + tag["manufacturer"][0] |
| 13283 |
) |
| 13284 |
profile.device["model"] = ( |
| 13285 |
b"\0\0" + tag["model"][0] + tag["model"][1] |
| 13286 |
) |
| 13287 |
profile.tags[tagname] = tag |
| 13288 |
elif tags is True: |
| 13289 |
edid = self.get_display_edid() |
| 13290 |
if edid: |
| 13291 |
profile.device["manufacturer"] = ( |
| 13292 |
b"\0\0" + edid["edid"][9:10] + edid["edid"][8:9] |
| 13293 |
) |
| 13294 |
profile.device["model"] = ( |
| 13295 |
b"\0\0" + edid["edid"][11:12] + edid["edid"][10:11] |
| 13296 |
) |
| 13297 |
# Add Apple-specific 'mmod' tag (TODO: need full spec) |
| 13298 |
mmod = ( |
| 13299 |
b"mmod" |
| 13300 |
+ (b"\x00" * 6) |
| 13301 |
+ edid["edid"][8:10] |
| 13302 |
+ (b"\x00" * 2) |
| 13303 |
+ edid["edid"][11:12] |
| 13304 |
+ edid["edid"][10:11] |
| 13305 |
+ (b"\x00" * 4) |
| 13306 |
+ (b"\x00" * 20) |
| 13307 |
) |
| 13308 |
profile.tags.mmod = ICCProfileTag(mmod, "mmod") |
| 13309 |
# Add new meta information based on EDID |
| 13310 |
profile.set_edid_metadata(edid) |
| 13311 |
elif "meta" not in profile.tags: |
| 13312 |
# Make sure meta tag exists |
| 13313 |
profile.tags.meta = DictType() |
| 13314 |
if tags is True or (tags and "meta" in tags): |
| 13315 |
profile.tags.meta.update( |
| 13316 |
{ |
| 13317 |
"CMF_product": APPNAME, |
| 13318 |
"CMF_binary": APPNAME, |
| 13319 |
"CMF_version": VERSION_STRING, |
| 13320 |
} |
| 13321 |
) |
| 13322 |
# Set license |
| 13323 |
profile.tags.meta["License"] = getcfg("profile.license") |
| 13324 |
# Set profile quality |
| 13325 |
quality = {"v": "very low", "l": "low", "m": "medium", "h": "high"}.get( |
| 13326 |
quality |
| 13327 |
) |
| 13328 |
if quality: |
| 13329 |
profile.tags.meta["Quality"] = quality |
| 13330 |
spec_prefixes = "CMF_" |
| 13331 |
if tags is True: |
| 13332 |
# Set OPENICC_automatic_generated to "0" |
| 13333 |
profile.tags.meta["OPENICC_automatic_generated"] = "0" |
| 13334 |
# Set GCM DATA_source to "calib" |
| 13335 |
profile.tags.meta["DATA_source"] = "calib" |
| 13336 |
# Add instrument |
| 13337 |
profile.tags.meta["MEASUREMENT_device"] = self.get_instrument_name().lower() |
| 13338 |
spec_prefixes = "CMF_,DATA_,MEASUREMENT_,OPENICC_" |
| 13339 |
# Add screen brightness if applicable |
| 13340 |
if sys.platform not in ("darwin", "win32") and dbus_session: |
| 13341 |
try: |
| 13342 |
iface = DBusObject( |
| 13343 |
BUSTYPE_SESSION, |
| 13344 |
"org.gnome.SettingsDaemon.Power", |
| 13345 |
"/org/gnome/SettingsDaemon/Power", |
| 13346 |
"Screen", |
| 13347 |
) |
| 13348 |
brightness = iface.get_percentage() |
| 13349 |
except DBusException: |
| 13350 |
pass |
| 13351 |
else: |
| 13352 |
profile.tags.meta["SCREEN_brightness"] = str(brightness) |
| 13353 |
spec_prefixes += ",SCREEN_" |
| 13354 |
# Set device ID |
| 13355 |
device_id = self.get_device_id(quirk=False, query=True) |
| 13356 |
if device_id: |
| 13357 |
profile.tags.meta["MAPPING_device_id"] = device_id |
| 13358 |
spec_prefixes += ",MAPPING_" |
| 13359 |
if tags is True or (tags and "meta" in tags): |
| 13360 |
prefix = profile.tags.meta.getvalue("prefix", b"", None) |
| 13361 |
if isinstance(prefix, bytes): |
| 13362 |
prefix = prefix.decode("utf-8") |
| 13363 |
prefixes = (prefix or spec_prefixes).split(",") |
| 13364 |
for prefix in spec_prefixes.split(","): |
| 13365 |
if prefix not in prefixes: |
| 13366 |
prefixes.append(prefix) |
| 13367 |
profile.tags.meta["prefix"] = ",".join(prefixes) |
| 13368 |
if (avg, peak, rms) != (None,) * 3: |
| 13369 |
# Make sure meta tag exists |
| 13370 |
if "meta" not in profile.tags: |
| 13371 |
profile.tags.meta = DictType() |
| 13372 |
# Update meta prefix |
| 13373 |
prefix = profile.tags.meta.getvalue("prefix", b"", None) |
| 13374 |
if isinstance(prefix, bytes): |
| 13375 |
prefix = prefix.decode("utf-8") |
| 13376 |
prefixes = (prefix or "ACCURACY_").split(",") |
| 13377 |
if "ACCURACY_" not in prefixes: |
| 13378 |
prefixes.append("ACCURACY_") |
| 13379 |
profile.tags.meta["prefix"] = ",".join(prefixes) |
| 13380 |
# Add error info |
| 13381 |
if avg is not None: |
| 13382 |
profile.tags.meta["ACCURACY_dE76_avg"] = avg |
| 13383 |
if peak is not None: |
| 13384 |
profile.tags.meta["ACCURACY_dE76_max"] = peak |
| 13385 |
if rms is not None: |
| 13386 |
profile.tags.meta["ACCURACY_dE76_rms"] = rms |
| 13387 |
profile.set_gamut_metadata(gamut_volume, gamut_coverage) |
| 13388 |
# Set default rendering intent |
| 13389 |
if "B2A0" in profile.tags and ( |
| 13390 |
"B2A1" in profile.tags or "B2A2" in profile.tags |
| 13391 |
): |
| 13392 |
profile.intent = {"p": 0, "r": 1, "s": 2, "a": 3}[ |
| 13393 |
getcfg("gamap_default_intent") |
| 13394 |
] |
| 13395 |
# Check if we need to video scale vcgt |
| 13396 |
if isinstance(profile.tags.get("vcgt"), VideoCardGammaType): |
| 13397 |
try: |
| 13398 |
cal = extract_cal_from_profile(profile, None, False, prefer_cal=True) |
| 13399 |
except Exception as exception: |
| 13400 |
self.log(exception) |
| 13401 |
else: |
| 13402 |
white = False |
| 13403 |
if cal: |
| 13404 |
if cal.queryv1("TV_OUTPUT_ENCODING") == "YES": |
| 13405 |
black, white = (16, 235) |
| 13406 |
else: |
| 13407 |
output_enc = cal.queryv1("OUTPUT_ENCODING") |
| 13408 |
if output_enc: |
| 13409 |
try: |
| 13410 |
black, white = (float(v) for v in output_enc.split()) |
| 13411 |
except (TypeError, ValueError): |
| 13412 |
white = False |
| 13413 |
if white and (black, white) != (0, 255): |
| 13414 |
self.log(f"Need to scale vcgt to video levels ({black}..{white})") |
| 13415 |
# Need to create videoscaled vcgt from calibration |
| 13416 |
data = cal.queryv1("DATA") |
| 13417 |
if data: |
| 13418 |
self.log(f"Scaling vcgt to video levels ({black}..{white})") |
| 13419 |
for entry in data.values(): |
| 13420 |
for column in "RGB": |
| 13421 |
v_old = entry["RGB_" + column] |
| 13422 |
# For video encoding the extra bits of |
| 13423 |
# precision are created by bit shifting rather |
| 13424 |
# than scaling, so we need to scale the fp |
| 13425 |
# value to account for this |
| 13426 |
newmin = (black / 256.0) * (65536 / 65535.0) |
| 13427 |
newmax = (white / 256.0) * (65536 / 65535.0) |
| 13428 |
v_new = colormath.convert_range( |
| 13429 |
v_old, 0, 1, newmin, newmax |
| 13430 |
) |
| 13431 |
entry["RGB_" + column] = v_new |
| 13432 |
profile.tags.vcgt = cal_to_vcgt(cal) |
| 13433 |
else: |
| 13434 |
self.log("Warning - no scaling applied - no calibration data!") |
| 13435 |
# Calculate profile ID |
| 13436 |
profile.calculate_id() |
| 13437 |
try: |
| 13438 |
profile.write() |
| 13439 |
except Exception as exception: |
| 13440 |
return exception |
| 13441 |
return True |
| 13442 |
|
| 13443 |
def get_logfiles(self, include_progress_buffers: bool = True) -> LineBufferedStream: |
| 13444 |
"""Get logfiles for logging. |
| 13445 |
|
| 13446 |
Args: |
| 13447 |
include_progress_buffers (bool): Whether to include progress buffers |
| 13448 |
in the returned logfiles. Defaults to True. |
| 13449 |
|
| 13450 |
Returns: |
| 13451 |
LineBufferedStream: A stream that writes to the logfiles. |
| 13452 |
""" |
| 13453 |
linebuffered_logfiles = [] |
| 13454 |
if sys.stdout and hasattr(sys.stdout, "isatty") and sys.stdout.isatty(): |
| 13455 |
linebuffered_logfiles.append(print) |
| 13456 |
else: |
| 13457 |
linebuffered_logfiles.append(LOG) |
| 13458 |
if self.sessionlogfile: |
| 13459 |
linebuffered_logfiles.append(self.sessionlogfile) |
| 13460 |
logfiles = LineBufferedStream( |
| 13461 |
FilteredStream( |
| 13462 |
Files(linebuffered_logfiles), |
| 13463 |
ENC, |
| 13464 |
discard="", |
| 13465 |
linesep_in="\n", |
| 13466 |
triggers=[], |
| 13467 |
) |
| 13468 |
) |
| 13469 |
if include_progress_buffers: |
| 13470 |
logfiles = Files([logfiles, self.recent, self.lastmsg]) |
| 13471 |
return logfiles |
| 13472 |
|
| 13473 |
def update_profile_B2A( |
| 13474 |
self, |
| 13475 |
profile: ICCProfile, |
| 13476 |
generate_perceptual_table: bool = True, |
| 13477 |
clutres: None | int = None, |
| 13478 |
smooth: None | bool = None, |
| 13479 |
rgb_space: None | str = None, |
| 13480 |
) -> list | Exception: |
| 13481 |
"""Update B2A tables in profile. |
| 13482 |
|
| 13483 |
Args: |
| 13484 |
profile (ICCProfile): The ICC profile to update. |
| 13485 |
generate_perceptual_table (bool): Whether to generate a perceptual |
| 13486 |
B2A table if not present. |
| 13487 |
clutres (int, optional): The resolution of the cLUT to generate. |
| 13488 |
If not specified, it will be determined based on the profile |
| 13489 |
settings. |
| 13490 |
smooth (bool, optional): Whether to apply smoothing to the |
| 13491 |
generated B2A table. Defaults to the value from the profile |
| 13492 |
configuration. |
| 13493 |
rgb_space (str, optional): The RGB color space to use for the |
| 13494 |
B2A table. If not specified, the RGB space from the profile |
| 13495 |
will be used. |
| 13496 |
|
| 13497 |
Returns: |
| 13498 |
list | Exception: A list of generated B2A tables, or an exception |
| 13499 |
if an error occurred. |
| 13500 |
""" |
| 13501 |
# Use reverse A2B interpolation to generate B2A table |
| 13502 |
if not clutres: |
| 13503 |
if getcfg("profile.b2a.hires"): |
| 13504 |
# Chosen resolution |
| 13505 |
clutres = getcfg("profile.b2a.hires.size") |
| 13506 |
elif getcfg("profile.quality.b2a") in "ln": |
| 13507 |
# Low quality/resolution |
| 13508 |
clutres = 9 |
| 13509 |
else: |
| 13510 |
# Medium quality/resolution |
| 13511 |
clutres = 17 |
| 13512 |
if smooth is None: |
| 13513 |
smooth = getcfg("profile.b2a.hires.smooth") |
| 13514 |
logfiles = self.get_logfiles() |
| 13515 |
tables = [1] |
| 13516 |
self.log("-" * 80) |
| 13517 |
# Add perceptual tables if not present |
| 13518 |
if "A2B0" in profile.tags and "A2B1" not in profile.tags: |
| 13519 |
if not isinstance(profile.tags.A2B0, LUT16Type): |
| 13520 |
self.log(f"{APPNAME}: Can't process non-LUT16Type A2B0 table") |
| 13521 |
return [] |
| 13522 |
try: |
| 13523 |
# Copy A2B0 |
| 13524 |
logfiles.write("Generating A2B1 by copying A2B0\n") |
| 13525 |
profile.tags.A2B1 = profile.tags.A2B0 |
| 13526 |
if "B2A0" in profile.tags: |
| 13527 |
# Copy B2A0 |
| 13528 |
B2A0 = profile.tags.B2A0 |
| 13529 |
profile.tags.B2A1 = B2A1 = LUT16Type(None, "B2A1", profile) |
| 13530 |
B2A1.matrix = [] |
| 13531 |
for row in B2A0.matrix: |
| 13532 |
B2A1.matrix.append(list(row)) |
| 13533 |
B2A1.input = [] |
| 13534 |
B2A1.output = [] |
| 13535 |
for table in ("input", "output"): |
| 13536 |
for channel in getattr(B2A0, table): |
| 13537 |
getattr(B2A1, table).append(list(channel)) |
| 13538 |
B2A1.clut = [] |
| 13539 |
for block in B2A0.clut: |
| 13540 |
B2A1.clut.append([]) |
| 13541 |
for row in block: |
| 13542 |
B2A1.clut[-1].append(list(row)) |
| 13543 |
except Exception as exception: |
| 13544 |
return exception |
| 13545 |
if "A2B2" not in profile.tags and generate_perceptual_table: |
| 13546 |
# Argyll always creates a complete set of A2B / B2A tables if |
| 13547 |
# colprof -s (perceptual) or -S (perceptual and saturation) is used, |
| 13548 |
# so we can assume that if A2B2 is not present then it is safe to |
| 13549 |
# re-generate B2A0 because it was not created by Argyll CMS. |
| 13550 |
tables.append(0) |
| 13551 |
# Invert A2B tables if present. Always invert colorimetric A2B table. |
| 13552 |
rtables = [] |
| 13553 |
filename = profile.filename |
| 13554 |
for tableno in tables: |
| 13555 |
if f"A2B{tableno:d}" not in profile.tags: |
| 13556 |
continue |
| 13557 |
if ( |
| 13558 |
f"B2A{tableno:d}" in profile.tags |
| 13559 |
and profile.tags[f"B2A{tableno:d}"] in rtables |
| 13560 |
): |
| 13561 |
continue |
| 13562 |
if not isinstance(profile.tags[f"A2B{tableno:d}"], LUT16Type): |
| 13563 |
self.log(f"{APPNAME}: Can't process non-LUT16Type A2B{tableno:d} table") |
| 13564 |
continue |
| 13565 |
# Check if we want to apply BPC |
| 13566 |
bpc = tableno != 1 |
| 13567 |
if bpc and ( |
| 13568 |
profile.tags["A2B1"].clut[0][0] != [0, 0, 0] |
| 13569 |
or profile.tags["A2B1"].input[0][0] != 0 |
| 13570 |
or profile.tags["A2B1"].input[1][0] != 0 |
| 13571 |
or profile.tags["A2B1"].input[2][0] != 0 |
| 13572 |
or profile.tags["A2B1"].output[0][0] != 0 |
| 13573 |
or profile.tags["A2B1"].output[1][0] != 0 |
| 13574 |
or profile.tags["A2B1"].output[2][0] != 0 |
| 13575 |
): |
| 13576 |
# Need to apply BPC |
| 13577 |
table = LUT16Type(profile=profile) |
| 13578 |
# Copy existing B2A1 table matrix, cLUT and output curves |
| 13579 |
table.matrix = rtables[0].matrix |
| 13580 |
table.clut = rtables[0].clut |
| 13581 |
table.output = rtables[0].output |
| 13582 |
profile.tags[f"B2A{tableno:d}"] = table |
| 13583 |
elif bpc: |
| 13584 |
# BPC not needed, copy existing B2A |
| 13585 |
profile.tags[f"B2A{tableno:d}"] = rtables[0] |
| 13586 |
return rtables |
| 13587 |
if not filename or not os.path.isfile(filename) or bpc: |
| 13588 |
# Write profile to temp dir |
| 13589 |
tempdir = self.create_tempdir() |
| 13590 |
if isinstance(tempdir, Exception): |
| 13591 |
return tempdir |
| 13592 |
fd, profile.filename = tempfile.mkstemp(PROFILE_EXT, dir=tempdir) |
| 13593 |
stream = os.fdopen(fd, "wb") |
| 13594 |
profile.write(stream) |
| 13595 |
stream.close() |
| 13596 |
temp = True |
| 13597 |
else: |
| 13598 |
temp = False |
| 13599 |
# Invert A2B |
| 13600 |
try: |
| 13601 |
result = self.generate_B2A_from_inverse_table( |
| 13602 |
profile, |
| 13603 |
clutres, |
| 13604 |
"A2B", |
| 13605 |
tableno, |
| 13606 |
bpc, |
| 13607 |
smooth, |
| 13608 |
rgb_space, |
| 13609 |
logfiles, |
| 13610 |
filename, |
| 13611 |
bpc, |
| 13612 |
) |
| 13613 |
except (Error, Info) as exception: |
| 13614 |
return exception |
| 13615 |
except Exception as exception: |
| 13616 |
self.log(traceback.format_exc()) |
| 13617 |
return exception |
| 13618 |
else: |
| 13619 |
if result: |
| 13620 |
rtables.append(profile.tags[f"B2A{tableno:d}"]) |
| 13621 |
else: |
| 13622 |
return False |
| 13623 |
finally: |
| 13624 |
if temp: |
| 13625 |
os.remove(profile.filename) |
| 13626 |
profile.filename = filename |
| 13627 |
return rtables |
| 13628 |
|
| 13629 |
def is_working(self) -> bool: |
| 13630 |
"""Check if any Worker instance is busy. |
| 13631 |
|
| 13632 |
Returns: |
| 13633 |
bool: Return True if at least one of the Worker instances is busy, |
| 13634 |
False if all are finished. |
| 13635 |
""" |
| 13636 |
return any(not getattr(worker, "finished", True) for worker in workers) |
| 13637 |
|
| 13638 |
def start_measurement( |
| 13639 |
self, |
| 13640 |
consumer: Callable, |
| 13641 |
apply_calibration: None | bool | str = True, |
| 13642 |
progress_msg: str = "", |
| 13643 |
resume: bool = False, |
| 13644 |
continue_next: bool = False, |
| 13645 |
) -> None: |
| 13646 |
"""Start a measurement and use a progress dialog for progress information. |
| 13647 |
|
| 13648 |
Args: |
| 13649 |
consumer (callable): The consumer function to call with progress |
| 13650 |
updates. |
| 13651 |
apply_calibration (None | bool | str): If True, apply calibration |
| 13652 |
to the measurements. If it is None or a str value, it will |
| 13653 |
be passed as the `apply_calibration` argument to the |
| 13654 |
`measure` method. |
| 13655 |
progress_msg (str): Message to display in the progress dialog. |
| 13656 |
resume (bool): If True, resume from the last measurement point. |
| 13657 |
continue_next (bool): If True, continue to the next step after |
| 13658 |
measurement. |
| 13659 |
""" |
| 13660 |
self.start( |
| 13661 |
consumer, |
| 13662 |
self.measure, |
| 13663 |
wkwargs={"apply_calibration": apply_calibration}, |
| 13664 |
progress_msg=progress_msg, |
| 13665 |
resume=resume, |
| 13666 |
continue_next=continue_next, |
| 13667 |
pauseable=True, |
| 13668 |
) |
| 13669 |
|
| 13670 |
def start_calibration( |
| 13671 |
self, consumer, remove=False, progress_msg="", resume=False, continue_next=False |
| 13672 |
): |
| 13673 |
"""Start a calibration and use a progress dialog for progress information. |
| 13674 |
|
| 13675 |
Args: |
| 13676 |
consumer (callable): The consumer function to call with progress |
| 13677 |
updates. |
| 13678 |
remove (bool): If True, remove existing calibration before |
| 13679 |
starting. |
| 13680 |
progress_msg (str): Message to display in the progress dialog. |
| 13681 |
resume (bool): If True, resume from the last calibration point. |
| 13682 |
continue_next (bool): If True, continue to the next step after |
| 13683 |
calibration. |
| 13684 |
""" |
| 13685 |
self.start( |
| 13686 |
consumer, |
| 13687 |
self.calibrate, |
| 13688 |
wkwargs={"remove": remove}, |
| 13689 |
progress_msg=progress_msg, |
| 13690 |
resume=resume, |
| 13691 |
continue_next=continue_next, |
| 13692 |
interactive_frame="adjust", |
| 13693 |
pauseable=True, |
| 13694 |
) |
| 13695 |
|
| 13696 |
def madtpg_init(self): |
| 13697 |
"""Initialize madTPG connection.""" |
| 13698 |
if hasattr(self, "madtpg"): |
| 13699 |
return |
| 13700 |
if sys.platform == "win32" and getcfg("madtpg.native"): |
| 13701 |
# Using native implementation (madHcNet32.dll) |
| 13702 |
self.madtpg = madvr.MadTPG() |
| 13703 |
else: |
| 13704 |
# Using madVR net-protocol pure python implementation |
| 13705 |
self.madtpg = madvr.MadTPGNet() |
| 13706 |
self.madtpg.debug = VERBOSE |
| 13707 |
|
| 13708 |
def madtpg_connect(self): |
| 13709 |
"""Connect to madTPG and check version. |
| 13710 |
|
| 13711 |
Returns: |
| 13712 |
bool: True if connected successfully, False otherwise. |
| 13713 |
""" |
| 13714 |
self.madtpg_init() |
| 13715 |
self.patterngenerator = self.madtpg |
| 13716 |
if self.madtpg.connect(method3=madvr.CM_StartLocalInstance, timeout3=3000): |
| 13717 |
# Check madVR version |
| 13718 |
madvr_version = self.madtpg.get_version() |
| 13719 |
if not madvr_version or madvr_version < madvr.MIN_VERSION: |
| 13720 |
self.madtpg_disconnect(False) |
| 13721 |
raise Error(lang.getstr("madvr.outdated", madvr.MIN_VERSION)) |
| 13722 |
self.log( |
| 13723 |
"Connected to madVR version {:d}.{:d}.{:d}.{:d} ({})".format( |
| 13724 |
*(*madvr_version, self.madtpg.uri) |
| 13725 |
) |
| 13726 |
) |
| 13727 |
self.madtpg.set_osd_text("\u25b6") # "Play" symbol |
| 13728 |
return True |
| 13729 |
return False |
| 13730 |
|
| 13731 |
def madtpg_disconnect(self, restore_settings=True): |
| 13732 |
"""Restore madVR settings and disconnect. |
| 13733 |
|
| 13734 |
Args: |
| 13735 |
restore_settings (bool): If True, restore madTPG settings before |
| 13736 |
disconnecting. If False, do not restore settings. |
| 13737 |
""" |
| 13738 |
if restore_settings: |
| 13739 |
self.madtpg_restore_settings() |
| 13740 |
if self.madtpg.disconnect(): |
| 13741 |
self.log("Successfully disconnected from madTPG") |
| 13742 |
|
| 13743 |
def madtpg_restore_settings( |
| 13744 |
self, reconnect=True, restore_fullscreen=None, restore_osd=None |
| 13745 |
): |
| 13746 |
"""Restore madTPG settings (fullscreen and OSD). |
| 13747 |
|
| 13748 |
Args: |
| 13749 |
reconnect (bool): If True, re-connect to madTPG before restoring |
| 13750 |
settings. If False, assume madTPG is already connected. |
| 13751 |
restore_fullscreen (bool): If True, restore the fullscreen state |
| 13752 |
of madTPG. If None, use the previous state stored in |
| 13753 |
`madtpg_previous_fullscreen`. |
| 13754 |
restore_osd (bool): If True, restore the OSD state of madTPG. |
| 13755 |
If None, use the previous state stored in `madtpg_osd`. |
| 13756 |
If both `restore_fullscreen` and `restore_osd` are None, no |
| 13757 |
settings are restored. |
| 13758 |
""" |
| 13759 |
if restore_fullscreen is None: |
| 13760 |
restore_fullscreen = getattr(self, "madtpg_previous_fullscreen", None) |
| 13761 |
if restore_osd is None: |
| 13762 |
restore_osd = getattr(self, "madtpg_osd", None) is False |
| 13763 |
if not restore_fullscreen and not restore_osd: |
| 13764 |
return |
| 13765 |
|
| 13766 |
check = not reconnect or self.madtpg.get_version() |
| 13767 |
if not check and reconnect: |
| 13768 |
check = self.madtpg_connect() |
| 13769 |
if check: |
| 13770 |
if restore_fullscreen: |
| 13771 |
# Restore fullscreen |
| 13772 |
if self.madtpg.set_use_fullscreen_button(True): |
| 13773 |
self.log( |
| 13774 |
f"{APPNAME}: Restored madTPG 'use fullscreen' button state" |
| 13775 |
) |
| 13776 |
self.madtpg_previous_fullscreen = None |
| 13777 |
else: |
| 13778 |
self.log( |
| 13779 |
f"{APPNAME}: Warning - couldn't restore madTPG " |
| 13780 |
"'use fullscreen' button state" |
| 13781 |
) |
| 13782 |
if not reconnect: |
| 13783 |
if self.madtpg.is_fse_mode_enabled(): |
| 13784 |
# Allow three seconds for automatic switch to FSE |
| 13785 |
sleep(3) |
| 13786 |
# Allow three seconds for fullscreen to settle |
| 13787 |
sleep(3) |
| 13788 |
if restore_osd: |
| 13789 |
# Restore disable OSD |
| 13790 |
if self.madtpg.set_disable_osd_button(True): |
| 13791 |
self.log(f"{APPNAME}: Restored madTPG 'disable OSD' button state") |
| 13792 |
self.madtpg_osd = None |
| 13793 |
else: |
| 13794 |
self.log( |
| 13795 |
f"{APPNAME}: Warning - couldn't restore madTPG " |
| 13796 |
"'disable OSD' button state" |
| 13797 |
) |
| 13798 |
else: |
| 13799 |
buttons = [] |
| 13800 |
if restore_fullscreen: |
| 13801 |
buttons.append("'use fullscreen'") |
| 13802 |
if restore_osd: |
| 13803 |
buttons.append("'disable OSD'") |
| 13804 |
self.log( |
| 13805 |
f"{APPNAME}: Warning - couldn't re-connect to madTPG " |
| 13806 |
f"to restore {'/'.join(buttons)} button states" |
| 13807 |
) |
| 13808 |
|
| 13809 |
def madtpg_show_osd(self, msg=None, leave_fullscreen=False): |
| 13810 |
"""Show madTPG OSD, optionally with message and leaving fullscreen. |
| 13811 |
|
| 13812 |
Args: |
| 13813 |
msg (str): Message to show in OSD. If None, no message is shown. |
| 13814 |
leave_fullscreen (bool): If True, leave fullscreen mode if |
| 13815 |
currently in fullscreen mode. If False, stay in fullscreen |
| 13816 |
mode. |
| 13817 |
""" |
| 13818 |
if self.madtpg.is_fullscreen() and leave_fullscreen: |
| 13819 |
self.madtpg_previous_fullscreen = True |
| 13820 |
self.madtpg.set_use_fullscreen_button(False) |
| 13821 |
self.madtpg_osd = not self.madtpg.is_disable_osd_button_pressed() |
| 13822 |
if not self.madtpg_osd: |
| 13823 |
self.madtpg.set_disable_osd_button(False) |
| 13824 |
if msg: |
| 13825 |
self.madtpg.set_osd_text(msg) |
| 13826 |
if self.cmdname == "dispcal": |
| 13827 |
self.madtpg.show_progress_bar(6) |
| 13828 |
|
| 13829 |
def measure(self, apply_calibration: bool = True) -> bool | Exception: |
| 13830 |
"""Measure the configured testchart. |
| 13831 |
|
| 13832 |
Args: |
| 13833 |
apply_calibration (None | bool | str): If True, apply calibration |
| 13834 |
to the measurement. If False, use the raw measurement data. If |
| 13835 |
it is None or a string, it will be passed to the |
| 13836 |
`prepare_dispread` method to prepare the command for |
| 13837 |
measurement. |
| 13838 |
|
| 13839 |
Returns: |
| 13840 |
bool | Exception : True if successful, or an Exception if an error |
| 13841 |
occurred. |
| 13842 |
""" |
| 13843 |
result = self.detect_video_levels() |
| 13844 |
if isinstance(result, Exception) or not result: |
| 13845 |
return result |
| 13846 |
precond_ti1 = None |
| 13847 |
precond_ti3 = None |
| 13848 |
testchart_file = getcfg("testchart.file") |
| 13849 |
auto = getcfg("testchart.auto_optimize") or 7 |
| 13850 |
if testchart_file == "auto" and auto > 4: |
| 13851 |
# Testchart auto-optimization |
| 13852 |
# Create optimized testchart on-the-fly. To do this, create a |
| 13853 |
# simple profile for preconditioning |
| 13854 |
if config.get_display_name() == "Untethered": |
| 13855 |
return Error( |
| 13856 |
lang.getstr("testchart.auto_optimize.untethered.unsupported") |
| 13857 |
) |
| 13858 |
# Use small testchart for grayscale+primaries (34 patches) |
| 13859 |
precond_ti1_path = get_data_path("ti1/d3-e4-s2-g28-m0-b0-f0.ti1") |
| 13860 |
precond_ti1 = CGATS(precond_ti1_path) |
| 13861 |
setcfg("testchart.file", precond_ti1_path) |
| 13862 |
cmd, args = self.prepare_dispread(apply_calibration) |
| 13863 |
setcfg("testchart.file", "auto") |
| 13864 |
if not isinstance(cmd, Exception): |
| 13865 |
# Measure testchart |
| 13866 |
result = self.exec_cmd(cmd, args) |
| 13867 |
if not isinstance(result, Exception) and result: |
| 13868 |
# Create preconditioning profile |
| 13869 |
self.pauseable = False |
| 13870 |
basename = args[-1] |
| 13871 |
precond_ti3 = CGATS(f"{basename}.ti3") |
| 13872 |
precond_ti3.fix_zero_measurements(logfile=self.get_logfiles(False)) |
| 13873 |
precond_ti3.write() |
| 13874 |
# Extract grays and remaining colors |
| 13875 |
( |
| 13876 |
ti3_extracted, |
| 13877 |
ti3_RGB_XYZ, |
| 13878 |
ti3_remaining, |
| 13879 |
) = extract_device_gray_primaries(precond_ti3, True, self.log) |
| 13880 |
profile = self._create_simple_matrix_profile( |
| 13881 |
ti3_RGB_XYZ, ti3_remaining, os.path.basename(basename) |
| 13882 |
) |
| 13883 |
result = self._create_matrix_profile(basename, profile, omit="XYZ") |
| 13884 |
if not isinstance(result, Exception) and result: |
| 13885 |
# Write matrix profile |
| 13886 |
result.write(basename + PROFILE_EXT) |
| 13887 |
# Create optimized testchart |
| 13888 |
if getcfg("use_fancy_progress"): |
| 13889 |
# Fade out animation/sound |
| 13890 |
self.cmdname = get_argyll_utilname("targen") |
| 13891 |
# Allow time for fade out |
| 13892 |
sleep(4) |
| 13893 |
s = min(auto, 11) * 4 - 3 |
| 13894 |
g = s * 3 - 2 |
| 13895 |
f = get_total_patches(4, 4, s, g, auto, auto, 0) |
| 13896 |
f += 120 |
| 13897 |
cmd, args = ( |
| 13898 |
get_argyll_util("targen"), |
| 13899 |
[ |
| 13900 |
"-v", |
| 13901 |
"-d3", |
| 13902 |
"-e4", |
| 13903 |
f"-s{s:d}", |
| 13904 |
f"-g{g:d}", |
| 13905 |
"-m0", |
| 13906 |
f"-f{f:d}", |
| 13907 |
"-A1.0", |
| 13908 |
], |
| 13909 |
) |
| 13910 |
if self.argyll_version >= [1, 1]: |
| 13911 |
args.append("-G") |
| 13912 |
if self.argyll_version >= [1, 3, 3]: |
| 13913 |
args.append("-N0.5") |
| 13914 |
if self.argyll_version >= [1, 6]: |
| 13915 |
args.extend(["-B4", "-b0"]) |
| 13916 |
if self.argyll_version >= [1, 6, 2]: |
| 13917 |
args.append("-V1.6") |
| 13918 |
args.extend(["-c", basename + PROFILE_EXT, basename]) |
| 13919 |
result = self.exec_cmd(cmd, args) |
| 13920 |
self.pauseable = True |
| 13921 |
else: |
| 13922 |
result = cmd |
| 13923 |
else: |
| 13924 |
result = True |
| 13925 |
if testchart_file == "auto" and auto < 5: |
| 13926 |
# Use pre-baked testchart |
| 13927 |
if auto == 1: |
| 13928 |
testchart = "ti1/d3-e4-s2-g28-m0-b0-f0.ti1" |
| 13929 |
elif auto == 2: |
| 13930 |
testchart = "ti1/d3-e4-s3-g52-m3-b0-f0.ti1" |
| 13931 |
elif auto == 3: |
| 13932 |
testchart = "ti1/d3-e4-s4-g52-m4-b0-f0.ti1" |
| 13933 |
else: |
| 13934 |
testchart = "ti1/d3-e4-s5-g52-m5-b0-f0.ti1" |
| 13935 |
testchart_path = get_data_path(testchart) |
| 13936 |
if testchart_path: |
| 13937 |
setcfg("testchart.file", testchart_path) |
| 13938 |
else: |
| 13939 |
result = Error(lang.getstr("not_found", testchart)) |
| 13940 |
if not isinstance(result, Exception) and result: |
| 13941 |
cmd, args = self.prepare_dispread(apply_calibration) |
| 13942 |
if testchart_file == "auto": |
| 13943 |
# Restore "auto" setting |
| 13944 |
setcfg("testchart.file", "auto") |
| 13945 |
else: |
| 13946 |
cmd = result |
| 13947 |
if not isinstance(cmd, Exception) and cmd: |
| 13948 |
if config.get_display_name() == "Untethered": |
| 13949 |
cmd, args2 = get_argyll_util("spotread"), ["-v", "-e"] |
| 13950 |
if getcfg("extra_args.spotread").strip(): |
| 13951 |
args2 += parse_argument_string(getcfg("extra_args.spotread")) |
| 13952 |
result = self.add_measurement_features( |
| 13953 |
args2, False, allow_nondefault_observer=is_ccxx_testchart() |
| 13954 |
) |
| 13955 |
if isinstance(result, Exception): |
| 13956 |
return result |
| 13957 |
else: |
| 13958 |
args2 = args |
| 13959 |
result = self.exec_cmd(cmd, args2) |
| 13960 |
if not isinstance(result, Exception) and result: |
| 13961 |
self.update_display_name_manufacturer(args[-1] + ".ti3") |
| 13962 |
ti3 = args[-1] + ".ti3" |
| 13963 |
if precond_ti3: |
| 13964 |
# Add patches from preconditioning measurements |
| 13965 |
ti3 = insert_ti_patches_omitting_RGB_duplicates( |
| 13966 |
precond_ti3, ti3, self.log |
| 13967 |
) |
| 13968 |
options = { |
| 13969 |
"OBSERVER": get_cfg_option_from_args("observer", "-Q", args[:-1]) |
| 13970 |
} |
| 13971 |
ti3 = add_keywords_to_cgats(ti3, options) |
| 13972 |
if 1 in ti3: |
| 13973 |
# Add video level encoding flag if needed |
| 13974 |
black_white = False |
| 13975 |
if "-E" in args2: |
| 13976 |
black_white = (16, 235) |
| 13977 |
elif config.get_display_name() == "madVR": |
| 13978 |
# Get output encoding from madVR |
| 13979 |
# Note: 'tags' will only be True if creating profile |
| 13980 |
# directly after measurements, and only in that case will |
| 13981 |
# we want to query madVR |
| 13982 |
black_white = self.madtpg_bw_lvl |
| 13983 |
if black_white == (16, 235): |
| 13984 |
ti3[1].add_keyword("TV_OUTPUT_ENCODING", "YES") |
| 13985 |
elif black_white == (0, 255): |
| 13986 |
ti3[1].add_keyword("TV_OUTPUT_ENCODING", "NO") |
| 13987 |
elif black_white and black_white != (0, 255): |
| 13988 |
ti3[1].add_keyword( |
| 13989 |
"OUTPUT_ENCODING", " ".join(str(v) for v in black_white) |
| 13990 |
) |
| 13991 |
ti3.write() |
| 13992 |
# Restore original TI1 |
| 13993 |
ti1_orig = args[-1] + ".original.ti1" |
| 13994 |
ti1 = args[-1] + ".ti1" |
| 13995 |
if os.path.isfile(ti1_orig): |
| 13996 |
try: |
| 13997 |
if os.path.isfile(ti1): |
| 13998 |
# Should always exist |
| 13999 |
os.remove(ti1) |
| 14000 |
os.rename(ti1_orig, ti1) |
| 14001 |
except Exception as exception: |
| 14002 |
self.log( |
| 14003 |
"Warning - could not restore " |
| 14004 |
f"backup of original TI1 file {ti1_orig}:", |
| 14005 |
exception, |
| 14006 |
) |
| 14007 |
else: |
| 14008 |
self.log("Restored backup of original TI1 file") |
| 14009 |
if precond_ti1 and os.path.isfile(ti1): |
| 14010 |
# Need to add precond TI1 patches to TI1. |
| 14011 |
# Do this AFTER the measurements because we don't want to |
| 14012 |
# measure precond patches twice. |
| 14013 |
ti1 = insert_ti_patches_omitting_RGB_duplicates( |
| 14014 |
precond_ti1, ti1, self.log |
| 14015 |
) |
| 14016 |
ti1.write() |
| 14017 |
else: |
| 14018 |
result = cmd |
| 14019 |
result2 = self.wrapup( |
| 14020 |
not isinstance(result, UnloggedInfo) and result, |
| 14021 |
isinstance(result, Exception) or not result, |
| 14022 |
) |
| 14023 |
if isinstance(result2, Exception): |
| 14024 |
if isinstance(result, Exception): |
| 14025 |
result = Error(str(result) + "\n\n" + str(result2)) |
| 14026 |
else: |
| 14027 |
result = result2 |
| 14028 |
return result |
| 14029 |
|
| 14030 |
def ensure_patch_sequence(self, ti1, write=True): |
| 14031 |
"""Ensure correct patch sequence of TI1 file. |
| 14032 |
|
| 14033 |
Return either the changed CGATS object or the original path/TI1 |
| 14034 |
|
| 14035 |
Args: |
| 14036 |
ti1 (str or CGATS): Path to TI1 file or CGATS object. |
| 14037 |
write (bool): If True, write the modified TI1 back to the original |
| 14038 |
file. If False, return the modified CGATS object without writing. |
| 14039 |
|
| 14040 |
Returns: |
| 14041 |
str | CGATS: The modified CGATS object if the patch sequence was |
| 14042 |
changed, or the original path/TI1 if no changes were made. |
| 14043 |
""" |
| 14044 |
patch_sequence = getcfg("testchart.patch_sequence") |
| 14045 |
if patch_sequence != "optimize_display_response_delay": |
| 14046 |
# Need to re-order patches |
| 14047 |
if not isinstance(ti1, CGATS): |
| 14048 |
try: |
| 14049 |
ti1 = CGATS(ti1) |
| 14050 |
except Exception as exception: |
| 14051 |
self.log(f"Warning - could not process TI1 file {ti1}:", exception) |
| 14052 |
return ti1 |
| 14053 |
self.log( |
| 14054 |
"Changing patch sequence:", lang.getstr(f"testchart.{patch_sequence}") |
| 14055 |
) |
| 14056 |
if patch_sequence == "maximize_lightness_difference": |
| 14057 |
result = ti1.checkerboard(sort1=stable_sort_by_l) |
| 14058 |
elif patch_sequence == "maximize_rec709_luma_difference": |
| 14059 |
result = ti1.checkerboard(sort_by_rec709_luma) |
| 14060 |
elif patch_sequence == "maximize_RGB_difference": |
| 14061 |
result = ti1.checkerboard(sort_by_rgb_sum) |
| 14062 |
elif patch_sequence == "vary_RGB_difference": |
| 14063 |
result = ti1.checkerboard( |
| 14064 |
sort_by_rgb, None, split_grays=True, shift=True |
| 14065 |
) |
| 14066 |
if not result: |
| 14067 |
self.log("Warning - patch sequence was not changed") |
| 14068 |
elif write: |
| 14069 |
# Make a copy |
| 14070 |
try: |
| 14071 |
shutil.copyfile( |
| 14072 |
ti1.filename, |
| 14073 |
os.path.splitext(ti1.filename)[0] + ".original.ti1", |
| 14074 |
) |
| 14075 |
except Exception as exception: |
| 14076 |
self.log( |
| 14077 |
f"Warning - could not make backup of TI1 file {ti1.filename}:", |
| 14078 |
exception, |
| 14079 |
) |
| 14080 |
# Write new TI1 to original filename |
| 14081 |
try: |
| 14082 |
ti1.write() |
| 14083 |
except Exception as exception: |
| 14084 |
self.log( |
| 14085 |
f"Warning - could not write TI1 file {ti1.filename}:", |
| 14086 |
exception, |
| 14087 |
) |
| 14088 |
return ti1 |
| 14089 |
|
| 14090 |
def parse(self, txt): |
| 14091 |
"""Parse the command output and check for specific conditions. |
| 14092 |
|
| 14093 |
Args: |
| 14094 |
txt (str): Command output. |
| 14095 |
""" |
| 14096 |
if not txt: |
| 14097 |
return |
| 14098 |
self.logger.info(f"{txt}") |
| 14099 |
self.check_instrument_calibration(txt) |
| 14100 |
self.check_instrument_place_on_screen(txt) |
| 14101 |
self.check_instrument_sensor_position(txt) |
| 14102 |
self.check_retry_measurement(txt) |
| 14103 |
self.check_is_single_measurement(txt) |
| 14104 |
self.check_spotread_result(txt) |
| 14105 |
|
| 14106 |
def audio_visual_feedback(self, txt): |
| 14107 |
"""Provide audio/visual feedback based on the command output. |
| 14108 |
|
| 14109 |
Args: |
| 14110 |
txt (str): Command output. |
| 14111 |
""" |
| 14112 |
if isinstance(txt, bytes): |
| 14113 |
txt = txt.decode() |
| 14114 |
|
| 14115 |
if self.cmdname not in ( |
| 14116 |
get_argyll_utilname("dispcal"), |
| 14117 |
get_argyll_utilname("dispread"), |
| 14118 |
get_argyll_utilname("spotread"), |
| 14119 |
): |
| 14120 |
return |
| 14121 |
|
| 14122 |
if self.cmdname == get_argyll_utilname("dispcal") and ", repeat" in txt.lower(): |
| 14123 |
self.repeat = True |
| 14124 |
elif ", ok" in txt.lower(): |
| 14125 |
self.repeat = False |
| 14126 |
if ( |
| 14127 |
re.search(r"Patch [2-9]\d* of ", txt, re.I) |
| 14128 |
or ( |
| 14129 |
re.search( |
| 14130 |
r"Patch \d+ of |The instrument can be removed from the screen", |
| 14131 |
txt, |
| 14132 |
re.I, |
| 14133 |
) |
| 14134 |
and self.patch_count > 1 |
| 14135 |
) |
| 14136 |
or ( |
| 14137 |
"Result is XYZ:" in txt |
| 14138 |
and not isinstance(self.progress_wnd, UntetheredFrame) |
| 14139 |
) |
| 14140 |
): |
| 14141 |
if self.cmdname == get_argyll_utilname("dispcal") and self.repeat: |
| 14142 |
if getcfg("measurement.play_sound") and hasattr( |
| 14143 |
self.progress_wnd, "sound_on_off_btn" |
| 14144 |
): |
| 14145 |
self.measurement_sound.safe_play() |
| 14146 |
else: |
| 14147 |
if getcfg("measurement.play_sound") and ( |
| 14148 |
hasattr(self.progress_wnd, "sound_on_off_btn") |
| 14149 |
or isinstance(self.progress_wnd, DisplayUniformityFrame) |
| 14150 |
or getattr(self.progress_wnd, "Name", None) |
| 14151 |
== "VisualWhitepointEditor" |
| 14152 |
): |
| 14153 |
self.commit_sound.safe_play() |
| 14154 |
if hasattr(self.progress_wnd, "animbmp"): |
| 14155 |
self.progress_wnd.animbmp.frame = 0 |
| 14156 |
|
| 14157 |
def setup_patterngenerator(self, logfile=None): |
| 14158 |
"""Set up the pattern generator instance based on the current configuration. |
| 14159 |
|
| 14160 |
Args: |
| 14161 |
logfile (File, optional): Log file to use for the pattern generator. |
| 14162 |
""" |
| 14163 |
pgname = config.get_display_name(None, True) |
| 14164 |
if self.patterngenerator: |
| 14165 |
# Use existing pattern generator instance |
| 14166 |
self.patterngenerator.logfile = logfile |
| 14167 |
self.patterngenerator.use_video_levels = getcfg( |
| 14168 |
"patterngenerator.use_video_levels" |
| 14169 |
) |
| 14170 |
if hasattr(self.patterngenerator, "conn"): |
| 14171 |
# Try to use existing connection |
| 14172 |
try: |
| 14173 |
self.patterngenerator_send( |
| 14174 |
(0.5,) * 3, raise_exceptions=True, increase_sent_count=False |
| 14175 |
) |
| 14176 |
except (OSError, http.client.HTTPException) as exception: |
| 14177 |
self.log(exception) |
| 14178 |
self.patterngenerator.disconnect_client() |
| 14179 |
elif pgname == "Prisma": |
| 14180 |
patterngenerator = PrismaPatternGeneratorClient |
| 14181 |
self.patterngenerator = patterngenerator( |
| 14182 |
host=getcfg("patterngenerator.prisma.host"), |
| 14183 |
port=getcfg("patterngenerator.prisma.port"), |
| 14184 |
use_video_levels=getcfg("patterngenerator.use_video_levels"), |
| 14185 |
logfile=logfile, |
| 14186 |
) |
| 14187 |
elif pgname == "Web @ localhost": |
| 14188 |
patterngenerator = WebWinHTTPPatternGeneratorServer |
| 14189 |
self.patterngenerator = patterngenerator( |
| 14190 |
port=getcfg("webserver.portnumber"), logfile=logfile |
| 14191 |
) |
| 14192 |
elif pgname.startswith("Chromecast "): |
| 14193 |
from DisplayCAL.chromecast_pattern_generator import ( |
| 14194 |
ChromeCastPatternGenerator, |
| 14195 |
) |
| 14196 |
|
| 14197 |
self.patterngenerator = ChromeCastPatternGenerator( |
| 14198 |
name=self.get_display_name(), logfile=logfile |
| 14199 |
) |
| 14200 |
elif pgname == "Resolve": |
| 14201 |
# Resolve |
| 14202 |
if getcfg("patterngenerator.resolve") == "LS": |
| 14203 |
patterngenerator = ResolveLSPatternGeneratorServer |
| 14204 |
else: |
| 14205 |
patterngenerator = ResolveCMPatternGeneratorServer |
| 14206 |
self.patterngenerator = patterngenerator( |
| 14207 |
port=getcfg("patterngenerator.resolve.port"), |
| 14208 |
use_video_levels=getcfg("patterngenerator.use_video_levels"), |
| 14209 |
logfile=logfile, |
| 14210 |
) |
| 14211 |
|
| 14212 |
@property |
| 14213 |
def patterngenerator(self): |
| 14214 |
"""Return the current pattern generator instance. |
| 14215 |
|
| 14216 |
Returns: |
| 14217 |
PatternGenerator: Instance of a pattern generator class, such as |
| 14218 |
PrismaPatternGeneratorClient or |
| 14219 |
WebWinHTTPPatternGeneratorServer. |
| 14220 |
""" |
| 14221 |
pgname = config.get_display_name() |
| 14222 |
return self._patterngenerators.get(pgname) |
| 14223 |
|
| 14224 |
@patterngenerator.setter |
| 14225 |
def patterngenerator(self, patterngenerator): |
| 14226 |
"""Set the current pattern generator instance. |
| 14227 |
|
| 14228 |
Args: |
| 14229 |
patterngenerator (PatternGenerator): Instance of a pattern |
| 14230 |
generator class, such as PrismaPatternGeneratorClient or |
| 14231 |
WebWinHTTPPatternGeneratorServer. |
| 14232 |
""" |
| 14233 |
pgname = config.get_display_name() |
| 14234 |
self._patterngenerators[pgname] = patterngenerator |
| 14235 |
|
| 14236 |
@property |
| 14237 |
def patterngenerators(self): |
| 14238 |
"""Return all pattern generators. |
| 14239 |
|
| 14240 |
Returns: |
| 14241 |
dict: Dictionary of pattern generator instances, keyed by display |
| 14242 |
""" |
| 14243 |
return self._patterngenerators |
| 14244 |
|
| 14245 |
def patterngenerator_send( |
| 14246 |
self, rgb, bgrgb=None, raise_exceptions=False, increase_sent_count=True |
| 14247 |
): |
| 14248 |
"""Send RGB color to pattern generator. |
| 14249 |
|
| 14250 |
Args: |
| 14251 |
rgb (tuple): RGB color to send, as a tuple of three floats in the |
| 14252 |
range [0, 1]. |
| 14253 |
bgrgb (tuple, optional): Background RGB color to send, as a tuple |
| 14254 |
of three floats in the range [0, 1]. Defaults to None. |
| 14255 |
raise_exceptions (bool, optional): Whether to raise exceptions on |
| 14256 |
failure. Defaults to False. |
| 14257 |
increase_sent_count (bool, optional): Whether to increase the sent |
| 14258 |
count. Defaults to True. |
| 14259 |
|
| 14260 |
Returns: |
| 14261 |
None or Exception: Returns None if successful, or an Exception if |
| 14262 |
an error occurred. |
| 14263 |
""" |
| 14264 |
if getattr(self, "abort_requested", False): |
| 14265 |
return |
| 14266 |
x, y, w, h, size = get_pattern_geometry() |
| 14267 |
if bgrgb is not None: |
| 14268 |
pass |
| 14269 |
elif getcfg("measure.darken_background"): |
| 14270 |
bgrgb = (0, 0, 0) |
| 14271 |
elif size == 1.0: |
| 14272 |
bgrgb = list(rgb) |
| 14273 |
else: |
| 14274 |
# Constant APL (matches madTPG 'gamma light') |
| 14275 |
desired_apl = getcfg("patterngenerator.apl") |
| 14276 |
bgrgb = [min(max(desired_apl - v * size, 0) / (1.0 - size), 1) for v in rgb] |
| 14277 |
bgrgb_apl = sum(bgrgb) / 3.0 * (1 - size) |
| 14278 |
rgb_apl = sum(rgb) / 3.0 * size |
| 14279 |
needed_bgrgb_apl = max(desired_apl - rgb_apl, 0) |
| 14280 |
if bgrgb_apl > needed_bgrgb_apl: |
| 14281 |
f = needed_bgrgb_apl / bgrgb_apl |
| 14282 |
bgrgb = [v * f for v in bgrgb] |
| 14283 |
self.log( |
| 14284 |
f"{APPNAME}: Sending RGB {rgb[0]:.3f} {rgb[1]:.3f} {rgb[2]:.3f}, " |
| 14285 |
f"background RGB {bgrgb[0]:.3f} {bgrgb[1]:.3f} {bgrgb[2]:.3f}, " |
| 14286 |
f"x {x:.4f}, y {y:.4f}, w {w:.4f}, h {h:.4f}" |
| 14287 |
) |
| 14288 |
if self._use_patternwindow: |
| 14289 |
# Preliminary Wayland support. This still needs a lot |
| 14290 |
# of work as Argyll doesn't support Wayland natively yet, |
| 14291 |
# so we use virtual display to drive our own patch window. |
| 14292 |
self._patterngenerator_wait = True |
| 14293 |
wx.CallAfter(self.owner.measureframe.show_rgb, rgb) |
| 14294 |
# Wait for call to return |
| 14295 |
while self._patterngenerator_wait and not self.subprocess_abort: |
| 14296 |
sleep(0.001) |
| 14297 |
else: |
| 14298 |
try: |
| 14299 |
self.patterngenerator.send(rgb, bgrgb, x=x, y=y, w=w, h=h) |
| 14300 |
except Exception as exception: |
| 14301 |
if raise_exceptions: |
| 14302 |
raise |
| 14303 |
self.exec_cmd_returnvalue = exception |
| 14304 |
self.abort_subprocess() |
| 14305 |
return |
| 14306 |
if increase_sent_count: |
| 14307 |
self.patterngenerator_sent_count += 1 |
| 14308 |
self.log( |
| 14309 |
f"{APPNAME}: Patterngenerator sent count: " |
| 14310 |
f"{self.patterngenerator_sent_count:d}" |
| 14311 |
) |
| 14312 |
|
| 14313 |
@property |
| 14314 |
def pauseable(self): |
| 14315 |
"""Return whether the current measurement or calibration is pauseable. |
| 14316 |
|
| 14317 |
Returns: |
| 14318 |
bool: True if the current measurement or calibration is pauseable, |
| 14319 |
False otherwise. |
| 14320 |
""" |
| 14321 |
return self._pauseable |
| 14322 |
|
| 14323 |
@pauseable.setter |
| 14324 |
def pauseable(self, pauseable): |
| 14325 |
"""Set whether the current measurement or calibration is pauseable.""" |
| 14326 |
self._pauseable = pauseable |
| 14327 |
self.pauseable_now = False |
| 14328 |
|
| 14329 |
def pause_continue(self): |
| 14330 |
"""Pause or continue the current measurement or calibration.""" |
| 14331 |
if not self.pauseable or not self.pauseable_now: |
| 14332 |
return |
| 14333 |
if getattr(self.progress_wnd, "paused", False) and not getattr( |
| 14334 |
self, "paused", False |
| 14335 |
): |
| 14336 |
self.paused = True |
| 14337 |
self.log(f"{APPNAME}: Pausing...") |
| 14338 |
self.safe_send("\x1b") |
| 14339 |
if self.use_madnet_tpg: |
| 14340 |
self.madtpg.set_osd_text("\u23f8") # "Pause" symbol |
| 14341 |
elif not getattr(self.progress_wnd, "paused", False) and getattr( |
| 14342 |
self, "paused", False |
| 14343 |
): |
| 14344 |
self.paused = False |
| 14345 |
self.log(f"{APPNAME}: Continuing...") |
| 14346 |
self.safe_send(" ") |
| 14347 |
if self.use_madnet_tpg: |
| 14348 |
self.madtpg.set_osd_text("\u25b6") # "Play" symbol |
| 14349 |
|
| 14350 |
def prepare_colprof( |
| 14351 |
self, profile_name=None, display_name=None, display_manufacturer=None, tags=None |
| 14352 |
): |
| 14353 |
"""Prepare a colprof commandline. |
| 14354 |
|
| 14355 |
All options are read from the user configuration. Profile name and display |
| 14356 |
name can be overridden by passing thecorresponding arguments. |
| 14357 |
""" |
| 14358 |
if profile_name is None: |
| 14359 |
profile_name = getcfg("profile.name.expanded") |
| 14360 |
in_out_file = self.setup_inout(profile_name) |
| 14361 |
if not in_out_file or isinstance(in_out_file, Exception): |
| 14362 |
return in_out_file, None |
| 14363 |
if not os.path.exists(f"{in_out_file}.ti3"): |
| 14364 |
return ( |
| 14365 |
Error( |
| 14366 |
lang.getstr("error.measurement.file_missing", f"{in_out_file}.ti3") |
| 14367 |
), |
| 14368 |
None, |
| 14369 |
) |
| 14370 |
if not os.path.isfile(f"{in_out_file}.ti3"): |
| 14371 |
return Error(lang.getstr("file_notfile", f"{in_out_file}.ti3")), None |
| 14372 |
|
| 14373 |
cmd = get_argyll_util("colprof") |
| 14374 |
args = ["-v", f"-q{getcfg('profile.quality')}", f"-a{getcfg('profile.type')}"] |
| 14375 |
gamap_args = args |
| 14376 |
if getcfg("profile.type") in ["l", "x", "X"]: |
| 14377 |
if getcfg("gamap_saturation"): |
| 14378 |
gamap = "S" |
| 14379 |
elif getcfg("gamap_perceptual"): |
| 14380 |
gamap = "s" |
| 14381 |
else: |
| 14382 |
gamap = None |
| 14383 |
gamap_profile = None |
| 14384 |
if gamap and getcfg("gamap_profile"): |
| 14385 |
# CIECAM02 gamut mapping - perceptual and saturation tables |
| 14386 |
# Only for L*a*b* LUT or if source profile is not a simple matrix |
| 14387 |
# profile, otherwise create hires CIECAM02 tables with collink |
| 14388 |
try: |
| 14389 |
gamap_profile = ICCProfile(getcfg("gamap_profile")) |
| 14390 |
except ICCProfileInvalidError as exception: |
| 14391 |
self.log(exception) |
| 14392 |
return Error( |
| 14393 |
lang.getstr("profile.invalid") + "\n" + getcfg("gamap_profile") |
| 14394 |
) |
| 14395 |
except OSError as exception: |
| 14396 |
return exception |
| 14397 |
if ( |
| 14398 |
getcfg("profile.type") != "l" |
| 14399 |
and getcfg("profile.b2a.hires") |
| 14400 |
and "A2B0" not in gamap_profile.tags |
| 14401 |
and "rXYZ" in gamap_profile.tags |
| 14402 |
and "gXYZ" in gamap_profile.tags |
| 14403 |
and "bXYZ" in gamap_profile.tags |
| 14404 |
and "rTRC" in gamap_profile.tags |
| 14405 |
and "gTRC" in gamap_profile.tags |
| 14406 |
and "bTRC" in gamap_profile.tags |
| 14407 |
): |
| 14408 |
self.log("Delegating CIECAM02 gamut mapping to collink") |
| 14409 |
# Make a copy, so we can store options without adding them |
| 14410 |
# to actual colprof arguments |
| 14411 |
gamap_args = [] |
| 14412 |
gamap_profile = None |
| 14413 |
gamap_args.append(f"-{gamap}") |
| 14414 |
gamap_args.append(getcfg("gamap_profile")) |
| 14415 |
gamap_args.append(f"-t{getcfg('gamap_perceptual_intent')}") |
| 14416 |
if gamap == "S": |
| 14417 |
gamap_args.append(f"-T{getcfg('gamap_saturation_intent')}") |
| 14418 |
if getcfg("gamap_src_viewcond"): |
| 14419 |
gamap_args.append(f"-c{getcfg('gamap_src_viewcond')}") |
| 14420 |
if getcfg("gamap_out_viewcond"): |
| 14421 |
gamap_args.append(f"-d{getcfg('gamap_out_viewcond')}") |
| 14422 |
b2a_q = getcfg("profile.quality.b2a") |
| 14423 |
if ( |
| 14424 |
getcfg("profile.b2a.hires") |
| 14425 |
and getcfg("profile.type") in ("l", "x", "X") |
| 14426 |
and not (gamap and gamap_profile) |
| 14427 |
): |
| 14428 |
rgb = False |
| 14429 |
is_lab_clut_ptype = getcfg("profile.type") == "l" |
| 14430 |
if is_lab_clut_ptype: |
| 14431 |
with open(f"{in_out_file}.ti3", "rb") as ti3_file: |
| 14432 |
for line in ti3_file: |
| 14433 |
if line.startswith(b"COLOR_REP"): |
| 14434 |
if b"RGB_XYZ" in line: |
| 14435 |
rgb = True |
| 14436 |
break |
| 14437 |
if rgb or not is_lab_clut_ptype: |
| 14438 |
# Disable B2A creation in colprof, B2A is handled |
| 14439 |
# by A2B inversion code (only for cLUT profiles) |
| 14440 |
b2a_q = "n" |
| 14441 |
if b2a_q and b2a_q != getcfg("profile.quality"): |
| 14442 |
args.append(f"-b{b2a_q}") |
| 14443 |
args.append("-C") |
| 14444 |
args.append(getcfg("copyright").encode("ASCII", "asciize").decode("utf-8")) |
| 14445 |
if getcfg("extra_args.colprof").strip(): |
| 14446 |
args += parse_argument_string(getcfg("extra_args.colprof")) |
| 14447 |
options_dispcal = [] |
| 14448 |
if "-d3" in self.options_targen: |
| 14449 |
# only add display desc and dispcal options if creating RGB profile |
| 14450 |
options_dispcal = self.options_dispcal |
| 14451 |
if len(self.displays): |
| 14452 |
args.extend( |
| 14453 |
self.update_display_name_manufacturer( |
| 14454 |
f"{in_out_file}.ti3", |
| 14455 |
display_name, |
| 14456 |
display_manufacturer, |
| 14457 |
write=False, |
| 14458 |
) |
| 14459 |
) |
| 14460 |
self.options_colprof = list(args) |
| 14461 |
if gamap_args is not args: |
| 14462 |
self.options_colprof.extend(gamap_args) |
| 14463 |
args.append("-D") |
| 14464 |
args.append(profile_name) |
| 14465 |
args.append(in_out_file) |
| 14466 |
# Add dispcal and colprof arguments to ti3 |
| 14467 |
ti3 = add_options_to_ti3( |
| 14468 |
f"{in_out_file}.ti3", options_dispcal, self.options_colprof |
| 14469 |
) |
| 14470 |
if ti3: |
| 14471 |
color_rep = (ti3.queryv1("COLOR_REP").decode("utf-8") or "").split("_") |
| 14472 |
# Prepare ChromaticityType tag |
| 14473 |
self.log("Preparing ChromaticityType tag from TI3 colorants") |
| 14474 |
colorants = ti3.get_colorants() |
| 14475 |
if colorants and None not in colorants: |
| 14476 |
chrm = ChromaticityType() |
| 14477 |
chrm.type = 0 |
| 14478 |
for colorant in colorants: |
| 14479 |
if color_rep[1] == "LAB": |
| 14480 |
XYZ = colormath.Lab2XYZ( |
| 14481 |
colorant["LAB_L"], colorant["LAB_A"], colorant["LAB_B"] |
| 14482 |
) |
| 14483 |
else: |
| 14484 |
XYZ = (colorant["XYZ_X"], colorant["XYZ_Y"], colorant["XYZ_Z"]) |
| 14485 |
chrm.channels.append(colormath.XYZ2xyY(*XYZ)[:-1]) |
| 14486 |
with open(in_out_file + ".chrm", "wb") as blob: |
| 14487 |
blob.write(chrm.tagData) |
| 14488 |
self.log("Storing settings in TI3") |
| 14489 |
# Black point compensation |
| 14490 |
ti3[0].add_keyword( |
| 14491 |
"USE_BLACK_POINT_COMPENSATION", |
| 14492 |
"YES" if getcfg("profile.black_point_compensation") else "NO", |
| 14493 |
) |
| 14494 |
# Black point correction |
| 14495 |
# NOTE that profile black point correction is not the same as |
| 14496 |
# calibration black point correction! |
| 14497 |
# See Worker.create_profile |
| 14498 |
ti3[0].add_keyword( |
| 14499 |
"BLACK_POINT_CORRECTION", getcfg("profile.black_point_correction") |
| 14500 |
) |
| 14501 |
# Hires B2A with optional smoothing |
| 14502 |
ti3[0].add_keyword( |
| 14503 |
"HIRES_B2A", "YES" if getcfg("profile.b2a.hires") else "NO" |
| 14504 |
) |
| 14505 |
ti3[0].add_keyword("HIRES_B2A_SIZE", getcfg("profile.b2a.hires.size")) |
| 14506 |
ti3[0].add_keyword( |
| 14507 |
"SMOOTH_B2A", "YES" if getcfg("profile.b2a.hires.smooth") else "NO" |
| 14508 |
) |
| 14509 |
# Display update delay |
| 14510 |
if getcfg("measure.override_min_display_update_delay_ms"): |
| 14511 |
ti3[0].add_keyword( |
| 14512 |
"MIN_DISPLAY_UPDATE_DELAY_MS", |
| 14513 |
getcfg("measure.min_display_update_delay_ms"), |
| 14514 |
) |
| 14515 |
# Display settle time multiplier |
| 14516 |
if getcfg("measure.override_display_settle_time_mult"): |
| 14517 |
ti3[0].add_keyword( |
| 14518 |
"DISPLAY_SETTLE_TIME_MULT", |
| 14519 |
getcfg("measure.display_settle_time_mult"), |
| 14520 |
) |
| 14521 |
# FFP |
| 14522 |
if getcfg("patterngenerator.ffp_insertion"): |
| 14523 |
for keyword in ("INTERVAL", "DURATION", "LEVEL"): |
| 14524 |
ti3[0].add_keyword( |
| 14525 |
f"FFP_INSERTION_{keyword}", |
| 14526 |
getcfg(f"patterngenerator.ffp_insertion.{keyword.lower()}"), |
| 14527 |
) |
| 14528 |
# Remove AUTO_OPTIMIZE |
| 14529 |
if ti3[0].queryv1("AUTO_OPTIMIZE"): |
| 14530 |
ti3[0].remove_keyword("AUTO_OPTIMIZE") |
| 14531 |
# Patch sequence |
| 14532 |
ti3[0].add_keyword( |
| 14533 |
"PATCH_SEQUENCE", getcfg("testchart.patch_sequence").upper() |
| 14534 |
) |
| 14535 |
# Add 3D LUT options if set, else remove them |
| 14536 |
for keyword, cfgname in { |
| 14537 |
"3DLUT_SOURCE_PROFILE": "3dlut.input.profile", |
| 14538 |
"3DLUT_TRC": "3dlut.trc", |
| 14539 |
"3DLUT_HDR_PEAK_LUMINANCE": "3dlut.hdr_peak_luminance", |
| 14540 |
"3DLUT_HDR_SAT": "3dlut.hdr_sat", |
| 14541 |
"3DLUT_HDR_HUE": "3dlut.hdr_hue", |
| 14542 |
"3DLUT_HDR_MAXMLL": "3dlut.hdr_maxmll", |
| 14543 |
"3DLUT_HDR_MAXMLL_ALT_CLIP": "3dlut.hdr_maxmll_alt_clip", |
| 14544 |
"3DLUT_HDR_MINMLL": "3dlut.hdr_minmll", |
| 14545 |
"3DLUT_HDR_AMBIENT_LUMINANCE": "3dlut.hdr_ambient_luminance", |
| 14546 |
"3DLUT_HDR_DISPLAY": "3dlut.hdr_display", |
| 14547 |
"3DLUT_GAMMA": "3dlut.trc_gamma", |
| 14548 |
"3DLUT_DEGREE_OF_BLACK_OUTPUT_OFFSET": "3dlut.trc_output_offset", |
| 14549 |
"3DLUT_INPUT_ENCODING": "3dlut.encoding.input", |
| 14550 |
"3DLUT_OUTPUT_ENCODING": "3dlut.encoding.output", |
| 14551 |
"3DLUT_GAMUT_MAPPING_MODE": "3dlut.gamap.use_b2a", |
| 14552 |
"3DLUT_RENDERING_INTENT": "3dlut.rendering_intent", |
| 14553 |
"3DLUT_FORMAT": "3dlut.format", |
| 14554 |
"3DLUT_SIZE": "3dlut.size", |
| 14555 |
"3DLUT_INPUT_BITDEPTH": "3dlut.bitdepth.input", |
| 14556 |
"3DLUT_OUTPUT_BITDEPTH": "3dlut.bitdepth.output", |
| 14557 |
"3DLUT_APPLY_CAL": "3dlut.output.profile.apply_cal", |
| 14558 |
"SIMULATION_PROFILE": "measurement_report.simulation_profile", |
| 14559 |
}.items(): |
| 14560 |
if getcfg("3dlut.create"): |
| 14561 |
value = getcfg(cfgname) |
| 14562 |
if cfgname == "3dlut.gamap.use_b2a": |
| 14563 |
value = "g" if value else "G" |
| 14564 |
elif cfgname == "3dlut.trc_gamma": |
| 14565 |
if getcfg("3dlut.trc_gamma_type") == "B": |
| 14566 |
value = -value |
| 14567 |
elif ( |
| 14568 |
cfgname == "3dlut.input.profile" |
| 14569 |
and os.path.basename(os.path.dirname(value)) == "ref" |
| 14570 |
and get_data_path("ref/" + os.path.basename(value)) == value |
| 14571 |
): |
| 14572 |
# Store relative path instead of absolute path if |
| 14573 |
# ref file |
| 14574 |
value = "ref/" + os.path.basename(value) |
| 14575 |
elif cfgname == "measurement_report.simulation_profile": |
| 14576 |
if ( |
| 14577 |
getcfg("3dlut.trc").startswith("smpte2084") |
| 14578 |
or getcfg("3dlut.trc") == "hlg" |
| 14579 |
): |
| 14580 |
# Use 3D LUT profile |
| 14581 |
value = getcfg("3dlut.input.profile") |
| 14582 |
# Add 3D LUT HDR parameters and store only filename |
| 14583 |
# (file will be copied to profile dir) |
| 14584 |
fn, ext = os.path.splitext(os.path.basename(value)) |
| 14585 |
lut3d_fn = self.lut3d_get_filename(fn, False, False) |
| 14586 |
value = lut3d_fn + ext |
| 14587 |
else: |
| 14588 |
value = None |
| 14589 |
else: |
| 14590 |
value = None |
| 14591 |
if value is not None: |
| 14592 |
ti3[0].add_keyword(keyword, safe_str(value, "utf-8")) |
| 14593 |
elif keyword in ti3[0]: |
| 14594 |
ti3[0].remove_keyword(keyword) |
| 14595 |
# 3D LUT content color space (currently only used for HDR) |
| 14596 |
for color in ("white", "red", "green", "blue"): |
| 14597 |
for coord in "xy": |
| 14598 |
keyword = ( |
| 14599 |
f"3DLUT_CONTENT_COLORSPACE_{color.upper()}_{coord.upper()}" |
| 14600 |
) |
| 14601 |
if getcfg("3dlut.create"): |
| 14602 |
value = getcfg(f"3dlut.content.colorspace.{color}.{coord}") |
| 14603 |
ti3[0].add_keyword(keyword, safe_str(value, "utf-8")) |
| 14604 |
elif keyword in ti3[0]: |
| 14605 |
ti3[0].remove_keyword(keyword) |
| 14606 |
ti3[0].fix_zero_measurements(logfile=self.get_logfiles(False)) |
| 14607 |
ti3.write() |
| 14608 |
return cmd, args |
| 14609 |
|
| 14610 |
def prepare_dispcal(self, calibrate=True, verify=False, dry_run=False): |
| 14611 |
"""Prepare a dispcal commandline. |
| 14612 |
|
| 14613 |
All options are read from the user configuration. |
| 14614 |
You can choose if you want to calibrate and/or verify by passing |
| 14615 |
the corresponding arguments. |
| 14616 |
""" |
| 14617 |
cmd = get_argyll_util("dispcal") |
| 14618 |
args = ["-v2"] |
| 14619 |
if getcfg("argyll.debug"): |
| 14620 |
args.append("-D8") |
| 14621 |
result = self.add_measurement_features(args, allow_nondefault_observer=True) |
| 14622 |
if isinstance(result, Exception): |
| 14623 |
return result, None |
| 14624 |
if calibrate: |
| 14625 |
if getcfg("trc"): |
| 14626 |
args.append("-q" + getcfg("calibration.quality")) |
| 14627 |
inoutfile = self.setup_inout() |
| 14628 |
if not inoutfile or isinstance(inoutfile, Exception): |
| 14629 |
return inoutfile, None |
| 14630 |
if getcfg("profile.update") or self.dispcal_create_fast_matrix_shaper: |
| 14631 |
args.append("-o") |
| 14632 |
if getcfg("calibration.update") and not dry_run: |
| 14633 |
cal = getcfg("calibration.file", False) |
| 14634 |
calcopy = os.path.join(f"{inoutfile}.cal") |
| 14635 |
filename, ext = os.path.splitext(cal) |
| 14636 |
ext = ".cal" |
| 14637 |
cal = f"{filename}{ext}" |
| 14638 |
if ext.lower() == ".cal": |
| 14639 |
result = check_cal_isfile(cal) |
| 14640 |
if isinstance(result, Exception): |
| 14641 |
return result, None |
| 14642 |
if not result: |
| 14643 |
return None, None |
| 14644 |
if not os.path.exists(calcopy): |
| 14645 |
try: |
| 14646 |
# Copy cal to profile dir |
| 14647 |
shutil.copyfile(cal, calcopy) |
| 14648 |
except Exception as exception: |
| 14649 |
return ( |
| 14650 |
Error( |
| 14651 |
lang.getstr("error.copy_failed", (cal, calcopy)) |
| 14652 |
+ "\n\n" |
| 14653 |
+ str(exception) |
| 14654 |
), |
| 14655 |
None, |
| 14656 |
) |
| 14657 |
result = check_cal_isfile(calcopy) |
| 14658 |
if isinstance(result, Exception): |
| 14659 |
return result, None |
| 14660 |
if not result: |
| 14661 |
return None, None |
| 14662 |
cal = calcopy |
| 14663 |
else: |
| 14664 |
rslt = extract_fix_copy_cal(cal, calcopy) |
| 14665 |
if isinstance(rslt, ICCProfileInvalidError): |
| 14666 |
return Error(lang.getstr("profile.invalid") + "\n" + cal), None |
| 14667 |
if isinstance(rslt, Exception): |
| 14668 |
traceback.print_exc() |
| 14669 |
return ( |
| 14670 |
Error( |
| 14671 |
lang.getstr("cal_extraction_failed") |
| 14672 |
+ "\n" |
| 14673 |
+ cal |
| 14674 |
+ "\n\n" |
| 14675 |
+ rslt |
| 14676 |
), |
| 14677 |
None, |
| 14678 |
) |
| 14679 |
if not isinstance(rslt, list): |
| 14680 |
return None, None |
| 14681 |
if getcfg("profile.update"): |
| 14682 |
profile_path = ( |
| 14683 |
os.path.splitext(getcfg("calibration.file", False))[0] |
| 14684 |
+ PROFILE_EXT |
| 14685 |
) |
| 14686 |
result = check_profile_isfile(profile_path) |
| 14687 |
if isinstance(result, Exception): |
| 14688 |
return result, None |
| 14689 |
if not result: |
| 14690 |
return None, None |
| 14691 |
profilecopy = os.path.join(inoutfile + PROFILE_EXT) |
| 14692 |
if not os.path.exists(profilecopy): |
| 14693 |
try: |
| 14694 |
# Copy profile to profile dir |
| 14695 |
shutil.copyfile(profile_path, profilecopy) |
| 14696 |
except Exception as exception: |
| 14697 |
return ( |
| 14698 |
Error( |
| 14699 |
lang.getstr( |
| 14700 |
"error.copy_failed", (profile_path, profilecopy) |
| 14701 |
) |
| 14702 |
+ "\n\n" |
| 14703 |
+ str(exception) |
| 14704 |
), |
| 14705 |
None, |
| 14706 |
) |
| 14707 |
result = check_profile_isfile(profilecopy) |
| 14708 |
if isinstance(result, Exception): |
| 14709 |
return result, None |
| 14710 |
if not result: |
| 14711 |
return None, None |
| 14712 |
args.append("-u") |
| 14713 |
if calibrate or verify: |
| 14714 |
if calibrate and not getcfg("calibration.interactive_display_adjustment"): |
| 14715 |
# Skip interactive display adjustment |
| 14716 |
args.append("-m") |
| 14717 |
whitepoint_colortemp = getcfg("whitepoint.colortemp", False) |
| 14718 |
whitepoint_x = getcfg("whitepoint.x", False) |
| 14719 |
whitepoint_y = getcfg("whitepoint.y", False) |
| 14720 |
if whitepoint_colortemp or None in (whitepoint_x, whitepoint_y): |
| 14721 |
whitepoint = getcfg("whitepoint.colortemp.locus") |
| 14722 |
if whitepoint_colortemp: |
| 14723 |
whitepoint += str(whitepoint_colortemp) |
| 14724 |
args.append(f"-{whitepoint}") |
| 14725 |
else: |
| 14726 |
args.append(f"-w{whitepoint_x},{whitepoint_y}") |
| 14727 |
luminance = getcfg("calibration.luminance", False) |
| 14728 |
self.log(f"{APPNAME}: luminance: {luminance}") |
| 14729 |
if luminance is not None: |
| 14730 |
args.append(f"-b{luminance}") |
| 14731 |
if getcfg("trc"): |
| 14732 |
args.append("-{}{}".format(getcfg("trc.type"), getcfg("trc"))) |
| 14733 |
args.append("-f{}".format(getcfg("calibration.black_output_offset"))) |
| 14734 |
if bool(int(getcfg("calibration.ambient_viewcond_adjust"))): |
| 14735 |
# Argyll dispcal uses 20% of ambient (in lux, |
| 14736 |
# fixed steradiant of 3.1415) as adapting |
| 14737 |
# luminance, but we assume it already *is* |
| 14738 |
# the adapting luminance. To correct for this, |
| 14739 |
# scale so that dispcal gets the correct value. |
| 14740 |
ambient = getcfg("calibration.ambient_viewcond_adjust.lux") |
| 14741 |
args.append(f"-a{ambient * 5}") |
| 14742 |
if not getcfg("calibration.black_point_correction.auto"): |
| 14743 |
args.append( |
| 14744 |
"-k{}".format(getcfg("calibration.black_point_correction")) |
| 14745 |
) |
| 14746 |
if ( |
| 14747 |
DEFAULTS["calibration.black_point_rate.enabled"] |
| 14748 |
and float(getcfg("calibration.black_point_correction")) < 1 |
| 14749 |
): |
| 14750 |
black_point_rate = getcfg("calibration.black_point_rate") |
| 14751 |
if black_point_rate: |
| 14752 |
args.append(f"-A{black_point_rate}") |
| 14753 |
black_luminance = getcfg("calibration.black_luminance", False) |
| 14754 |
if black_luminance: |
| 14755 |
args.append(f"-B{black_luminance:f}") |
| 14756 |
elif ( |
| 14757 |
not ( |
| 14758 |
getcfg("calibration.black_point_correction.auto") |
| 14759 |
or getcfg("calibration.black_point_correction") |
| 14760 |
) |
| 14761 |
and DEFAULTS["calibration.black_point_hack"] |
| 14762 |
): |
| 14763 |
# Forced black point hack |
| 14764 |
# (Argyll CMS 1.7b 2014-12-22) |
| 14765 |
# Always use this if no black luminance or black point hue |
| 14766 |
# correction specified. The rationale is that a reasonably good |
| 14767 |
# quality digitally driven display should have no "dead zone" |
| 14768 |
# above zero device input if set up correctly. Using this option |
| 14769 |
# with a display that is not well behaved may result in a loss |
| 14770 |
# of shadow detail. |
| 14771 |
args.append("-b") |
| 14772 |
if verify: |
| 14773 |
if calibrate and isinstance(verify, int): |
| 14774 |
args.append(f"-e{verify}") # Verify final computed curves |
| 14775 |
elif self.argyll_version >= [1, 6]: |
| 14776 |
args.append("-z") # Verify current curves |
| 14777 |
else: |
| 14778 |
args.append("-E") # Verify current curves |
| 14779 |
if getcfg("extra_args.dispcal").strip(): |
| 14780 |
args += parse_argument_string(getcfg("extra_args.dispcal")) |
| 14781 |
if config.get_display_name() == "Resolve" or ( |
| 14782 |
config.get_display_name() == "Prisma" |
| 14783 |
and not DEFAULTS["patterngenerator.prisma.argyll"] |
| 14784 |
): |
| 14785 |
# Substitute actual measurement frame dimensions |
| 14786 |
self.options_dispcal = [ |
| 14787 |
re.sub( |
| 14788 |
r"^-[Pp]1,1,0.01$", "-P" + getcfg("dimensions.measureframe"), arg |
| 14789 |
) |
| 14790 |
for arg in args |
| 14791 |
] |
| 14792 |
# Re-add -F (darken background) so it can be set when loading settings |
| 14793 |
if getcfg("measure.darken_background"): |
| 14794 |
self.options_dispcal.append("-F") |
| 14795 |
else: |
| 14796 |
self.options_dispcal = list(args) |
| 14797 |
if calibrate: |
| 14798 |
args.append(inoutfile) |
| 14799 |
return cmd, args |
| 14800 |
|
| 14801 |
def prepare_dispread(self, apply_calibration=True): |
| 14802 |
"""Prepare a dispread commandline. |
| 14803 |
|
| 14804 |
All options are read from the user configuration. |
| 14805 |
You can choose if you want to apply the current calibration, |
| 14806 |
either the previously by dispcal created one by passing in True, by |
| 14807 |
passing in a valid path to a .cal file, or by passing in None |
| 14808 |
(current video card gamma table). |
| 14809 |
|
| 14810 |
Args: |
| 14811 |
apply_calibration (None | bool | str): If True, apply the current |
| 14812 |
calibration (i.e. the one created by dispcal). If a string, it |
| 14813 |
should be a path to a .cal file to apply. If None, use the |
| 14814 |
current video card gamma table. |
| 14815 |
""" |
| 14816 |
self.lastcmdname = get_argyll_utilname("dispread") |
| 14817 |
inoutfile = self.setup_inout() |
| 14818 |
if not inoutfile or isinstance(inoutfile, Exception): |
| 14819 |
return inoutfile, None |
| 14820 |
if not os.path.exists(f"{inoutfile}.ti1"): |
| 14821 |
filename, ext = os.path.splitext(getcfg("testchart.file")) |
| 14822 |
result = check_file_isfile(filename + ext) |
| 14823 |
if isinstance(result, Exception): |
| 14824 |
return result, None |
| 14825 |
try: |
| 14826 |
if ext.lower() in (".icc", ".icm"): |
| 14827 |
try: |
| 14828 |
profile = ICCProfile(filename + ext) |
| 14829 |
except (OSError, ICCProfileInvalidError): |
| 14830 |
return ( |
| 14831 |
Error( |
| 14832 |
lang.getstr( |
| 14833 |
"error.testchart.read", getcfg("testchart.file") |
| 14834 |
) |
| 14835 |
), |
| 14836 |
None, |
| 14837 |
) |
| 14838 |
ti3 = BytesIO( |
| 14839 |
profile.tags.get("CIED", b"") or profile.tags.get("targ", b"") |
| 14840 |
) |
| 14841 |
elif ext.lower() == ".ti1": |
| 14842 |
shutil.copyfile(f"{filename}{ext}", f"{inoutfile}.ti1") |
| 14843 |
else: # ti3 |
| 14844 |
try: |
| 14845 |
if ext.lower() != ".ti1": |
| 14846 |
with open(f"{filename}{ext}", "rb") as ti3: |
| 14847 |
ti3_lines = [line.strip() for line in ti3] |
| 14848 |
if b"CTI3" not in ti3_lines: |
| 14849 |
return ( |
| 14850 |
Error( |
| 14851 |
lang.getstr( |
| 14852 |
"error.testchart.invalid", |
| 14853 |
getcfg("testchart.file"), |
| 14854 |
) |
| 14855 |
), |
| 14856 |
None, |
| 14857 |
) |
| 14858 |
with open(f"{inoutfile}.ti1", "wb") as ti1: |
| 14859 |
ti1.write(ti3_to_ti1(ti3_lines)) |
| 14860 |
except Exception: |
| 14861 |
return ( |
| 14862 |
Error( |
| 14863 |
lang.getstr( |
| 14864 |
"error.testchart.read", getcfg("testchart.file") |
| 14865 |
) |
| 14866 |
), |
| 14867 |
None, |
| 14868 |
) |
| 14869 |
except Exception as exception: |
| 14870 |
localized_error_message = lang.getstr( |
| 14871 |
"error.testchart.creation_failed", f"{inoutfile}.ti1" |
| 14872 |
) |
| 14873 |
return ( |
| 14874 |
Error(f"{localized_error_message}\n\n{exception}"), |
| 14875 |
None, |
| 14876 |
) |
| 14877 |
if apply_calibration is not False: |
| 14878 |
if apply_calibration is True: |
| 14879 |
# Always a .cal file in that case |
| 14880 |
cal = ( |
| 14881 |
os.path.join( |
| 14882 |
getcfg("profile.save_path"), |
| 14883 |
getcfg("profile.name.expanded"), |
| 14884 |
getcfg("profile.name.expanded"), |
| 14885 |
) |
| 14886 |
+ ".cal" |
| 14887 |
) |
| 14888 |
elif apply_calibration is None: |
| 14889 |
# Use current videoLUT |
| 14890 |
cal = f"{inoutfile}.cal" |
| 14891 |
result = self.save_current_video_lut(self.get_display(), cal) |
| 14892 |
if isinstance(result, Exception) and not isinstance( |
| 14893 |
result, UnloggedInfo |
| 14894 |
): |
| 14895 |
return result, None |
| 14896 |
else: |
| 14897 |
cal = apply_calibration # can be .cal or .icc / .icm |
| 14898 |
calcopy = f"{inoutfile}.cal" |
| 14899 |
filename, ext = os.path.splitext(cal) |
| 14900 |
if getcfg("dry_run"): |
| 14901 |
options_dispcal = [] |
| 14902 |
elif ext.lower() == ".cal": |
| 14903 |
result = check_cal_isfile(cal) |
| 14904 |
if isinstance(result, Exception): |
| 14905 |
return result, None |
| 14906 |
if not result: |
| 14907 |
return None, None |
| 14908 |
# Get dispcal options if present |
| 14909 |
try: |
| 14910 |
options_dispcal = get_options_from_cal(cal)[0] |
| 14911 |
except ( |
| 14912 |
OSError, |
| 14913 |
CGATSInvalidError, |
| 14914 |
CGATSInvalidOperationError, |
| 14915 |
CGATSKeyError, |
| 14916 |
CGATSTypeError, |
| 14917 |
CGATSValueError, |
| 14918 |
) as exception: |
| 14919 |
return exception, None |
| 14920 |
if not os.path.exists(calcopy): |
| 14921 |
try: |
| 14922 |
# Copy cal to temp dir |
| 14923 |
shutil.copyfile(cal, calcopy) |
| 14924 |
except Exception as exception: |
| 14925 |
return ( |
| 14926 |
Error( |
| 14927 |
lang.getstr("error.copy_failed", (cal, calcopy)) |
| 14928 |
+ "\n\n" |
| 14929 |
+ str(exception) |
| 14930 |
), |
| 14931 |
None, |
| 14932 |
) |
| 14933 |
result = check_cal_isfile(calcopy) |
| 14934 |
if isinstance(result, Exception): |
| 14935 |
return result, None |
| 14936 |
if not result: |
| 14937 |
return None, None |
| 14938 |
else: |
| 14939 |
# .icc / .icm |
| 14940 |
result = check_profile_isfile(cal) |
| 14941 |
if isinstance(result, Exception): |
| 14942 |
return result, None |
| 14943 |
if not result: |
| 14944 |
return None, None |
| 14945 |
try: |
| 14946 |
profile = ICCProfile(filename + ext) |
| 14947 |
except (OSError, ICCProfileInvalidError): |
| 14948 |
profile = None |
| 14949 |
if profile: |
| 14950 |
ti3 = StringIO( |
| 14951 |
profile.tags.get("CIED", "") or profile.tags.get("targ", "") |
| 14952 |
) |
| 14953 |
# Get dispcal options if present |
| 14954 |
options_dispcal = get_options_from_profile(profile)[0] |
| 14955 |
else: |
| 14956 |
ti3 = StringIO("") |
| 14957 |
ti3_lines = [line.strip() for line in ti3] |
| 14958 |
ti3.close() |
| 14959 |
if "CTI3" not in ti3_lines: |
| 14960 |
return Error(lang.getstr("error.cal_extraction", (cal))), None |
| 14961 |
try: |
| 14962 |
with open(calcopy, "w") as tmpcal: |
| 14963 |
tmpcal.write(extract_cal_from_ti3(ti3_lines)) |
| 14964 |
except Exception as exception: |
| 14965 |
return ( |
| 14966 |
Error( |
| 14967 |
lang.getstr("error.cal_extraction", (cal)) |
| 14968 |
+ "\n\n" |
| 14969 |
+ str(exception) |
| 14970 |
), |
| 14971 |
None, |
| 14972 |
) |
| 14973 |
cal = calcopy |
| 14974 |
if options_dispcal: |
| 14975 |
self.options_dispcal = [f"-{arg}" for arg in options_dispcal] |
| 14976 |
# |
| 14977 |
# Make sure any measurement options are present |
| 14978 |
if not self.options_dispcal: |
| 14979 |
self.prepare_dispcal(dry_run=True) |
| 14980 |
# Special case -X because it can have a separate filename argument |
| 14981 |
if "-X" in self.options_dispcal: |
| 14982 |
index = self.options_dispcal.index("-X") |
| 14983 |
if ( |
| 14984 |
len(self.options_dispcal) > index + 1 |
| 14985 |
and self.options_dispcal[index + 1][0] != "-" |
| 14986 |
): |
| 14987 |
self.options_dispcal = ( |
| 14988 |
self.options_dispcal[:index] + self.options_dispcal[index + 2 :] |
| 14989 |
) |
| 14990 |
# Strip options we may override (basically all the stuff which can be |
| 14991 |
# added by add_measurement_features. -X is repeated because it can |
| 14992 |
# have a number instead of explicit filename argument, e.g. -X1) |
| 14993 |
dispcal_override_args = ( |
| 14994 |
"-F", |
| 14995 |
"-H", |
| 14996 |
"-I", |
| 14997 |
"-P", |
| 14998 |
"-V", |
| 14999 |
"-X", |
| 15000 |
"-d", |
| 15001 |
"-c", |
| 15002 |
"-p", |
| 15003 |
"-y", |
| 15004 |
) |
| 15005 |
self.options_dispcal = [ |
| 15006 |
arg for arg in self.options_dispcal if arg[:2] not in dispcal_override_args |
| 15007 |
] |
| 15008 |
# Only add the dispcal extra args which may override measurement features |
| 15009 |
dispcal_extra_args = parse_argument_string(getcfg("extra_args.dispcal")) |
| 15010 |
for i, arg in enumerate(dispcal_extra_args): |
| 15011 |
if not arg.startswith("-") and i > 0: |
| 15012 |
# Assume option to previous arg |
| 15013 |
arg = dispcal_extra_args[i - 1] |
| 15014 |
if arg[:2] in dispcal_override_args: |
| 15015 |
self.options_dispcal.append(dispcal_extra_args[i]) |
| 15016 |
result = self.add_measurement_features( |
| 15017 |
self.options_dispcal, ignore_display_name=True |
| 15018 |
) |
| 15019 |
if isinstance(result, Exception): |
| 15020 |
return result, None |
| 15021 |
cmd = get_argyll_util("dispread") |
| 15022 |
args = [] |
| 15023 |
args.append("-v") # verbose |
| 15024 |
if getcfg("argyll.debug"): |
| 15025 |
args.append("-D8") |
| 15026 |
result = self.add_measurement_features( |
| 15027 |
args, allow_nondefault_observer=is_ccxx_testchart(), quantize=True |
| 15028 |
) |
| 15029 |
if isinstance(result, Exception): |
| 15030 |
return result, None |
| 15031 |
if apply_calibration is not False: |
| 15032 |
if ( |
| 15033 |
self.argyll_version >= [1, 3, 3] |
| 15034 |
and ( |
| 15035 |
not self.has_lut_access() or not getcfg("calibration.use_video_lut") |
| 15036 |
) |
| 15037 |
# Only use -K if we don't use -d n,m (Linux X11) |
| 15038 |
and len(get_arg("-d", args)[1].split(",")) == 1 |
| 15039 |
): |
| 15040 |
# Apply calibration to test values directly instead of via |
| 15041 |
# videoLUT |
| 15042 |
args.append("-K") |
| 15043 |
else: |
| 15044 |
# Apply calibration via videoLUT (in special case of madVR, |
| 15045 |
# always applied to test values directly instead) |
| 15046 |
args.append("-k") |
| 15047 |
args.append(cal) |
| 15048 |
if self.get_instrument_features().get("spectral"): |
| 15049 |
args.append("-s") |
| 15050 |
if getcfg("extra_args.dispread").strip(): |
| 15051 |
args += parse_argument_string(getcfg("extra_args.dispread")) |
| 15052 |
self.options_dispread = list(args) |
| 15053 |
cgats = self.ensure_patch_sequence(inoutfile + ".ti1") |
| 15054 |
if getattr(self, "terminal", None) and isinstance( |
| 15055 |
self.terminal, UntetheredFrame |
| 15056 |
): |
| 15057 |
result = self.set_terminal_cgats(cgats) |
| 15058 |
if isinstance(result, Exception): |
| 15059 |
return result, None |
| 15060 |
return cmd, [*self.options_dispread, inoutfile] |
| 15061 |
|
| 15062 |
def prepare_dispwin(self, cal=None, profile_path=None, install=True): |
| 15063 |
"""Prepare a dispwin commandline. |
| 15064 |
|
| 15065 |
All options are read from the user configuration. |
| 15066 |
If you pass in cal as True, it will try to load the current |
| 15067 |
display profile's calibration. If cal is a path, it'll use |
| 15068 |
that instead. If cal is False, it'll clear the current calibration. |
| 15069 |
If cal is None, it'll try to load the calibration from a profile |
| 15070 |
specified by profile_path. |
| 15071 |
|
| 15072 |
""" |
| 15073 |
cmd = get_argyll_util("dispwin") |
| 15074 |
args = [] |
| 15075 |
args.append("-v") |
| 15076 |
if getcfg("argyll.debug"): |
| 15077 |
if self.argyll_version >= [1, 3, 1]: |
| 15078 |
args.append("-D8") |
| 15079 |
else: |
| 15080 |
args.append("-E8") |
| 15081 |
args.append("-d" + self.get_display()) |
| 15082 |
if sys.platform != "darwin" or cal is False: |
| 15083 |
# Mac OS X 10.7 Lion needs root privileges when clearing |
| 15084 |
# calibration |
| 15085 |
args.append("-c") |
| 15086 |
if cal is True: |
| 15087 |
args.append( |
| 15088 |
self.get_dispwin_display_profile_argument( |
| 15089 |
max(0, min(len(self.displays), getcfg("display.number")) - 1) |
| 15090 |
) |
| 15091 |
) |
| 15092 |
elif cal: |
| 15093 |
result = check_cal_isfile(cal) |
| 15094 |
if isinstance(result, Exception): |
| 15095 |
return result, None |
| 15096 |
if not result: |
| 15097 |
return None, None |
| 15098 |
args.append(cal) |
| 15099 |
elif cal is None: |
| 15100 |
if not profile_path: |
| 15101 |
profile_save_path = os.path.join( |
| 15102 |
getcfg("profile.save_path"), getcfg("profile.name.expanded") |
| 15103 |
) |
| 15104 |
profile_path = os.path.join( |
| 15105 |
profile_save_path, getcfg("profile.name.expanded") + PROFILE_EXT |
| 15106 |
) |
| 15107 |
result = check_profile_isfile(profile_path) |
| 15108 |
if isinstance(result, Exception): |
| 15109 |
return result, None |
| 15110 |
if not result: |
| 15111 |
return None, None |
| 15112 |
try: |
| 15113 |
profile = ICCProfile(profile_path) |
| 15114 |
except (OSError, ICCProfileInvalidError): |
| 15115 |
return ( |
| 15116 |
Error(lang.getstr("profile.invalid") + "\n" + profile_path), |
| 15117 |
None, |
| 15118 |
) |
| 15119 |
if profile.profileClass != b"mntr" or profile.colorSpace != b"RGB": |
| 15120 |
return ( |
| 15121 |
Error( |
| 15122 |
lang.getstr( |
| 15123 |
"profile.unsupported", |
| 15124 |
( |
| 15125 |
profile.profileClass.decode("utf-8"), |
| 15126 |
profile.colorSpace.decode("utf-8"), |
| 15127 |
), |
| 15128 |
) |
| 15129 |
+ "\n" |
| 15130 |
+ profile_path |
| 15131 |
), |
| 15132 |
None, |
| 15133 |
) |
| 15134 |
if install: |
| 15135 |
if getcfg("profile.install_scope") != "u" and ( |
| 15136 |
( |
| 15137 |
( |
| 15138 |
sys.platform == "darwin" |
| 15139 |
or ( |
| 15140 |
sys.platform != "win32" |
| 15141 |
and self.argyll_version >= [1, 1, 0] |
| 15142 |
) |
| 15143 |
) |
| 15144 |
and (os.geteuid() == 0 or which("sudo")) |
| 15145 |
) |
| 15146 |
or ( |
| 15147 |
sys.platform == "win32" |
| 15148 |
and sys.getwindowsversion() >= (6,) |
| 15149 |
and self.argyll_version > [1, 1, 1] |
| 15150 |
) |
| 15151 |
): |
| 15152 |
# -S option is broken on Linux with current Argyll |
| 15153 |
# releases |
| 15154 |
args.append("-S" + getcfg("profile.install_scope")) |
| 15155 |
else: |
| 15156 |
# Make sure user profile dir exists |
| 15157 |
# (e.g. on Mac OS X 10.9 Mavericks, it does not by |
| 15158 |
# default) |
| 15159 |
for profile_dir in reversed(defaultpaths.ICCPROFILES_HOME): |
| 15160 |
if os.path.isdir(profile_dir): |
| 15161 |
break |
| 15162 |
if not os.path.isdir(profile_dir): |
| 15163 |
try: |
| 15164 |
os.makedirs(profile_dir) |
| 15165 |
except OSError as exception: |
| 15166 |
return exception, None |
| 15167 |
args.append("-I") |
| 15168 |
# Always copy to temp dir so if a user accidentally tries |
| 15169 |
# to install a profile from the location where it's already |
| 15170 |
# installed (e.g. system32/spool/drivers/color) it doesn't |
| 15171 |
# get nuked by dispwin |
| 15172 |
tmp_dir = self.create_tempdir() |
| 15173 |
if not tmp_dir or isinstance(tmp_dir, Exception): |
| 15174 |
return tmp_dir, None |
| 15175 |
# Check directory and in/output file(s) |
| 15176 |
result = check_create_dir(tmp_dir) |
| 15177 |
if isinstance(result, Exception): |
| 15178 |
return result, None |
| 15179 |
profile_name = os.path.basename(profile_path) |
| 15180 |
if ( |
| 15181 |
sys.platform in ("win32", "darwin") |
| 15182 |
or FS_ENC.upper() not in ("UTF8", "UTF-8") |
| 15183 |
) and re.search(r"[^\x20-\x7e]", profile_name): |
| 15184 |
# Copy to temp dir and give ASCII-only name to |
| 15185 |
# avoid profile install issues |
| 15186 |
profile_tmp_path = os.path.join( |
| 15187 |
tmp_dir, |
| 15188 |
safe_asciize(profile_name).decode("utf-8", "ignore"), |
| 15189 |
) |
| 15190 |
else: |
| 15191 |
profile_tmp_path = os.path.join(tmp_dir, profile_name) |
| 15192 |
shutil.copyfile(profile_path, profile_tmp_path) |
| 15193 |
profile_path = profile_tmp_path |
| 15194 |
args.append(profile_path) |
| 15195 |
return cmd, args |
| 15196 |
|
| 15197 |
def prepare_targen(self): |
| 15198 |
"""Prepare a targen commandline. |
| 15199 |
|
| 15200 |
All options are read from the user configuration. |
| 15201 |
|
| 15202 |
""" |
| 15203 |
path = self.create_tempdir() |
| 15204 |
if not path or isinstance(path, Exception): |
| 15205 |
return path, None |
| 15206 |
# Check directory and in/output file(s) |
| 15207 |
result = check_create_dir(path) |
| 15208 |
if isinstance(result, Exception): |
| 15209 |
return result, None |
| 15210 |
inoutfile = os.path.join(path, "temp") |
| 15211 |
cmd = get_argyll_util("targen") |
| 15212 |
args = [] |
| 15213 |
args.append("-v") |
| 15214 |
args.append("-d3") |
| 15215 |
args.append("-e{}".format(getcfg("tc_white_patches"))) |
| 15216 |
if self.argyll_version >= [1, 6]: |
| 15217 |
args.append("-B{}".format(getcfg("tc_black_patches"))) |
| 15218 |
args.append("-s{}".format(getcfg("tc_single_channel_patches"))) |
| 15219 |
args.append("-g{}".format(getcfg("tc_gray_patches"))) |
| 15220 |
args.append("-m{}".format(getcfg("tc_multi_steps"))) |
| 15221 |
if self.argyll_version >= [1, 6, 0]: |
| 15222 |
args.append("-b{}".format(getcfg("tc_multi_bcc_steps"))) |
| 15223 |
tc_algo = getcfg("tc_algo") |
| 15224 |
if getcfg("tc_fullspread_patches") > 0: |
| 15225 |
args.append(f"-f{config.get_total_patches()}") |
| 15226 |
if tc_algo: |
| 15227 |
args.append("-" + tc_algo) |
| 15228 |
if tc_algo in ("i", "I"): |
| 15229 |
args.append("-a{}".format(getcfg("tc_angle"))) |
| 15230 |
if tc_algo == "": |
| 15231 |
args.append("-A{}".format(getcfg("tc_adaption"))) |
| 15232 |
if self.argyll_version >= [1, 3, 3]: |
| 15233 |
args.append("-N{}".format(getcfg("tc_neutral_axis_emphasis"))) |
| 15234 |
if self.argyll_version == [1, 1, "RC1"] or self.argyll_version >= [1, 1]: |
| 15235 |
args.append("-G") |
| 15236 |
else: |
| 15237 |
args.append("-f0") |
| 15238 |
if getcfg("tc_precond") and getcfg("tc_precond_profile"): |
| 15239 |
args.append("-c") |
| 15240 |
args.append(getcfg("tc_precond_profile")) |
| 15241 |
if getcfg("tc_filter"): |
| 15242 |
args.append( |
| 15243 |
"-F{},{},{},{}".format( |
| 15244 |
getcfg("tc_filter_L"), |
| 15245 |
getcfg("tc_filter_a"), |
| 15246 |
getcfg("tc_filter_b"), |
| 15247 |
getcfg("tc_filter_rad"), |
| 15248 |
) |
| 15249 |
) |
| 15250 |
if self.argyll_version >= [1, 6, 2] and ( |
| 15251 |
"-c" in args or self.argyll_version >= [1, 6, 3] |
| 15252 |
): |
| 15253 |
args.append("-V{}".format(1 + getcfg("tc_dark_emphasis") * 3)) |
| 15254 |
if self.argyll_version == [1, 1, "RC2"] or self.argyll_version >= [1, 1]: |
| 15255 |
args.append("-p{}".format(getcfg("tc_gamma"))) |
| 15256 |
if getcfg("extra_args.targen").strip(): |
| 15257 |
# Disallow -d and -D as the testchart editor only supports |
| 15258 |
# video RGB (-d3) |
| 15259 |
args += [ |
| 15260 |
arg |
| 15261 |
for arg in parse_argument_string(getcfg("extra_args.targen")) |
| 15262 |
if not arg.lower().startswith("-d") |
| 15263 |
] |
| 15264 |
self.options_targen = list(args) |
| 15265 |
args.append(inoutfile) |
| 15266 |
return cmd, args |
| 15267 |
|
| 15268 |
def progress_handler(self, event): |
| 15269 |
"""Handle progress dialog updates and react to Argyll CMS command output.""" |
| 15270 |
if getattr(self, "subprocess_abort", False) or getattr( |
| 15271 |
self, "thread_abort", False |
| 15272 |
): |
| 15273 |
self.progress_wnd.Pulse(lang.getstr("aborting")) |
| 15274 |
return |
| 15275 |
percentage = None |
| 15276 |
msg = self.recent.read(FilteredStream.triggers) |
| 15277 |
lastmsg = self.lastmsg.read(FilteredStream.triggers).strip() |
| 15278 |
warning = r"\D+: Warning -.*" |
| 15279 |
msg = re.sub(warning, "", msg) |
| 15280 |
lastmsg = re.sub(warning, "", lastmsg) |
| 15281 |
# Filter for '=' so that 1% reading during calibration check |
| 15282 |
# measurements doesn't trigger swapping from the interactive adjustment |
| 15283 |
# to the progress window |
| 15284 |
if re.match(r"\s*\d+%\s*(?:[^=]+)?$", lastmsg): |
| 15285 |
# colprof, download progress |
| 15286 |
with contextlib.suppress(ValueError): |
| 15287 |
percentage = int(self.lastmsg.read().split("%")[0]) |
| 15288 |
elif re.match(r"Patch \d+ of \d+", lastmsg, re.I): |
| 15289 |
# dispcal/dispread |
| 15290 |
components = lastmsg.split() |
| 15291 |
try: |
| 15292 |
start = float(components[1]) |
| 15293 |
end = float(components[3]) |
| 15294 |
except ValueError: |
| 15295 |
pass |
| 15296 |
else: |
| 15297 |
percentage = max(start - 1, 0) / end * 100 |
| 15298 |
elif re.match(r"Added \d+/\d+", lastmsg, re.I): |
| 15299 |
# targen |
| 15300 |
components = lastmsg.lower().replace("added ", "").split("/") |
| 15301 |
try: |
| 15302 |
start = float(components[0]) |
| 15303 |
end = float(components[1]) |
| 15304 |
except ValueError: |
| 15305 |
pass |
| 15306 |
else: |
| 15307 |
percentage = start / end * 100 |
| 15308 |
else: |
| 15309 |
iteration = re.search(r"It (\d+):", msg) |
| 15310 |
if iteration: |
| 15311 |
# targen |
| 15312 |
try: |
| 15313 |
start = float(iteration.groups()[0]) |
| 15314 |
except ValueError: |
| 15315 |
pass |
| 15316 |
else: |
| 15317 |
end = 20 |
| 15318 |
percentage = min(start, 20.0) / end * 100 |
| 15319 |
lastmsg = "" |
| 15320 |
if ( |
| 15321 |
percentage is not None |
| 15322 |
and time() > self.starttime + 3 |
| 15323 |
and self.progress_wnd is getattr(self, "terminal", None) |
| 15324 |
and not self._detecting_video_levels |
| 15325 |
and not getattr(getattr(self, "terminal", None), "is_measuring", False) |
| 15326 |
): |
| 15327 |
# We no longer need keyboard interaction, switch over to |
| 15328 |
# progress dialog |
| 15329 |
wx.CallAfter(self.swap_progress_wnds) |
| 15330 |
self.set_progress_type() |
| 15331 |
if ( |
| 15332 |
getattr(self.progress_wnd, "original_msg", None) |
| 15333 |
and msg != self.progress_wnd.original_msg |
| 15334 |
): |
| 15335 |
# UGLY HACK: This 'print' call fixes a GTK assertion and |
| 15336 |
# segfault under Arch Linux when setting the window title. |
| 15337 |
# This has a chance of throwing a IOError: [Errno 9] Bad file |
| 15338 |
# descriptor under Windows, so check for wxGTK |
| 15339 |
if "__WXGTK__" in wx.PlatformInfo: |
| 15340 |
print("") |
| 15341 |
self.progress_wnd.SetTitle(self.progress_wnd.original_msg) |
| 15342 |
self.progress_wnd.original_msg = None |
| 15343 |
if percentage is not None: |
| 15344 |
if ( |
| 15345 |
"Setting up the instrument" in msg |
| 15346 |
or "Commencing device calibration" in msg |
| 15347 |
or "Commencing display calibration" in msg |
| 15348 |
or "Calibration complete" in msg |
| 15349 |
): |
| 15350 |
self.recent.clear() |
| 15351 |
msg = "" |
| 15352 |
keepGoing, skip = self.progress_wnd.UpdateProgress( |
| 15353 |
max(min(percentage, 100), 0), msg + "\n" + lastmsg |
| 15354 |
) |
| 15355 |
elif re.match(r"\d+(?:\.\d+)? (?:[KM]iB)", lastmsg, re.I): |
| 15356 |
keepGoing, skip = self.progress_wnd.Pulse(f"{msg}\n{lastmsg}") |
| 15357 |
elif getattr(self.progress_wnd, "lastmsg", "") == msg or not msg: |
| 15358 |
keepGoing, skip = self.progress_wnd.Pulse() |
| 15359 |
else: |
| 15360 |
if "Setting up the instrument" in lastmsg: |
| 15361 |
msg = lang.getstr("instrument.initializing") |
| 15362 |
elif "Created web server at" in msg: |
| 15363 |
webserver = re.search(r"(http\:\/\/[^']+)", msg) |
| 15364 |
if webserver: |
| 15365 |
msg = lang.getstr("webserver.waiting") + " " + webserver.groups()[0] |
| 15366 |
keepGoing, skip = self.progress_wnd.Pulse(msg) |
| 15367 |
self.pause_continue() |
| 15368 |
if hasattr(self.progress_wnd, "pause_continue"): |
| 15369 |
if "read stopped at user request!" in lastmsg: |
| 15370 |
self.progress_wnd.pause_continue.Enable() |
| 15371 |
if self.progress_wnd.pause_continue.IsShown() != self.pauseable: |
| 15372 |
self.progress_wnd.pause_continue.Show(self.pauseable) |
| 15373 |
self.progress_wnd.Layout() |
| 15374 |
if not keepGoing and not getattr(self, "abort_requested", False): |
| 15375 |
# Only confirm abort if we are not currently doing interactive |
| 15376 |
# display adjustment |
| 15377 |
self.abort_subprocess( |
| 15378 |
not isinstance(self._progress_wnd, DisplayAdjustmentFrame) |
| 15379 |
) |
| 15380 |
if self.finished is True: |
| 15381 |
return |
| 15382 |
if ( |
| 15383 |
self.progress_wnd.IsShownOnScreen() |
| 15384 |
and not self.progress_wnd.IsActive() |
| 15385 |
and ( |
| 15386 |
not getattr(self.progress_wnd, "dlg", None) |
| 15387 |
or not self.progress_wnd.dlg.IsShownOnScreen() |
| 15388 |
) |
| 15389 |
and wx.GetApp().GetTopWindow() |
| 15390 |
and wx.GetApp().GetTopWindow().IsShownOnScreen() |
| 15391 |
and ( |
| 15392 |
wx.GetApp().IsActive() |
| 15393 |
or (sys.platform == "darwin" and not self.activated) |
| 15394 |
) |
| 15395 |
): |
| 15396 |
for window in list(wx.GetTopLevelWindows()): |
| 15397 |
if ( |
| 15398 |
window |
| 15399 |
and window is not self.progress_wnd |
| 15400 |
and isinstance(window, wx.Dialog) |
| 15401 |
and window.IsShownOnScreen() |
| 15402 |
): |
| 15403 |
return |
| 15404 |
self.activated = True |
| 15405 |
self.progress_wnd.Raise() |
| 15406 |
|
| 15407 |
def progress_dlg_start( |
| 15408 |
self, progress_title="", progress_msg="", parent=None, resume=False, fancy=True |
| 15409 |
): |
| 15410 |
"""Start a progress dialog, replacing existing one if present.""" |
| 15411 |
if self._progress_wnd and self.progress_wnd is getattr(self, "terminal", None): |
| 15412 |
self.terminal.stop_timer() |
| 15413 |
self.terminal.Hide() |
| 15414 |
if self.finished is True: |
| 15415 |
return |
| 15416 |
fancy = fancy and getcfg("use_fancy_progress") |
| 15417 |
if ( |
| 15418 |
resume |
| 15419 |
and self._progress_wnd |
| 15420 |
and self._progress_wnd in list(self._progress_dlgs.values()) |
| 15421 |
): |
| 15422 |
progress_wnd = self._progress_wnd |
| 15423 |
else: |
| 15424 |
key = ( |
| 15425 |
self.show_remaining_time, |
| 15426 |
self.cancelable, |
| 15427 |
fancy, |
| 15428 |
parent, |
| 15429 |
parent and parent.IsShownOnScreen(), |
| 15430 |
) |
| 15431 |
progress_wnd = self._progress_dlgs.get(key) |
| 15432 |
if progress_wnd: |
| 15433 |
if self._progress_wnd is not progress_wnd: |
| 15434 |
self.progress_wnd = progress_wnd |
| 15435 |
# UGLY HACK: This 'print' call fixes a GTK assertion and |
| 15436 |
# segfault under Arch Linux when setting the window title |
| 15437 |
# This has a chance of throwing a IOError: [Errno 9] Bad file |
| 15438 |
# descriptor under Windows, so check for wxGTK |
| 15439 |
if "__WXGTK__" in wx.PlatformInfo: |
| 15440 |
print("") |
| 15441 |
self.progress_wnd.SetTitle(progress_title) |
| 15442 |
if not resume or not self.progress_wnd.IsShown(): |
| 15443 |
self.progress_wnd.reset() |
| 15444 |
self.progress_wnd.Pulse(progress_msg) |
| 15445 |
if hasattr(self.progress_wnd, "pause_continue"): |
| 15446 |
self.progress_wnd.pause_continue.Show(self.pauseable) |
| 15447 |
self.progress_wnd.Layout() |
| 15448 |
self.progress_wnd.Resume() |
| 15449 |
if not self.progress_wnd.IsShownOnScreen(): |
| 15450 |
self.progress_wnd.place() |
| 15451 |
self.progress_wnd.Show() |
| 15452 |
else: |
| 15453 |
style = wx.PD_SMOOTH | wx.PD_ELAPSED_TIME |
| 15454 |
if self.show_remaining_time: |
| 15455 |
style |= wx.PD_REMAINING_TIME |
| 15456 |
if self.cancelable: |
| 15457 |
style |= wx.PD_CAN_ABORT |
| 15458 |
# Set maximum to 101 to prevent the 'cancel' changing to 'close' |
| 15459 |
# when 100 is reached |
| 15460 |
self._progress_dlgs[key] = ProgressDialog( |
| 15461 |
progress_title, |
| 15462 |
progress_msg, |
| 15463 |
maximum=101, |
| 15464 |
parent=parent, |
| 15465 |
handler=self.progress_handler, |
| 15466 |
keyhandler=self.terminal_key_handler, |
| 15467 |
pauseable=self.pauseable, |
| 15468 |
style=style, |
| 15469 |
start_timer=False, |
| 15470 |
fancy=fancy, |
| 15471 |
) |
| 15472 |
self.progress_wnd = self._progress_dlgs[key] |
| 15473 |
self.set_progress_type() |
| 15474 |
if not self.progress_wnd.timer.IsRunning(): |
| 15475 |
self.progress_wnd.start_timer() |
| 15476 |
self.progress_wnd.original_msg = progress_msg |
| 15477 |
|
| 15478 |
def set_progress_type(self): |
| 15479 |
"""Set progress type for fancy progress dialog.""" |
| 15480 |
if hasattr(self.progress_wnd, "progress_type"): |
| 15481 |
if self.pauseable or getattr(self, "interactive_frame", "") in ( |
| 15482 |
"ambient", |
| 15483 |
"luminance", |
| 15484 |
): |
| 15485 |
# If pauseable, we assume it's a measurement |
| 15486 |
progress_type = 1 # Measuring |
| 15487 |
elif self.cmdname == get_argyll_utilname("targen"): |
| 15488 |
progress_type = 2 # Generating test patches |
| 15489 |
else: |
| 15490 |
progress_type = 0 # Processing |
| 15491 |
if self.progress_wnd.progress_type != progress_type: |
| 15492 |
if self.progress_wnd.timer.IsRunning(): |
| 15493 |
# Fade-out current progress type, fade-in new one |
| 15494 |
self.progress_wnd.set_progress_type(progress_type) |
| 15495 |
else: |
| 15496 |
# Not yet running, just set initial progress type |
| 15497 |
self.progress_wnd.progress_type = progress_type |
| 15498 |
|
| 15499 |
def quit_terminate_cmd(self): |
| 15500 |
"""Forcefully abort the current subprocess. |
| 15501 |
|
| 15502 |
Try to gracefully exit first by sending common Argyll CMS abort |
| 15503 |
keystrokes (ESC), forcefully terminate the subprocess if not |
| 15504 |
reacting |
| 15505 |
|
| 15506 |
""" |
| 15507 |
# If running wexpect.spawn in a thread under Windows, writing to |
| 15508 |
# sys.stdout from another thread can fail sporadically with IOError 9 |
| 15509 |
# 'Bad file descriptor', so don't use sys.stdout |
| 15510 |
# Careful: Python 2.5 Producer objects don't have a name attribute |
| 15511 |
if ( |
| 15512 |
hasattr(self, "thread") |
| 15513 |
and self.thread.is_alive() |
| 15514 |
and ( |
| 15515 |
not hasattr(current_thread(), "name") |
| 15516 |
or current_thread().name != self.thread.name |
| 15517 |
) |
| 15518 |
): |
| 15519 |
logfn = LOG |
| 15520 |
else: |
| 15521 |
logfn = print |
| 15522 |
subprocess = getattr(self, "subprocess", None) |
| 15523 |
if self.isalive(subprocess): |
| 15524 |
try: |
| 15525 |
if self.measure_cmd and hasattr(subprocess, "send"): |
| 15526 |
self.log( |
| 15527 |
f"{APPNAME}: Trying to end subprocess gracefully...", fn=logfn |
| 15528 |
) |
| 15529 |
try: |
| 15530 |
if subprocess.after == "Current": |
| 15531 |
# Stop measurement |
| 15532 |
self.safe_send(" ") |
| 15533 |
sleep(1) |
| 15534 |
ts = time() |
| 15535 |
while ( |
| 15536 |
self.isalive(subprocess) and self.subprocess == subprocess |
| 15537 |
): |
| 15538 |
self.safe_send("\x1b") |
| 15539 |
if time() > ts + 20: |
| 15540 |
break |
| 15541 |
sleep(0.5) |
| 15542 |
except Exception as exception: |
| 15543 |
self.log(traceback.format_exc(), fn=logfn) |
| 15544 |
self.log( |
| 15545 |
f"{APPNAME}: Exception in quit_terminate_command: " |
| 15546 |
f"{exception}", |
| 15547 |
fn=logfn, |
| 15548 |
) |
| 15549 |
elif hasattr(subprocess, "sendintr"): |
| 15550 |
self.log(f"{APPNAME}: Sending CTRL+C to subprocess...", fn=logfn) |
| 15551 |
try: |
| 15552 |
subprocess.sendintr() |
| 15553 |
except Exception as exception: |
| 15554 |
self.log(traceback.format_exc(), fn=logfn) |
| 15555 |
self.log( |
| 15556 |
f"{APPNAME}: Exception in quit_terminate_command: " |
| 15557 |
f"{exception}", |
| 15558 |
fn=logfn, |
| 15559 |
) |
| 15560 |
ts = time() |
| 15561 |
while self.isalive(subprocess): |
| 15562 |
if time() > ts + 20: |
| 15563 |
break |
| 15564 |
sleep(0.25) |
| 15565 |
if self.isalive(subprocess): |
| 15566 |
self.log(f"{APPNAME}: Trying to terminate subprocess...", fn=logfn) |
| 15567 |
subprocess.terminate() |
| 15568 |
ts = time() |
| 15569 |
while self.isalive(subprocess): |
| 15570 |
if time() > ts + 3: |
| 15571 |
break |
| 15572 |
sleep(0.25) |
| 15573 |
if sys.platform != "win32" and self.isalive(subprocess): |
| 15574 |
self.log( |
| 15575 |
f"{APPNAME}: Trying to terminate subprocess forcefully...", |
| 15576 |
fn=logfn, |
| 15577 |
) |
| 15578 |
if isinstance(subprocess, sp.Popen): |
| 15579 |
subprocess.kill() |
| 15580 |
else: |
| 15581 |
subprocess.terminate(force=True) |
| 15582 |
ts = time() |
| 15583 |
while self.isalive(subprocess): |
| 15584 |
if time() > ts + 3: |
| 15585 |
break |
| 15586 |
sleep(0.25) |
| 15587 |
if self.isalive(subprocess): |
| 15588 |
self.log("...warning: couldn't terminate subprocess.", fn=logfn) |
| 15589 |
else: |
| 15590 |
self.log("...subprocess terminated.", fn=logfn) |
| 15591 |
except Exception as exception: |
| 15592 |
self.log(traceback.format_exc(), fn=logfn) |
| 15593 |
self.log( |
| 15594 |
f"{APPNAME}: Exception in quit_terminate_command: {exception}", |
| 15595 |
fn=logfn, |
| 15596 |
) |
| 15597 |
subprocess_isalive = self.isalive(subprocess) |
| 15598 |
if subprocess_isalive or ( |
| 15599 |
hasattr(self, "thread") and not self.thread.is_alive() |
| 15600 |
): |
| 15601 |
# We don't normally need this as closing of the progress window is |
| 15602 |
# handled by _generic_consumer(), but there are two cases where it |
| 15603 |
# is desirable to have this 'safety net': |
| 15604 |
# 1. The user aborted a running task, but we couldn't terminate the |
| 15605 |
# associated subprocess. In that case, we have a lingering |
| 15606 |
# subprocess which is problematic but we can't do anything about |
| 15607 |
# it. Atleast we need to give control back to the user by closing |
| 15608 |
# the progress window so he can interact with the application |
| 15609 |
# and doesn't have to resort to forecfully terminate it. |
| 15610 |
# 2. We started a thread with continue_next=True, which then exited |
| 15611 |
# without returning an error, yet not the result we were looking |
| 15612 |
# for, so we never started the next thread with resume=True, but |
| 15613 |
# we forgot to call stop_progress() exlicitly. This should never |
| 15614 |
# happen if we design our result consumer correctly to handle |
| 15615 |
# this particular case, but we need to make sure the user can |
| 15616 |
# close the progress window in case we mess up. |
| 15617 |
if hasattr(self, "thread") and not self.thread.is_alive(): |
| 15618 |
wx.CallAfter(self.stop_progress) |
| 15619 |
if subprocess_isalive: |
| 15620 |
wx.CallAfter( |
| 15621 |
show_result_dialog, |
| 15622 |
Warning( |
| 15623 |
f"Couldn't terminate {self.cmd}. Please try to end it manually " |
| 15624 |
f"before continuing to use {APPNAME}. If you can not terminate " |
| 15625 |
f"{self.cmd}, restarting {APPNAME} may also help. Apologies " |
| 15626 |
"for the inconvenience." |
| 15627 |
), |
| 15628 |
self.owner, |
| 15629 |
) |
| 15630 |
if self.patterngenerator: |
| 15631 |
self.patterngenerator.listening = False |
| 15632 |
return not subprocess_isalive |
| 15633 |
|
| 15634 |
def report(self, report_calibrated=True): |
| 15635 |
"""Report on calibrated or uncalibrated display device response. |
| 15636 |
|
| 15637 |
Args: |
| 15638 |
report_calibrated (bool): If True, report on calibrated display |
| 15639 |
device response, otherwise report on uncalibrated display |
| 15640 |
device response. |
| 15641 |
|
| 15642 |
Returns: |
| 15643 |
str | Exception: a string containing the report if |
| 15644 |
successful, an Exception if an error occurs. |
| 15645 |
""" |
| 15646 |
result = self.detect_video_levels() |
| 15647 |
if isinstance(result, Exception) or not result: |
| 15648 |
return result |
| 15649 |
cmd, args = self.prepare_dispcal(calibrate=False) |
| 15650 |
if isinstance(cmd, Exception): |
| 15651 |
return cmd |
| 15652 |
if args: |
| 15653 |
if report_calibrated: |
| 15654 |
args.append("-r") |
| 15655 |
else: |
| 15656 |
args.append("-R") |
| 15657 |
return self.exec_cmd(cmd, args, capture_output=True, skip_scripts=True) |
| 15658 |
|
| 15659 |
def reset_cal(self): |
| 15660 |
"""Reset the current display calibration. |
| 15661 |
|
| 15662 |
Returns: |
| 15663 |
None | Exception: None if successful, or an Exception if an error |
| 15664 |
occurs. |
| 15665 |
""" |
| 15666 |
cmd, args = self.prepare_dispwin(False) |
| 15667 |
return self.exec_cmd( |
| 15668 |
cmd, args, capture_output=True, skip_scripts=True, silent=False |
| 15669 |
) |
| 15670 |
|
| 15671 |
def safe_send(self, data): |
| 15672 |
"""Send data to the current subprocess, retrying if necessary. |
| 15673 |
|
| 15674 |
Returns: |
| 15675 |
bool: Always send True. |
| 15676 |
""" |
| 15677 |
self.send_buffer = data |
| 15678 |
return True |
| 15679 |
|
| 15680 |
def _safe_send(self, data, retry=3, obfuscate=False): |
| 15681 |
"""Safely send a keystroke to the current subprocess. |
| 15682 |
|
| 15683 |
Args: |
| 15684 |
data (str): Data to send to the subprocess. |
| 15685 |
retry (int): Number of times to retry sending the data. |
| 15686 |
obfuscate (bool): If True, obfuscate the data in the log output. |
| 15687 |
|
| 15688 |
Returns: |
| 15689 |
bool: True if the data was sent successfully, False otherwise. |
| 15690 |
""" |
| 15691 |
for i in range(retry): |
| 15692 |
logbytes = "***" if obfuscate else data |
| 15693 |
self.logger.info(f"Sending key(s) {logbytes} ({i + 1:d})") |
| 15694 |
try: |
| 15695 |
if sys.platform == "win32": |
| 15696 |
# directly send the bytes_ without encoding to anything |
| 15697 |
self.subprocess.send(data) |
| 15698 |
else: |
| 15699 |
# for Linux and MacOS encode to bytes |
| 15700 |
self.subprocess.send(data.encode()) |
| 15701 |
except Exception as exception: |
| 15702 |
self.logger.exception(f"Exception: {exception}") |
| 15703 |
else: |
| 15704 |
return True |
| 15705 |
sleep(0.25) |
| 15706 |
return False |
| 15707 |
|
| 15708 |
def save_current_video_lut( |
| 15709 |
self, display_no, outfilename, interpolate_to_256=True, silent=False |
| 15710 |
): |
| 15711 |
"""Save current videoLUT, optionally interpolating to n entries. |
| 15712 |
|
| 15713 |
Args: |
| 15714 |
display_no (int): Display number to save the videoLUT for. |
| 15715 |
outfilename (str): Output filename to save the videoLUT to. |
| 15716 |
interpolate_to_256 (bool): If True, interpolate the videoLUT to 256 |
| 15717 |
entries. |
| 15718 |
silent (bool): If True, do not print any messages. |
| 15719 |
|
| 15720 |
Returns: |
| 15721 |
None | Exception: None if successful, or an Exception if an error |
| 15722 |
occurs. |
| 15723 |
""" |
| 15724 |
result = None |
| 15725 |
if self.argyll_version[0:3] > [1, 1, 0] or ( |
| 15726 |
self.argyll_version[0:3] == [1, 1, 0] |
| 15727 |
and "Beta" not in self.argyll_version_string |
| 15728 |
): |
| 15729 |
cmd, args = ( |
| 15730 |
get_argyll_util("dispwin"), |
| 15731 |
[f"-d{display_no}", "-s", outfilename], |
| 15732 |
) |
| 15733 |
result = self.exec_cmd( |
| 15734 |
cmd, args, capture_output=True, skip_scripts=True, silent=silent |
| 15735 |
) |
| 15736 |
if isinstance(result, Exception) and not isinstance(result, UnloggedInfo): |
| 15737 |
return result |
| 15738 |
if not result: |
| 15739 |
return Error(lang.getstr("calibration.load_error")) |
| 15740 |
# Make sure there are 256 entries in the .cal file, otherwise dispwin |
| 15741 |
# will complain and not be able to load it back in. |
| 15742 |
# Under Windows, the GetDeviceGammaRamp API seems to enforce 256 entries |
| 15743 |
# regardless of graphics card, but under Linux and Mac OS X there may be |
| 15744 |
# more than 256 entries if the graphics card has greater than 8 bit |
| 15745 |
# videoLUTs (e.g. Quadro and newer consumer cards) |
| 15746 |
cgats = CGATS(outfilename) |
| 15747 |
data = cgats.queryv1("DATA") |
| 15748 |
if data and len(data) != 256: |
| 15749 |
print(f"VideoLUT has {len(data):d} entries, interpolating to 256") |
| 15750 |
rgb = {"I": [], "R": [], "G": [], "B": []} |
| 15751 |
for entry in data.values(): |
| 15752 |
for column in ("I", "R", "G", "B"): |
| 15753 |
rgb[column].append(entry["RGB_" + column]) |
| 15754 |
interp = {} |
| 15755 |
for column in ("R", "G", "B"): |
| 15756 |
interp[column] = colormath.Interp(rgb["I"], rgb[column]) |
| 15757 |
resized = CGATS() |
| 15758 |
data.parent.DATA = resized |
| 15759 |
resized.key = "DATA" |
| 15760 |
resized.parent = data.parent |
| 15761 |
resized.root = cgats |
| 15762 |
resized.type = b"DATA" |
| 15763 |
for i in range(256): |
| 15764 |
entry = {"RGB_I": i / 255.0} |
| 15765 |
for column in ("R", "G", "B"): |
| 15766 |
entry["RGB_" + column] = interp[column](entry["RGB_I"]) |
| 15767 |
resized.add_data(entry) |
| 15768 |
cgats.write() |
| 15769 |
return result |
| 15770 |
|
| 15771 |
def set_argyll_version(self, name, silent=False, cfg=False): |
| 15772 |
"""Set the Argyll CMS version from a name. |
| 15773 |
|
| 15774 |
Args: |
| 15775 |
name (str): Name of the Argyll CMS version to set. |
| 15776 |
silent (bool): If True, do not print the version string. |
| 15777 |
cfg (bool): If True, write the version to the configuration. |
| 15778 |
""" |
| 15779 |
self.set_argyll_version_from_string( |
| 15780 |
get_argyll_version_string(name, silent), cfg |
| 15781 |
) |
| 15782 |
|
| 15783 |
def set_argyll_version_from_string(self, argyll_version_string, cfg=True): |
| 15784 |
"""Set the Argyll CMS version from a version string. |
| 15785 |
|
| 15786 |
Args: |
| 15787 |
argyll_version_string (str): The version string to set. |
| 15788 |
cfg (bool): If True, write the version to the configuration. |
| 15789 |
""" |
| 15790 |
self.argyll_version_string = argyll_version_string |
| 15791 |
if cfg: |
| 15792 |
setcfg("argyll.version", argyll_version_string) |
| 15793 |
# Always write cfg directly after setting Argyll version so |
| 15794 |
# subprocesses that read the configuration will use the right |
| 15795 |
# version |
| 15796 |
writecfg() |
| 15797 |
self.argyll_version = parse_argyll_version_string(argyll_version_string) |
| 15798 |
|
| 15799 |
def set_sessionlogfile(self, sessionlogfile, basename, dirname) -> None: |
| 15800 |
"""Set the session logfile for the current session. |
| 15801 |
|
| 15802 |
Args: |
| 15803 |
sessionlogfile (None | LogFile): LogFile object for the session |
| 15804 |
log, or None to create a new one. |
| 15805 |
basename (str): Basename for the session log file. |
| 15806 |
dirname (str): Directory where the session log file will be stored. |
| 15807 |
""" |
| 15808 |
if sessionlogfile: |
| 15809 |
self.sessionlogfile = sessionlogfile |
| 15810 |
else: |
| 15811 |
self.sessionlogfile = LogFile(basename, dirname) |
| 15812 |
self.sessionlogfiles[basename] = self.sessionlogfile |
| 15813 |
|
| 15814 |
def set_terminal_cgats(self, cgats): |
| 15815 |
"""Set the CGATS object for the terminal. |
| 15816 |
|
| 15817 |
Args: |
| 15818 |
cgats (CGATS): CGATS object. |
| 15819 |
|
| 15820 |
Returns: |
| 15821 |
None | Exception: None if successful, or an Exception if an error |
| 15822 |
occurs. |
| 15823 |
""" |
| 15824 |
if not isinstance(cgats, CGATS): |
| 15825 |
try: |
| 15826 |
cgats = CGATS(cgats) |
| 15827 |
except ( |
| 15828 |
OSError, |
| 15829 |
CGATSInvalidError, |
| 15830 |
CGATSInvalidOperationError, |
| 15831 |
CGATSKeyError, |
| 15832 |
CGATSTypeError, |
| 15833 |
CGATSValueError, |
| 15834 |
) as exception: |
| 15835 |
return exception |
| 15836 |
self.terminal.cgats = cgats |
| 15837 |
return None |
| 15838 |
|
| 15839 |
def setup_inout(self, basename=None): |
| 15840 |
"""Setup in/outfile basename and session logfile. |
| 15841 |
|
| 15842 |
Args: |
| 15843 |
basename (None | str): Basename for the in/output file(s). If None, |
| 15844 |
it will use the expanded profile name from the configuration. |
| 15845 |
|
| 15846 |
Returns: |
| 15847 |
str | Exception: Full path to the in/output file(s) or an Exception |
| 15848 |
if an error occurs. |
| 15849 |
""" |
| 15850 |
dirname = self.create_tempdir() |
| 15851 |
if not dirname or isinstance(dirname, Exception): |
| 15852 |
return dirname |
| 15853 |
# Check directory and in/output file(s) |
| 15854 |
result = check_create_dir(dirname) |
| 15855 |
if isinstance(result, Exception): |
| 15856 |
return result |
| 15857 |
if basename is None: |
| 15858 |
basename = getcfg("profile.name.expanded") |
| 15859 |
basename = make_argyll_compatible_path(basename, is_name=True) |
| 15860 |
self.set_sessionlogfile(None, basename, dirname) |
| 15861 |
return os.path.join(dirname, basename) |
| 15862 |
|
| 15863 |
def single_real_display(self): |
| 15864 |
"""Check if there is only one real display connected. |
| 15865 |
|
| 15866 |
Returns: |
| 15867 |
bool: True if there is only one real display, False otherwise. |
| 15868 |
""" |
| 15869 |
return len(self.get_real_displays()) == 1 |
| 15870 |
|
| 15871 |
def argyll_support_file_exists(self, name, scope=None): |
| 15872 |
"""Check if file exists in Argyll support locations for current version. |
| 15873 |
|
| 15874 |
Args: |
| 15875 |
name (str): Name of the file to check for. |
| 15876 |
scope (None | str): Scope can be 'u' (user), 'l' (local system) or |
| 15877 |
None (both) |
| 15878 |
|
| 15879 |
Returns: |
| 15880 |
bool: True if the file exists, False otherwise. |
| 15881 |
""" |
| 15882 |
paths = [] |
| 15883 |
if sys.platform != "darwin": |
| 15884 |
if not scope or scope == "u": |
| 15885 |
paths.append(defaultpaths.APPDATA) |
| 15886 |
if not scope or scope == "l": |
| 15887 |
paths += defaultpaths.COMMONAPPDATA |
| 15888 |
else: |
| 15889 |
if not scope or scope == "u": |
| 15890 |
paths.append(defaultpaths.LIBRARY_HOME) |
| 15891 |
if not scope or scope == "l": |
| 15892 |
paths.append(defaultpaths.LIBRARY) |
| 15893 |
searchpaths = [] |
| 15894 |
if self.argyll_version >= [1, 5, 0]: |
| 15895 |
if sys.platform != "darwin": |
| 15896 |
searchpaths.extend( |
| 15897 |
os.path.join(dir_, "ArgyllCMS", name) for dir_ in paths |
| 15898 |
) |
| 15899 |
else: |
| 15900 |
paths2 = [] |
| 15901 |
if not scope or scope == "u": |
| 15902 |
paths2.append(defaultpaths.APPDATA) |
| 15903 |
if not scope or scope == "l": |
| 15904 |
paths2.append(defaultpaths.LIBRARY) |
| 15905 |
if [1, 9] <= self.argyll_version <= [1, 9, 1]: |
| 15906 |
# Argyll CMS 1.9 and 1.9.1 use *nix locations due to a |
| 15907 |
# configuration problem |
| 15908 |
paths2.extend( |
| 15909 |
[ |
| 15910 |
os.path.join(defaultpaths.HOME, ".local", "share"), |
| 15911 |
"/usr/local/share", |
| 15912 |
] |
| 15913 |
) |
| 15914 |
searchpaths.extend( |
| 15915 |
os.path.join(dir_, "ArgyllCMS", name) for dir_ in paths2 |
| 15916 |
) |
| 15917 |
searchpaths.extend(os.path.join(dir_, "color", name) for dir_ in paths) |
| 15918 |
return any(os.path.isfile(searchpath) for searchpath in searchpaths) |
| 15919 |
|
| 15920 |
def spyder2_firmware_exists(self, scope=None): |
| 15921 |
"""Check if the Spyder 2 firmware file exists for the current Argyll version. |
| 15922 |
|
| 15923 |
Args: |
| 15924 |
scope (None | str): Scope can be 'u' (user), 'l' (local system) or |
| 15925 |
None (both). |
| 15926 |
|
| 15927 |
Returns: |
| 15928 |
bool: True if the Spyder 2 firmware file exists, False otherwise. |
| 15929 |
""" |
| 15930 |
if self.argyll_version < [1, 2, 0]: |
| 15931 |
spyd2en = get_argyll_util("spyd2en") |
| 15932 |
if not spyd2en: |
| 15933 |
return False |
| 15934 |
return os.path.isfile( |
| 15935 |
os.path.join(os.path.dirname(spyd2en), "spyd2PLD.bin") |
| 15936 |
) |
| 15937 |
return self.argyll_support_file_exists("spyd2PLD.bin", scope=scope) |
| 15938 |
|
| 15939 |
def spyder4_cal_exists(self): |
| 15940 |
"""Check if Spyder4/5 calibration file exists for current Argyll version. |
| 15941 |
|
| 15942 |
Returns: |
| 15943 |
bool: True if the Spyder4/5 calibration file exists, False |
| 15944 |
otherwise. |
| 15945 |
""" |
| 15946 |
if self.argyll_version < [1, 3, 6]: |
| 15947 |
# We couldn't use it even if it exists |
| 15948 |
return False |
| 15949 |
return self.argyll_support_file_exists("spyd4cal.bin") |
| 15950 |
|
| 15951 |
def start( |
| 15952 |
self, |
| 15953 |
consumer, |
| 15954 |
producer, |
| 15955 |
cargs=(), |
| 15956 |
ckwargs=None, |
| 15957 |
wargs=(), |
| 15958 |
wkwargs=None, |
| 15959 |
progress_title=APPNAME, |
| 15960 |
progress_msg="", |
| 15961 |
parent=None, |
| 15962 |
progress_start=100, |
| 15963 |
resume=False, |
| 15964 |
continue_next=False, |
| 15965 |
stop_timers=True, |
| 15966 |
interactive_frame="", |
| 15967 |
pauseable=False, |
| 15968 |
cancelable=True, |
| 15969 |
show_remaining_time=True, |
| 15970 |
fancy=True, |
| 15971 |
): |
| 15972 |
"""Start a worker process with a progress dialog. |
| 15973 |
|
| 15974 |
Args: |
| 15975 |
consumer (callable): Consumer function to handle results. |
| 15976 |
producer (callable): Producer function to run in a separate thread. |
| 15977 |
cargs (tuple): Arguments for the consumer function. |
| 15978 |
ckwargs (dict): Keyword arguments for the consumer function. |
| 15979 |
wargs (tuple): Arguments for the producer function. |
| 15980 |
wkwargs (dict): Keyword arguments for the producer function. |
| 15981 |
progress_title (str): Title for the progress dialog. Defaults to |
| 15982 |
'{APPNAME}'. |
| 15983 |
progress_msg (str): Message for the progress dialog. Defaults to ''. |
| 15984 |
parent (wx.Window): Parent window for the progress dialog. |
| 15985 |
progress_start (int): Delay before showing the progress dialog (ms). |
| 15986 |
resume (bool): Resume previous progress dialog (elapsed time etc). |
| 15987 |
continue_next (bool): Do not hide progress dialog after producer |
| 15988 |
finishes. |
| 15989 |
stop_timers (bool): Stop the timers on the owner window if True. |
| 15990 |
interactive_frame (str or wx.TopLevelWindow): Type of interactive |
| 15991 |
window or a wx.TopLevelWindow instance. |
| 15992 |
pauseable (bool): Is the operation pauseable? Show pause button on |
| 15993 |
the progress dialog. |
| 15994 |
cancelable (bool): Is the operation cancelable? Show cancel button |
| 15995 |
on the progress dialog. |
| 15996 |
show_remaining_time (bool): Show remaining time in the progress |
| 15997 |
dialog. |
| 15998 |
fancy (bool): Use fancy progress dialog with animated throbber & |
| 15999 |
sound effects. |
| 16000 |
|
| 16001 |
Returns: |
| 16002 |
None: If the worker thread is already running. |
| 16003 |
bool: True if the worker thread was started successfully, |
| 16004 |
""" |
| 16005 |
# The following statement is super hacky, I didn't want to use it but the |
| 16006 |
# original developer wanted to add the ``appname`` into the docstring |
| 16007 |
# programmatically. So, I think this is the best but hacky way to do it. |
| 16008 |
self.start.__func__.__doc__ = f"""Start a worker process. |
| 16009 |
|
| 16010 |
Also show a progress dialog while the process is running. |
| 16011 |
|
| 16012 |
consumer consumer function. |
| 16013 |
producer producer function. |
| 16014 |
cargs consumer arguments. |
| 16015 |
ckwargs consumer keyword arguments. |
| 16016 |
wargs producer arguments. |
| 16017 |
wkwargs producer keyword arguments. |
| 16018 |
progress_title progress dialog title. Defaults to '{APPNAME}'. |
| 16019 |
progress_msg progress dialog message. Defaults to ''. |
| 16020 |
progress_start show progress dialog after delay (ms). |
| 16021 |
resume resume previous progress dialog (elapsed time etc). |
| 16022 |
continue_next do not hide progress dialog after producer finishes. |
| 16023 |
stop_timers stop the timers on the owner window if True |
| 16024 |
interactive_frame "" or "uniformity" (selects the type of |
| 16025 |
interactive window) |
| 16026 |
pauseable Is the operation pauseable? (show pause button on |
| 16027 |
progress dialog) |
| 16028 |
cancelable Is the operation cancelable? (show cancel button on |
| 16029 |
progress dialog) |
| 16030 |
fancy Use fancy progress dialog with animated throbber & |
| 16031 |
sound fx |
| 16032 |
""" |
| 16033 |
if ckwargs is None: |
| 16034 |
ckwargs = {} |
| 16035 |
if wkwargs is None: |
| 16036 |
wkwargs = {} |
| 16037 |
while self.is_working(): |
| 16038 |
sleep(0.25) # wait until previous worker thread finishes |
| 16039 |
if hasattr(self.owner, "stop_timers") and stop_timers: |
| 16040 |
self.owner.stop_timers() |
| 16041 |
if not parent: |
| 16042 |
parent = self.owner |
| 16043 |
progress_start = max(progress_start, 1) # Can't be zero! |
| 16044 |
self.activated = False |
| 16045 |
self.cmdname = None |
| 16046 |
self.cmdrun = False |
| 16047 |
self.finished = False |
| 16048 |
self.instrument_calibration_complete = False |
| 16049 |
self._last_calibration_msg = None |
| 16050 |
if not resume: |
| 16051 |
self.instrument_on_screen = False |
| 16052 |
self.instrument_place_on_screen_msg = False |
| 16053 |
self.instrument_sensor_position_msg = False |
| 16054 |
self.interactive_frame = interactive_frame |
| 16055 |
self.is_single_measurement = interactive_frame in {"ambient", "luminance"} or ( |
| 16056 |
isinstance(interactive_frame, wx.TopLevelWindow) |
| 16057 |
and interactive_frame.Name == "VisualWhitepointEditor" |
| 16058 |
) |
| 16059 |
self.is_ambient_measurement = interactive_frame == "ambient" |
| 16060 |
self.lastcmdname = None |
| 16061 |
self.pauseable = pauseable |
| 16062 |
self.paused = False |
| 16063 |
self.cancelable = cancelable |
| 16064 |
self.show_remaining_time = show_remaining_time |
| 16065 |
self.fancy = fancy |
| 16066 |
self.resume = resume |
| 16067 |
self.subprocess_abort = False |
| 16068 |
self.abort_requested = False |
| 16069 |
self.starttime = time() |
| 16070 |
self.thread_abort = False |
| 16071 |
if ( |
| 16072 |
fancy |
| 16073 |
and ( |
| 16074 |
not self.interactive |
| 16075 |
or interactive_frame not in ("uniformity", "untethered") |
| 16076 |
) |
| 16077 |
and not isinstance(interactive_frame, wx.TopLevelWindow) |
| 16078 |
): |
| 16079 |
# Pre-init progress dialog bitmaps |
| 16080 |
ProgressDialog.get_bitmaps(0) |
| 16081 |
ProgressDialog.get_bitmaps(1) |
| 16082 |
if self.interactive: |
| 16083 |
self.progress_start_timer = wx.Timer() |
| 16084 |
if progress_msg and progress_title == APPNAME: |
| 16085 |
progress_title = progress_msg |
| 16086 |
if ( |
| 16087 |
config.get_display_name() == "Untethered" |
| 16088 |
and interactive_frame != "uniformity" |
| 16089 |
): |
| 16090 |
interactive_frame = "untethered" |
| 16091 |
if interactive_frame == "adjust": |
| 16092 |
windowclass = DisplayAdjustmentFrame |
| 16093 |
elif interactive_frame == "uniformity": |
| 16094 |
windowclass = DisplayUniformityFrame |
| 16095 |
elif interactive_frame == "untethered": |
| 16096 |
windowclass = UntetheredFrame |
| 16097 |
else: |
| 16098 |
windowclass = SimpleTerminal |
| 16099 |
if getattr(self, "terminal", None) and isinstance( |
| 16100 |
self.terminal, windowclass |
| 16101 |
): |
| 16102 |
self.progress_wnd = self.terminal |
| 16103 |
if not resume: |
| 16104 |
if isinstance(self.progress_wnd, SimpleTerminal): |
| 16105 |
self.progress_wnd.console.SetValue("") |
| 16106 |
elif isinstance( |
| 16107 |
self.progress_wnd, |
| 16108 |
( |
| 16109 |
DisplayAdjustmentFrame, |
| 16110 |
DisplayUniformityFrame, |
| 16111 |
UntetheredFrame, |
| 16112 |
), |
| 16113 |
): |
| 16114 |
self.progress_wnd.reset() |
| 16115 |
self.progress_wnd.stop_timer() |
| 16116 |
self.progress_wnd.Resume() |
| 16117 |
self.progress_wnd.start_timer() |
| 16118 |
# UGLY HACK: This 'print' call fixes a GTK assertion and |
| 16119 |
# segfault under Arch Linux when setting the window title |
| 16120 |
print("") |
| 16121 |
if isinstance(self.progress_wnd, SimpleTerminal): |
| 16122 |
self.progress_wnd.SetTitle(progress_title) |
| 16123 |
self.progress_wnd.Show() |
| 16124 |
if resume and isinstance(self.progress_wnd, SimpleTerminal): |
| 16125 |
self.progress_wnd.console.ScrollLines( |
| 16126 |
self.progress_wnd.console.GetNumberOfLines() |
| 16127 |
) |
| 16128 |
else: |
| 16129 |
if getattr(self, "terminal", None): |
| 16130 |
# Destroy the wx object so the decref'd python object can |
| 16131 |
# be garbage collected |
| 16132 |
self.terminal.Destroy() |
| 16133 |
if interactive_frame == "adjust": |
| 16134 |
self.terminal = DisplayAdjustmentFrame( |
| 16135 |
parent, |
| 16136 |
handler=self.progress_handler, |
| 16137 |
keyhandler=self.terminal_key_handler, |
| 16138 |
) |
| 16139 |
elif interactive_frame == "uniformity": |
| 16140 |
self.terminal = DisplayUniformityFrame( |
| 16141 |
parent, |
| 16142 |
handler=self.progress_handler, |
| 16143 |
keyhandler=self.terminal_key_handler, |
| 16144 |
) |
| 16145 |
elif interactive_frame == "untethered": |
| 16146 |
self.terminal = UntetheredFrame( |
| 16147 |
parent, |
| 16148 |
handler=self.progress_handler, |
| 16149 |
keyhandler=self.terminal_key_handler, |
| 16150 |
) |
| 16151 |
elif isinstance(interactive_frame, wx.TopLevelWindow): |
| 16152 |
self.terminal = interactive_frame |
| 16153 |
else: |
| 16154 |
self.terminal = SimpleTerminal( |
| 16155 |
parent, |
| 16156 |
title=progress_title, |
| 16157 |
handler=self.progress_handler, |
| 16158 |
keyhandler=self.terminal_key_handler, |
| 16159 |
) |
| 16160 |
if getattr(self.terminal, "worker", self) is not self: |
| 16161 |
print( |
| 16162 |
"DEBUG: In worker.Worker.start: worker.Worker()." |
| 16163 |
"terminal.worker is not self! This is probably a" |
| 16164 |
"bug." |
| 16165 |
) |
| 16166 |
self.terminal.worker = self |
| 16167 |
self.progress_wnd = self.terminal |
| 16168 |
else: |
| 16169 |
if not progress_msg: |
| 16170 |
progress_msg = lang.getstr("please_wait") |
| 16171 |
# Show the progress dialog after a delay |
| 16172 |
self.progress_start_timer = BetterCallLater( |
| 16173 |
progress_start, |
| 16174 |
self.progress_dlg_start, |
| 16175 |
progress_title, |
| 16176 |
progress_msg, |
| 16177 |
parent, |
| 16178 |
resume, |
| 16179 |
fancy, |
| 16180 |
) |
| 16181 |
if not hasattr(self, "_disabler"): |
| 16182 |
skip = self.progress_wnds |
| 16183 |
if self.owner and hasattr(self.owner, "measureframe"): |
| 16184 |
skip.append(self.owner.measureframe) |
| 16185 |
self._disabler = BetterWindowDisabler(skip) |
| 16186 |
# Can't use startWorker because we may need access to self.thread from |
| 16187 |
# within thread, and startWorker does not return before the actual |
| 16188 |
# thread starts running |
| 16189 |
jobID = None |
| 16190 |
sender = delayedresult.SenderCallAfter( |
| 16191 |
self._generic_consumer, |
| 16192 |
jobID, |
| 16193 |
args=[consumer, continue_next, *list(cargs)], |
| 16194 |
kwargs=ckwargs, |
| 16195 |
) |
| 16196 |
self.thread = delayedresult.Producer( |
| 16197 |
sender, |
| 16198 |
Producer(self, producer, continue_next), |
| 16199 |
args=wargs, |
| 16200 |
kwargs=wkwargs, |
| 16201 |
name=jobID, |
| 16202 |
group=None, |
| 16203 |
daemon=False, |
| 16204 |
senderArg=None, |
| 16205 |
sendReturn=True, |
| 16206 |
) |
| 16207 |
|
| 16208 |
self.thread.start() |
| 16209 |
return True |
| 16210 |
|
| 16211 |
def stop_progress(self): |
| 16212 |
"""Stop the progress dialog and clean up.""" |
| 16213 |
if hasattr(self, "_disabler"): |
| 16214 |
del self._disabler |
| 16215 |
if getattr(self, "progress_wnd", False): |
| 16216 |
if getattr(self.progress_wnd, "dlg", None): |
| 16217 |
if self.progress_wnd.dlg.IsShownOnScreen(): |
| 16218 |
self.progress_wnd.dlg.EndModal(wx.ID_CANCEL) |
| 16219 |
self.progress_wnd.dlg = None |
| 16220 |
self.progress_wnd.stop_timer() |
| 16221 |
if getattr(self.progress_wnd, "Name", None) == "VisualWhitepointEditor": |
| 16222 |
self.progress_wnd.Close() |
| 16223 |
else: |
| 16224 |
self.progress_wnd.Hide() |
| 16225 |
self.subprocess_abort = False |
| 16226 |
self.thread_abort = False |
| 16227 |
self.interactive = False |
| 16228 |
self.resume = False |
| 16229 |
self._detected_output_levels = False |
| 16230 |
|
| 16231 |
# Uninhibit session if needed |
| 16232 |
if hasattr(self, "dbus_ifaces"): |
| 16233 |
for bus_name in self.dbus_ifaces: |
| 16234 |
iface_dict = self.dbus_ifaces[bus_name] |
| 16235 |
cookie = iface_dict.get("cookie") |
| 16236 |
if cookie: |
| 16237 |
# Uninhibit. Note that if (e.g.) screensaver timeout has |
| 16238 |
# occurred during the time the session was inhibited, that |
| 16239 |
# may now kick in immediately after uninhibiting |
| 16240 |
uninhibit = iface_dict.get("uninhibit", "un_inhibit") |
| 16241 |
try: |
| 16242 |
getattr(iface_dict["iface"], uninhibit)(cookie) |
| 16243 |
except DBusException as exception: |
| 16244 |
self.log(exception) |
| 16245 |
else: |
| 16246 |
iface_dict["cookie"] = None |
| 16247 |
self.log(f"{APPNAME}: Uninhibited {bus_name}") |
| 16248 |
|
| 16249 |
def swap_progress_wnds(self): |
| 16250 |
"""Swap the current interactive window with a progress dialog.""" |
| 16251 |
parent = self.terminal.GetParent() |
| 16252 |
if isinstance(self.terminal, DisplayAdjustmentFrame): |
| 16253 |
title = lang.getstr("calibration") |
| 16254 |
else: |
| 16255 |
title = self.terminal.GetTitle() |
| 16256 |
self.progress_dlg_start(title, "", parent, self.resume, self.fancy) |
| 16257 |
|
| 16258 |
def terminal_key_handler(self, event): |
| 16259 |
"""Key handler for the interactive window or progress dialog. |
| 16260 |
|
| 16261 |
Args: |
| 16262 |
event (wx.Event): The key event to handle. |
| 16263 |
""" |
| 16264 |
keycode = None |
| 16265 |
if event.GetEventType() in (wx.EVT_CHAR_HOOK.typeId, wx.EVT_KEY_DOWN.typeId): |
| 16266 |
keycode = event.GetKeyCode() |
| 16267 |
elif event.GetEventType() == wx.EVT_MENU.typeId: |
| 16268 |
keycode = self.progress_wnd.id_to_keycode.get(event.GetId()) |
| 16269 |
if ( |
| 16270 |
keycode is not None |
| 16271 |
and getattr(self, "subprocess", None) |
| 16272 |
and hasattr(self.subprocess, "send") |
| 16273 |
): |
| 16274 |
keycode = keycodes.get(keycode, keycode) |
| 16275 |
if keycode in (ord("\x1b"), ord("8"), ord("Q"), ord("q")): |
| 16276 |
# exit |
| 16277 |
self.abort_subprocess(True) |
| 16278 |
return |
| 16279 |
with contextlib.suppress(Exception): |
| 16280 |
self.safe_send(chr(keycode)) |
| 16281 |
|
| 16282 |
def calculate_gamut( |
| 16283 |
self, |
| 16284 |
profile_paths, |
| 16285 |
intent="r", |
| 16286 |
direction="f", |
| 16287 |
order="n", |
| 16288 |
compare_standard_gamuts=True, |
| 16289 |
): |
| 16290 |
"""Calculate gamut, volume, and coverage % against sRGB and Adobe RGB. |
| 16291 |
|
| 16292 |
Return gamut volume (int, scaled to sRGB = 1.0) and coverage (dict) as |
| 16293 |
tuple. |
| 16294 |
|
| 16295 |
Args: |
| 16296 |
profile_paths (str or list): Path(s) to ICC profile(s) to calculate |
| 16297 |
gamut from. |
| 16298 |
intent (str): Rendering intent, one of "r" (relative colorimetric), |
| 16299 |
"s" (saturation), "m" (perceptual), "a" (absolute |
| 16300 |
colorimetric). |
| 16301 |
direction (str): Gamut direction, one of "f" (forward), "b" |
| 16302 |
(backward). |
| 16303 |
order (str): Gamut order, one of "n" (normal), "i" (interpolated), |
| 16304 |
"c" (continuous). |
| 16305 |
compare_standard_gamuts (bool): If True, compare gamut against |
| 16306 |
standard gamuts (sRGB, Adobe RGB, DCI-P3) and create |
| 16307 |
intersection VRML files. If False, only create gamut VRML files |
| 16308 |
for the provided profile(s). |
| 16309 |
|
| 16310 |
Returns: |
| 16311 |
tuple[float, dict]: A tuple containing the gamut_volume and |
| 16312 |
gamut_coverage. |
| 16313 |
""" |
| 16314 |
if not isinstance(profile_paths, list): |
| 16315 |
profile_paths = [profile_paths] |
| 16316 |
outname = os.path.splitext(profile_paths[0])[0] |
| 16317 |
mods = [] |
| 16318 |
if intent != "r": |
| 16319 |
mods.append(intent) |
| 16320 |
if direction != "f": |
| 16321 |
mods.append(direction) |
| 16322 |
if order != "n": |
| 16323 |
mods.append(order) |
| 16324 |
if mods: |
| 16325 |
outname += " {}".format("".join([f"[{mod.upper()}]" for mod in mods])) |
| 16326 |
gamut_volume = None |
| 16327 |
gamut_coverage = {} |
| 16328 |
# Create profile gamut and vrml |
| 16329 |
det = getcfg("iccgamut.surface_detail") |
| 16330 |
for i, profile_path in enumerate(profile_paths): |
| 16331 |
if not profile_path: |
| 16332 |
self.log(f"Warning: calculate_gamut(): No profile path {i:d}") |
| 16333 |
continue |
| 16334 |
result = self.exec_cmd( |
| 16335 |
get_argyll_util("iccgamut"), |
| 16336 |
[ |
| 16337 |
"-v", |
| 16338 |
"-w", |
| 16339 |
"-i" + intent, |
| 16340 |
"-f" + direction, |
| 16341 |
"-o" + order, |
| 16342 |
f"-d{det:.2f}", |
| 16343 |
profile_path, |
| 16344 |
], |
| 16345 |
capture_output=True, |
| 16346 |
skip_scripts=True, |
| 16347 |
) |
| 16348 |
if not isinstance(result, Exception) and result: |
| 16349 |
# iccgamut output looks like this: |
| 16350 |
# Header: |
| 16351 |
# <...> |
| 16352 |
# |
| 16353 |
# Total volume of gamut is xxxxxx.xxxxxx cubic colorspace units |
| 16354 |
for line in self.output: |
| 16355 |
match = re.search( |
| 16356 |
r"(\d+(?:\.\d+)?)\s+cubic\s+colorspace\s+units", line |
| 16357 |
) |
| 16358 |
if match: |
| 16359 |
gamut_volume = float(match.groups()[0]) / GAMUT_VOLUME_SRGB |
| 16360 |
break |
| 16361 |
else: |
| 16362 |
break |
| 16363 |
name = os.path.splitext(profile_paths[0])[0] |
| 16364 |
gamfilename = name + ".gam" |
| 16365 |
wrlfilename = name + ".wrl" |
| 16366 |
tmpfilenames = [gamfilename, wrlfilename] |
| 16367 |
if compare_standard_gamuts: |
| 16368 |
comparison_gamuts = [ |
| 16369 |
("srgb", "sRGB"), |
| 16370 |
("adobe-rgb", "ClayRGB1998"), |
| 16371 |
("dci-p3", "SMPTE431_P3"), |
| 16372 |
] |
| 16373 |
else: |
| 16374 |
comparison_gamuts = [] |
| 16375 |
for profile_path in profile_paths[1:]: |
| 16376 |
filename, ext = os.path.splitext(profile_path) |
| 16377 |
comparison_gamuts.append( |
| 16378 |
(filename.lower().replace(" ", "-"), filename + ".gam") |
| 16379 |
) |
| 16380 |
threads = [] |
| 16381 |
viewgam = get_argyll_util("viewgam") |
| 16382 |
for key, src in comparison_gamuts: |
| 16383 |
if not isinstance(result, Exception) and result: |
| 16384 |
# Create gamut view and intersection |
| 16385 |
if os.path.isabs(src): |
| 16386 |
src_path = src |
| 16387 |
src = os.path.splitext(os.path.basename(src))[0] |
| 16388 |
else: |
| 16389 |
if mods: |
| 16390 |
src += " " + "".join([f"[{mod.upper()}]" for mod in mods]) |
| 16391 |
src_path = get_data_path(f"ref/{src}.gam") |
| 16392 |
if not src_path: |
| 16393 |
continue |
| 16394 |
outfilename = outname + " vs " + src |
| 16395 |
if mods: |
| 16396 |
outfilename += " " + "".join([f"[{mod.upper()}]" for mod in mods]) |
| 16397 |
outfilename += ".wrl" |
| 16398 |
tmpfilenames.append(outfilename) |
| 16399 |
# Multi-threaded gamut view calculation |
| 16400 |
worker = Worker() |
| 16401 |
args = [ |
| 16402 |
"-cw", |
| 16403 |
"-t0", |
| 16404 |
"-w", |
| 16405 |
src_path, |
| 16406 |
"-cn", |
| 16407 |
"-t.3", |
| 16408 |
"-s", |
| 16409 |
gamfilename, |
| 16410 |
"-i", |
| 16411 |
outfilename, |
| 16412 |
] |
| 16413 |
thread = threading.Thread( |
| 16414 |
target=self.create_gamut_view_worker, |
| 16415 |
name="CreateGamutViewWorker", |
| 16416 |
args=(worker, viewgam, args, key, src, gamut_coverage), |
| 16417 |
) |
| 16418 |
threads.append((thread, worker, args)) |
| 16419 |
thread.start() |
| 16420 |
# Wait for threads to finish |
| 16421 |
for thread, worker, args in threads: |
| 16422 |
thread.join() |
| 16423 |
self.log("-" * 80) |
| 16424 |
self.log(lang.getstr("commandline")) |
| 16425 |
printcmdline(viewgam, args, fn=self.log, cwd=os.path.dirname(args[-1])) |
| 16426 |
self.log("") |
| 16427 |
self.log("".join(worker.output)) |
| 16428 |
|
| 16429 |
if not isinstance(result, Exception) and result: |
| 16430 |
for tmpfilename in tmpfilenames: |
| 16431 |
if tmpfilename == gamfilename and tmpfilename != f"{outname}.gam": |
| 16432 |
# Use the original file name |
| 16433 |
filename = f"{outname}.gam" |
| 16434 |
elif tmpfilename == wrlfilename and tmpfilename != f"{outname}.wrl": |
| 16435 |
# Use the original file name |
| 16436 |
filename = f"{outname}.wrl" |
| 16437 |
else: |
| 16438 |
filename = tmpfilename |
| 16439 |
|
| 16440 |
try: |
| 16441 |
|
| 16442 |
def tweak_vrml(vrml): |
| 16443 |
# Set viewpoint further away |
| 16444 |
vrml = re.sub( |
| 16445 |
rb"(Viewpoint\s*\{)[^}]+\}", rb"\1 position 0 0 340 }", vrml |
| 16446 |
) |
| 16447 |
# Fix label color for -a* axis |
| 16448 |
label = re.search( |
| 16449 |
rb'Transform\s*\{\s*translation\s+[+\-0-9.]+\s*[+\-0-9.]+\s*[+\-0-9.]+\s+children\s*\[\s*Shape\s*\{\s*geometry\s+Text\s*\{\s*string\s*\["-a\*"\]\s*fontStyle\s+FontStyle\s*\{[^}]*\}\s*\}\s*appearance\s+Appearance\s*\{\s*material\s+Material\s*{[^}]*\}\s*\}\s*\}\s*\]\s*\}', |
| 16450 |
vrml, |
| 16451 |
) |
| 16452 |
if label: |
| 16453 |
label = label.group() |
| 16454 |
vrml = vrml.replace( |
| 16455 |
label, |
| 16456 |
re.sub( |
| 16457 |
rb"(diffuseColor)\s+[+\-0-9.]+\s+[+\-0-9.]+\s+[+\-0-9.]+", |
| 16458 |
rb"\1 0.0 1.0 0.0", |
| 16459 |
label, |
| 16460 |
), |
| 16461 |
) |
| 16462 |
# Add range to axes |
| 16463 |
vrml = re.sub( |
| 16464 |
rb'(string\s*\[")(\+?)(L\*)("\])', |
| 16465 |
rb'\1\3", b"\2\0$\4', |
| 16466 |
vrml, |
| 16467 |
) |
| 16468 |
vrml = re.sub( |
| 16469 |
rb'(string\s*\[")([+\-]?)(a\*)("\])', |
| 16470 |
rb'\1\3", b"\2\0$\4', |
| 16471 |
vrml, |
| 16472 |
) |
| 16473 |
vrml = re.sub( |
| 16474 |
rb'(string\s*\[")([+\-]?)(b\*)("\])', rb"\1\3 \2\0$\4", vrml |
| 16475 |
) |
| 16476 |
return vrml.replace(b"\0$", b"100") |
| 16477 |
|
| 16478 |
gzfilename = f"{filename}.gz" |
| 16479 |
if sys.platform == "win32": |
| 16480 |
filename = make_win32_compatible_long_path(filename) |
| 16481 |
gzfilename = make_win32_compatible_long_path(gzfilename) |
| 16482 |
tmpfilename = make_win32_compatible_long_path(tmpfilename) |
| 16483 |
if getcfg("vrml.compress"): |
| 16484 |
# Compress gam and wrl files using gzip |
| 16485 |
with ( |
| 16486 |
GzipFileProper(gzfilename, "wb") as gz, |
| 16487 |
open(tmpfilename, "rb") as infile, |
| 16488 |
): |
| 16489 |
# Always use original filename with '.gz' extension, |
| 16490 |
# that way the filename in the header will be correct |
| 16491 |
gz.write(tweak_vrml(infile.read())) |
| 16492 |
# Remove uncompressed file |
| 16493 |
os.remove(tmpfilename) |
| 16494 |
tmpfilename = gzfilename |
| 16495 |
else: |
| 16496 |
with open(tmpfilename, "rb") as infile: |
| 16497 |
vrml = infile.read().decode() |
| 16498 |
with open(tmpfilename, "wb") as outfile: |
| 16499 |
outfile.write(tweak_vrml(vrml).encode()) |
| 16500 |
if filename.endswith(".wrl"): |
| 16501 |
filename = f"{filename[:-4]}.wrz" |
| 16502 |
else: |
| 16503 |
filename = gzfilename |
| 16504 |
if tmpfilename != filename: |
| 16505 |
# Rename the file if filename is different |
| 16506 |
if os.path.exists(filename): |
| 16507 |
os.remove(filename) |
| 16508 |
os.rename(tmpfilename, filename) |
| 16509 |
except Exception as exception: |
| 16510 |
self.log(exception) |
| 16511 |
elif result: |
| 16512 |
# Exception |
| 16513 |
self.log(result) |
| 16514 |
return gamut_volume, gamut_coverage |
| 16515 |
|
| 16516 |
@staticmethod |
| 16517 |
def create_gamut_view_worker( |
| 16518 |
worker, viewgam, args, key, src, gamut_coverage |
| 16519 |
) -> None: |
| 16520 |
"""Gamut view creation producer. |
| 16521 |
|
| 16522 |
Args: |
| 16523 |
worker (Worker): Worker instance to execute the command. |
| 16524 |
viewgam (str): Path to the viewgam executable. |
| 16525 |
args (list): Arguments for the viewgam command. |
| 16526 |
key (str): Key for the gamut coverage dictionary. |
| 16527 |
src (str): Source file name for the gamut view. |
| 16528 |
gamut_coverage (dict): Dictionary to store the coverage percentage. |
| 16529 |
""" |
| 16530 |
try: |
| 16531 |
result = worker.exec_cmd( |
| 16532 |
viewgam, |
| 16533 |
args, |
| 16534 |
capture_output=True, |
| 16535 |
skip_scripts=True, |
| 16536 |
silent=True, |
| 16537 |
log_output=False, |
| 16538 |
) |
| 16539 |
if not isinstance(result, Exception) and result: |
| 16540 |
# viewgam output looks like this: |
| 16541 |
# Intersecting volume = xxx.x cubic units |
| 16542 |
# 'path/to/1.gam' volume = xxx.x cubic units, intersect = xx.xx% |
| 16543 |
# 'path/to/2.gam' volume = xxx.x cubic units, intersect = xx.xx% |
| 16544 |
for line in worker.output: |
| 16545 |
match = re.search( |
| 16546 |
rf"[/\\]{re.escape(src)}.gam'\s+volume\s*=\s*" |
| 16547 |
r"\d+(?:\.\d+)?\s+cubic\s+units,?" |
| 16548 |
r"\s+intersect\s*=\s*" |
| 16549 |
r"(\d+(?:\.\d+)?)", |
| 16550 |
line, |
| 16551 |
) |
| 16552 |
if match: |
| 16553 |
gamut_coverage[key] = float(match.groups()[0]) / 100.0 |
| 16554 |
break |
| 16555 |
except Exception: |
| 16556 |
traceback.print_exc() |
| 16557 |
worker.log(traceback.format_exc()) |
| 16558 |
|
| 16559 |
def calibrate(self, remove=False): |
| 16560 |
"""Calibrate the screen and process the generated file(s). |
| 16561 |
|
| 16562 |
Args: |
| 16563 |
remove (bool): If True, remove the generated calibration files |
| 16564 |
after processing. Defaults to False. |
| 16565 |
|
| 16566 |
Returns: |
| 16567 |
result (Exception or bool): Returns an Exception if an error |
| 16568 |
occurs, or True if the calibration was successful. If no |
| 16569 |
calibration was performed, it returns False. |
| 16570 |
""" |
| 16571 |
result = self.detect_video_levels() |
| 16572 |
if isinstance(result, Exception) or not result: |
| 16573 |
return result |
| 16574 |
capture_output = False |
| 16575 |
if sys.stdout and hasattr(sys.stdout, "isatty") and not sys.stdout.isatty(): |
| 16576 |
capture_output = True |
| 16577 |
cmd, args = self.prepare_dispcal() |
| 16578 |
if not isinstance(cmd, Exception): |
| 16579 |
max_diffuser_retries = 2 |
| 16580 |
diffuser_retries = 0 |
| 16581 |
while True: |
| 16582 |
result = self.exec_cmd(cmd, args, capture_output=capture_output) |
| 16583 |
# Argyll's specbos driver spawns a background "Diffuser thread" |
| 16584 |
# that polls the instrument over the same serial port as |
| 16585 |
# measurements, causing a race condition. When this happens |
| 16586 |
# dispcal exits with "Instrument Access Failed". Restarting |
| 16587 |
# dispcal opens a fresh serial connection and usually avoids |
| 16588 |
# the race on subsequent attempts. |
| 16589 |
if ( |
| 16590 |
isinstance(result, Exception) |
| 16591 |
and not self.subprocess_abort |
| 16592 |
and diffuser_retries < max_diffuser_retries |
| 16593 |
and "Instrument Access Failed" in str(result) |
| 16594 |
and any( |
| 16595 |
"Diffuser thread failed" in line for line in self.output |
| 16596 |
) |
| 16597 |
): |
| 16598 |
diffuser_retries += 1 |
| 16599 |
self.log( |
| 16600 |
f"{APPNAME}: Calibration failed due to instrument " |
| 16601 |
"communication issue (Diffuser thread conflict). " |
| 16602 |
f"Retrying (attempt {diffuser_retries} of " |
| 16603 |
f"{max_diffuser_retries})..." |
| 16604 |
) |
| 16605 |
continue |
| 16606 |
break |
| 16607 |
else: |
| 16608 |
result = cmd |
| 16609 |
if not isinstance(result, Exception) and result and getcfg("trc"): |
| 16610 |
dst_pathname = os.path.join( |
| 16611 |
getcfg("profile.save_path"), |
| 16612 |
getcfg("profile.name.expanded"), |
| 16613 |
getcfg("profile.name.expanded"), |
| 16614 |
) |
| 16615 |
cal = args[-1] + ".cal" |
| 16616 |
result = check_cal_isfile( |
| 16617 |
cal, lang.getstr("error.calibration.file_not_created") |
| 16618 |
) |
| 16619 |
if not isinstance(result, Exception) and result: |
| 16620 |
cal_cgats = add_dispcal_options_to_cal(cal, self.options_dispcal) |
| 16621 |
if cal_cgats: |
| 16622 |
cal_cgats.write() |
| 16623 |
if getcfg("profile.update") or self.dispcal_create_fast_matrix_shaper: |
| 16624 |
profile_path = args[-1] + PROFILE_EXT |
| 16625 |
result = check_profile_isfile( |
| 16626 |
profile_path, lang.getstr("error.profile.file_not_created") |
| 16627 |
) |
| 16628 |
if not isinstance(result, Exception) and result: |
| 16629 |
try: |
| 16630 |
profile = ICCProfile(profile_path) |
| 16631 |
except (OSError, ICCProfileInvalidError): |
| 16632 |
result = Error( |
| 16633 |
lang.getstr("profile.invalid") + "\n" + profile_path |
| 16634 |
) |
| 16635 |
if not isinstance(result, Exception) and result: |
| 16636 |
if not getcfg("profile.update"): |
| 16637 |
# Created fast matrix shaper profile |
| 16638 |
# we need to set cprt, targ and a few other things |
| 16639 |
profile.setCopyright(getcfg("copyright")) |
| 16640 |
# Fast matrix shaper profiles currently don't |
| 16641 |
# contain TI3 data, but look for it anyways |
| 16642 |
# to be future-proof |
| 16643 |
ti3 = add_options_to_ti3( |
| 16644 |
profile.tags.get("targ", profile.tags.get("CIED", "")), |
| 16645 |
self.options_dispcal, |
| 16646 |
) |
| 16647 |
if not ti3: |
| 16648 |
ti3 = CGATS("TI3\n") |
| 16649 |
ti3[1] = cal_cgats |
| 16650 |
edid = self.get_display_edid() |
| 16651 |
display_name = edid.get( |
| 16652 |
"monitor_name", |
| 16653 |
edid.get("ascii", str(edid.get("product_id") or "")), |
| 16654 |
) |
| 16655 |
display_manufacturer = edid.get("manufacturer") |
| 16656 |
profile.setDeviceModelDescription(display_name) |
| 16657 |
if display_manufacturer: |
| 16658 |
profile.setDeviceManufacturerDescription( |
| 16659 |
display_manufacturer |
| 16660 |
) |
| 16661 |
(gamut_volume, gamut_coverage) = self.create_gamut_views( |
| 16662 |
profile_path |
| 16663 |
) |
| 16664 |
self.update_profile( |
| 16665 |
profile, |
| 16666 |
ti3=str(ti3), |
| 16667 |
chrm=None, |
| 16668 |
tags=True, |
| 16669 |
avg=None, |
| 16670 |
peak=None, |
| 16671 |
rms=None, |
| 16672 |
gamut_volume=gamut_volume, |
| 16673 |
gamut_coverage=gamut_coverage, |
| 16674 |
quality=getcfg("calibration.quality"), |
| 16675 |
) |
| 16676 |
else: |
| 16677 |
# Update desc tag - ASCII needs to be 7-bit |
| 16678 |
# also add Unicode string if different from ASCII |
| 16679 |
if "desc" in profile.tags and isinstance( |
| 16680 |
profile.tags.desc, TextDescriptionType |
| 16681 |
): |
| 16682 |
profile.setDescription(getcfg("profile.name.expanded")) |
| 16683 |
# Calculate profile ID |
| 16684 |
profile.calculate_id() |
| 16685 |
try: |
| 16686 |
profile.write() |
| 16687 |
except Exception as exception: |
| 16688 |
self.log(exception) |
| 16689 |
result2 = self.wrapup( |
| 16690 |
not isinstance(result, UnloggedInfo) and result, |
| 16691 |
remove or isinstance(result, Exception) or not result, |
| 16692 |
) |
| 16693 |
if isinstance(result2, Exception): |
| 16694 |
if isinstance(result, Exception): |
| 16695 |
result = Error(str(result) + "\n\n" + str(result2)) |
| 16696 |
else: |
| 16697 |
result = result2 |
| 16698 |
elif not isinstance(result, Exception) and result and getcfg("trc"): |
| 16699 |
setcfg("last_cal_path", dst_pathname + ".cal") |
| 16700 |
setcfg("calibration.file.previous", getcfg("calibration.file", False)) |
| 16701 |
if getcfg("profile.update") or self.dispcal_create_fast_matrix_shaper: |
| 16702 |
setcfg("last_cal_or_icc_path", dst_pathname + PROFILE_EXT) |
| 16703 |
setcfg("last_icc_path", dst_pathname + PROFILE_EXT) |
| 16704 |
setcfg("calibration.file", dst_pathname + PROFILE_EXT) |
| 16705 |
else: |
| 16706 |
setcfg("calibration.file", dst_pathname + ".cal") |
| 16707 |
setcfg("last_cal_or_icc_path", dst_pathname + ".cal") |
| 16708 |
return result |
| 16709 |
|
| 16710 |
@property |
| 16711 |
def calibration_loading_generally_supported(self): |
| 16712 |
"""Check if loading/clearing calibration is generally supported. |
| 16713 |
|
| 16714 |
Returns: |
| 16715 |
bool: True if loading/clearing calibration is generally supported, |
| 16716 |
False otherwise. |
| 16717 |
""" |
| 16718 |
# Loading/clearing calibration seems to have undesirable side-effects |
| 16719 |
# on Mac OS X 10.6 and newer |
| 16720 |
# Wayland does not support videoLUT access (only by installing a |
| 16721 |
# profile via colord) |
| 16722 |
return ( |
| 16723 |
sys.platform != "darwin" |
| 16724 |
or intlist(platform.mac_ver()[0].split(".")) < [10, 6] |
| 16725 |
) and os.getenv("XDG_SESSION_TYPE") != "wayland" |
| 16726 |
|
| 16727 |
@property |
| 16728 |
def calibration_loading_supported(self): |
| 16729 |
"""Check if loading/clearing calibration is supported. |
| 16730 |
|
| 16731 |
Returns: |
| 16732 |
bool: True if loading/clearing calibration is supported, False |
| 16733 |
otherwise. |
| 16734 |
""" |
| 16735 |
# Loading/clearing calibration seems to have undesirable side-effects |
| 16736 |
# on Mac OS X 10.6 and newer |
| 16737 |
return ( |
| 16738 |
self.calibration_loading_generally_supported |
| 16739 |
and not config.is_virtual_display() |
| 16740 |
) |
| 16741 |
|
| 16742 |
def change_display_profile_cal_whitepoint( |
| 16743 |
self, profile, x, y, outfilename, calibration_only=False, use_collink=False |
| 16744 |
): |
| 16745 |
"""Change display profile (and calibration) whitepoint. |
| 16746 |
|
| 16747 |
Do it in an colorimetrically accurate manner (as far as possible). |
| 16748 |
|
| 16749 |
""" |
| 16750 |
XYZw = colormath.xyY2XYZ(x, y) |
| 16751 |
xicclu = get_argyll_util("xicclu") |
| 16752 |
if not xicclu: |
| 16753 |
return Error(lang.getstr("argyll.util.not_found", "xicclu")) |
| 16754 |
tempdir = self.create_tempdir() |
| 16755 |
if isinstance(tempdir, Exception): |
| 16756 |
return tempdir |
| 16757 |
outpathname = os.path.splitext(outfilename)[0] |
| 16758 |
outname = os.path.basename(outpathname) |
| 16759 |
logfiles = Files([self.recent, self.lastmsg, LineBufferedStream(print)]) |
| 16760 |
ofilename = profile.filename |
| 16761 |
temppathname = os.path.join(tempdir, outname) |
| 16762 |
if ofilename and os.path.isfile(ofilename): |
| 16763 |
# Profile comes from a file |
| 16764 |
temp = False |
| 16765 |
temporig = ofilename |
| 16766 |
else: |
| 16767 |
# Profile not associated to a file, write to temp dir |
| 16768 |
temp = True |
| 16769 |
profile.filename = temporig = temppathname + ".orig.icc" |
| 16770 |
profile.write(temporig) |
| 16771 |
# Remember original white XYZ |
| 16772 |
origXYZ = profile.tags.wtpt.X, profile.tags.wtpt.Y, profile.tags.wtpt.Z |
| 16773 |
# Make a copy of the profile with changed whitepoint |
| 16774 |
profile.tags.wtpt.X, profile.tags.wtpt.Y, profile.tags.wtpt.Z = XYZw |
| 16775 |
tempcopy = temppathname + ".copy.icc" |
| 16776 |
profile.write(tempcopy) |
| 16777 |
# Generate updated calibration with changed whitepoint |
| 16778 |
if use_collink: |
| 16779 |
collink = get_argyll_util("collink") |
| 16780 |
if not collink: |
| 16781 |
profile.filename = ofilename |
| 16782 |
self.wrapup(False) |
| 16783 |
return Error(lang.getstr("argyll.util.not_found", "collink")) |
| 16784 |
linkpath = temppathname + ".link.icc" |
| 16785 |
result = self.exec_cmd( |
| 16786 |
collink, |
| 16787 |
["-v", "-n", "-G", "-iaw", "-b", tempcopy, temporig, linkpath], |
| 16788 |
capture_output=True, |
| 16789 |
) |
| 16790 |
if not result or isinstance(result, Exception): |
| 16791 |
profile.filename = ofilename |
| 16792 |
self.wrapup(False) |
| 16793 |
return result |
| 16794 |
link = ICCProfile(linkpath) |
| 16795 |
RGBscaled = [[i / 255.0] * 3 for i in range(256)] |
| 16796 |
RGBscaled = self.xicclu(link, RGBscaled) |
| 16797 |
logfiles.write("RGB white {:6.4f} {:6.4f} {:6.4f}\n".format(*RGBscaled[-1])) |
| 16798 |
# Restore original white XYZ |
| 16799 |
profile.tags.wtpt.X, profile.tags.wtpt.Y, profile.tags.wtpt.Z = origXYZ |
| 16800 |
# Get white RGB |
| 16801 |
XYZwscaled = self.xicclu(profile, RGBscaled[-1], "a", pcs="x")[0] |
| 16802 |
logfiles.write( |
| 16803 |
"XYZ white {:6.4f} {:6.4f} {:6.4f}, CCT {:0.0f}\n".format( |
| 16804 |
*[*XYZwscaled, colormath.XYZ2CCT(*XYZwscaled)] |
| 16805 |
) |
| 16806 |
) |
| 16807 |
else: |
| 16808 |
# Lookup scaled down white XYZ |
| 16809 |
logfiles.write("Looking for solution...\n") |
| 16810 |
XYZscaled = [[v * (1 - i / 1999.0) for v in XYZw] for i in range(2000)] |
| 16811 |
RGBscaled = self.xicclu( |
| 16812 |
profile, XYZscaled, "a", "if", pcs="x", get_clip=True |
| 16813 |
) |
| 16814 |
# Set filename to copy (used by worker.xicclu to get profile path) |
| 16815 |
profile.filename = tempcopy |
| 16816 |
# Find point at which it no longer clips |
| 16817 |
for i, RGBclip in enumerate(RGBscaled): |
| 16818 |
if RGBclip[3] is True: |
| 16819 |
# Clipped, skip |
| 16820 |
continue |
| 16821 |
# Found |
| 16822 |
XYZwscaled = XYZscaled[i] |
| 16823 |
logfiles.write( |
| 16824 |
f"Solution found at index {i:d} (step size {1 / 1999.0:f})\n" |
| 16825 |
) |
| 16826 |
logfiles.write( |
| 16827 |
"RGB white {:6.4f} {:6.4f} {:6.4f}\n".format(*RGBclip[:3]) |
| 16828 |
) |
| 16829 |
logfiles.write( |
| 16830 |
"XYZ white {:6.4f} {:6.4f} {:6.4f}, CCT {:0.0f}\n".format( |
| 16831 |
*(XYZscaled[i] + [colormath.XYZ2CCT(*XYZscaled[i])]) |
| 16832 |
) |
| 16833 |
) |
| 16834 |
break |
| 16835 |
else: |
| 16836 |
profile.filename = ofilename |
| 16837 |
self.wrapup(False) |
| 16838 |
return Error(f"No solution found in {i:d} steps") |
| 16839 |
# Generate RGB input values |
| 16840 |
# Reduce interpolation res as target whitepoint moves farther away |
| 16841 |
# from profile whitepoint in RGB |
| 16842 |
res = max(round((min(RGBclip[:3]) / 1.0) * 33), 9) |
| 16843 |
logfiles.write(f"Interpolation res {res:d}\n") |
| 16844 |
RGBscaled = [] |
| 16845 |
for i in range(res): |
| 16846 |
RGBscaled.append([v * (i / (res - 1.0)) for v in (1, 1, 1)]) |
| 16847 |
# Lookup RGB -> XYZ through whitepoint adjusted profile |
| 16848 |
RGBscaled2XYZ = self.xicclu(profile, RGBscaled, "a", pcs="x") |
| 16849 |
# Restore original XYZ |
| 16850 |
profile.tags.wtpt.X, profile.tags.wtpt.Y, profile.tags.wtpt.Z = origXYZ |
| 16851 |
# Restore original filename (used by worker.xicclu to get profile path) |
| 16852 |
profile.filename = temporig |
| 16853 |
# Get original black point |
| 16854 |
XYZk = self.xicclu(profile, [0, 0, 0], "a", pcs="x")[0] |
| 16855 |
logfiles.write("XYZ black {:6.4f} {:6.4f} {:6.4f}\n".format(*XYZk)) |
| 16856 |
logfiles.write( |
| 16857 |
"XYZ white after forward lookup {:6.4f} {:6.4f} {:6.4f}\n".format( |
| 16858 |
*RGBscaled2XYZ[-1] |
| 16859 |
) |
| 16860 |
) |
| 16861 |
# Scale down XYZ |
| 16862 |
XYZscaled = [] |
| 16863 |
for i in range(res): |
| 16864 |
XYZ = [v * XYZwscaled[1] for v in RGBscaled2XYZ[i]] |
| 16865 |
if i == 0: |
| 16866 |
bp_in = XYZ |
| 16867 |
XYZ = colormath.apply_bpc( |
| 16868 |
*XYZ, bp_in=bp_in, bp_out=XYZk, wp_out=XYZwscaled, weight=True |
| 16869 |
) |
| 16870 |
XYZscaled.append(XYZ) |
| 16871 |
logfiles.write( |
| 16872 |
"XYZ white after scale down {:6.4f} {:6.4f} {:6.4f}\n".format( |
| 16873 |
*XYZscaled[-1] |
| 16874 |
) |
| 16875 |
) |
| 16876 |
# Lookup XYZ -> RGB through original profile |
| 16877 |
RGBscaled = self.xicclu( |
| 16878 |
profile, XYZscaled, "a", "if", pcs="x", use_cam_clipping=True |
| 16879 |
) |
| 16880 |
logfiles.write( |
| 16881 |
"RGB black after inverse forward lookup" |
| 16882 |
" {:6.4f} {:6.4f} {:6.4f}\n".format(*RGBscaled[0]) |
| 16883 |
) |
| 16884 |
logfiles.write( |
| 16885 |
"RGB white after inverse forward lookup " |
| 16886 |
"{:6.4f} {:6.4f} {:6.4f}\n".format(*RGBscaled[-1]) |
| 16887 |
) |
| 16888 |
if res != 256: |
| 16889 |
# Interpolate |
| 16890 |
R = [] |
| 16891 |
G = [] |
| 16892 |
B = [] |
| 16893 |
for RGB in RGBscaled: |
| 16894 |
R.append(RGB[0]) |
| 16895 |
G.append(RGB[1]) |
| 16896 |
B.append(RGB[2]) |
| 16897 |
if res > 2: |
| 16898 |
# Catmull-Rom spline interpolation |
| 16899 |
Ri = CRInterpolation(R) |
| 16900 |
Gi = CRInterpolation(G) |
| 16901 |
Bi = CRInterpolation(B) |
| 16902 |
else: |
| 16903 |
# Linear interpolation |
| 16904 |
Ri = colormath.Interp(list(range(res)), R) |
| 16905 |
Gi = colormath.Interp(list(range(res)), G) |
| 16906 |
Bi = colormath.Interp(list(range(res)), B) |
| 16907 |
RGBscaled = [] |
| 16908 |
step = (res - 1) / 255.0 |
| 16909 |
for i in range(256): |
| 16910 |
RGB = [Ri(i * step), Gi(i * step), Bi(i * step)] |
| 16911 |
RGBscaled.append(RGB) |
| 16912 |
logfiles.write( |
| 16913 |
"RGB black after interpolation {:6.4f} {:6.4f} {:6.4f}\n".format( |
| 16914 |
*RGBscaled[0] |
| 16915 |
) |
| 16916 |
) |
| 16917 |
logfiles.write( |
| 16918 |
"RGB white after interpolation {:6.4f} {:6.4f} {:6.4f}\n".format( |
| 16919 |
*RGBscaled[-1] |
| 16920 |
) |
| 16921 |
) |
| 16922 |
has_nonlinear_vcgt = ( |
| 16923 |
isinstance(profile.tags.get("vcgt"), VideoCardGammaType) |
| 16924 |
and not profile.tags.vcgt.is_linear() |
| 16925 |
) |
| 16926 |
if has_nonlinear_vcgt: |
| 16927 |
# Apply cal |
| 16928 |
ocal = extract_cal_from_profile(profile) |
| 16929 |
bp_out = list(ocal.queryv1({"RGB_R": 0, "RGB_G": 0, "RGB_B": 0}).values()) |
| 16930 |
ocalpath = temppathname + ".cal" |
| 16931 |
ocal.filename = ocalpath |
| 16932 |
RGBscaled = self.xicclu(ocal, RGBscaled) |
| 16933 |
logfiles.write( |
| 16934 |
"RGB black after cal {:6.4f} {:6.4f} {:6.4f}\n".format(*RGBscaled[0]) |
| 16935 |
) |
| 16936 |
logfiles.write( |
| 16937 |
"RGB white after cal {:6.4f} {:6.4f} {:6.4f}\n".format(*RGBscaled[-1]) |
| 16938 |
) |
| 16939 |
else: |
| 16940 |
bp_out = (0, 0, 0) |
| 16941 |
cal = """CAL |
| 16942 |
|
| 16943 |
KEYWORD "DEVICE_CLASS" |
| 16944 |
DEVICE_CLASS "DISPLAY" |
| 16945 |
KEYWORD "COLOR_REP" |
| 16946 |
COLOR_REP "RGB" |
| 16947 |
BEGIN_DATA_FORMAT |
| 16948 |
RGB_I RGB_R RGB_G RGB_B |
| 16949 |
END_DATA_FORMAT |
| 16950 |
NUMBER_OF_SETS 256 |
| 16951 |
BEGIN_DATA |
| 16952 |
""" |
| 16953 |
for i, RGB in enumerate(RGBscaled): |
| 16954 |
R, G, B = colormath.apply_bpc( |
| 16955 |
*RGB, |
| 16956 |
bp_in=RGBscaled[0], |
| 16957 |
bp_out=bp_out, |
| 16958 |
wp_out=RGBscaled[-1], |
| 16959 |
weight=True, |
| 16960 |
) |
| 16961 |
cal += f"{i / 255.0:f} {R:f} {G:f} {B:f}\n" |
| 16962 |
cal += "END_DATA" |
| 16963 |
cal = CGATS(cal) |
| 16964 |
cal.filename = outpathname + ".cal" |
| 16965 |
cal.write() |
| 16966 |
if calibration_only: |
| 16967 |
# Only update calibration |
| 16968 |
profile.setDescription(outname) |
| 16969 |
profile.tags.vcgt = cal_to_fake_profile(cal).tags.vcgt |
| 16970 |
profile.tags.wtpt.X, profile.tags.wtpt.Y, profile.tags.wtpt.Z = XYZw |
| 16971 |
profile.calculate_id() |
| 16972 |
profile.write(outfilename) |
| 16973 |
self.wrapup(False) |
| 16974 |
return True |
| 16975 |
# Re-create profile |
| 16976 |
cti3 = None |
| 16977 |
if isinstance(profile.tags.get("targ"), Text): |
| 16978 |
# Get measurement data |
| 16979 |
try: |
| 16980 |
cti3 = CGATS(profile.tags.targ) |
| 16981 |
except (OSError, CGATSError): |
| 16982 |
pass |
| 16983 |
else: |
| 16984 |
if 0 not in cti3 or cti3[0].type.strip() != b"CTI3": |
| 16985 |
# Not Argyll measurement data |
| 16986 |
cti3 = None |
| 16987 |
if not cti3: |
| 16988 |
# Use fakeread |
| 16989 |
fakeread = get_argyll_util("fakeread") |
| 16990 |
if not fakeread: |
| 16991 |
profile.filename = ofilename |
| 16992 |
self.wrapup(False) |
| 16993 |
return Error(lang.getstr("argyll.util.not_found", "fakeread")) |
| 16994 |
shutil.copyfile(DEFAULTS["testchart.file"], temppathname + ".ti1") |
| 16995 |
result = self.exec_cmd(fakeread, [temporig, temppathname]) |
| 16996 |
if not result or isinstance(result, Exception): |
| 16997 |
profile.filename = ofilename |
| 16998 |
self.wrapup(False) |
| 16999 |
return result |
| 17000 |
cti3 = CGATS(temppathname + ".ti3") |
| 17001 |
# Get RGB from measurement data |
| 17002 |
RGBorig = [] |
| 17003 |
for sample in cti3[0].DATA.values(): |
| 17004 |
RGB = [] |
| 17005 |
for component in "RGB": |
| 17006 |
RGB.append(sample[f"RGB_{component}"]) |
| 17007 |
RGBorig.append(RGB) |
| 17008 |
# Lookup RGB -> scaled RGB through calibration |
| 17009 |
RGBscaled = self.xicclu(cal, RGBorig, scale=100) |
| 17010 |
if has_nonlinear_vcgt: |
| 17011 |
# Undo original calibration |
| 17012 |
RGBscaled = self.xicclu(ocal, RGBscaled, direction="b", scale=100) |
| 17013 |
# Update CAL in ti3 file |
| 17014 |
if 1 in cti3 and cti3[1].type.strip() == b"CAL": |
| 17015 |
cti3[1].DATA = cal[0].DATA |
| 17016 |
else: |
| 17017 |
cti3[1] = cal[0] |
| 17018 |
# Lookup scaled RGB -> XYZ through profile |
| 17019 |
RGBscaled2XYZ = self.xicclu(profile, RGBscaled, "a", pcs="x", scale=100) |
| 17020 |
# Update measurement data |
| 17021 |
if "LUMINANCE_XYZ_CDM2" in cti3[0]: |
| 17022 |
XYZa = [ |
| 17023 |
float(v) * XYZwscaled[i] |
| 17024 |
for i, v in enumerate(cti3[0].LUMINANCE_XYZ_CDM2.split()) |
| 17025 |
] |
| 17026 |
cti3[0].add_keyword("LUMINANCE_XYZ_CDM2", " ".join([str(v) for v in XYZa])) |
| 17027 |
for i, sample in cti3[0].DATA.items(): |
| 17028 |
for j, component in enumerate("XYZ"): |
| 17029 |
sample["XYZ_" + component] = RGBscaled2XYZ[i][j] / XYZwscaled[1] * 100 |
| 17030 |
cti3.write(temppathname + ".ti3") |
| 17031 |
# Preserve custom tags |
| 17032 |
display_name = profile.getDeviceModelDescription() |
| 17033 |
display_manufacturer = profile.getDeviceManufacturerDescription() |
| 17034 |
tags = {} |
| 17035 |
for tagname in ("mmod", "meta"): |
| 17036 |
if tagname in profile.tags: |
| 17037 |
tags[tagname] = profile.tags[tagname] |
| 17038 |
if temp: |
| 17039 |
os.remove(temporig) |
| 17040 |
os.remove(tempcopy) |
| 17041 |
# Compute profile |
| 17042 |
self.options_targen = ["-d3"] |
| 17043 |
return self.create_profile( |
| 17044 |
outfilename, True, display_name, display_manufacturer, tags |
| 17045 |
) |
| 17046 |
|
| 17047 |
def chart_lookup( |
| 17048 |
self, |
| 17049 |
cgats, |
| 17050 |
profile, |
| 17051 |
as_ti3=False, |
| 17052 |
fields=None, |
| 17053 |
check_missing_fields=False, |
| 17054 |
function="f", |
| 17055 |
pcs="l", |
| 17056 |
intent="r", |
| 17057 |
bt1886=None, |
| 17058 |
white_patches=4, |
| 17059 |
white_patches_total=True, |
| 17060 |
raise_exceptions=False, |
| 17061 |
): |
| 17062 |
"""Lookup CIE or device values through profile.""" |
| 17063 |
if profile.colorSpace == b"RGB": |
| 17064 |
labels = ("RGB_R", "RGB_G", "RGB_B") |
| 17065 |
else: |
| 17066 |
labels = ("CMYK_C", "CMYK_M", "CMYK_Y", "CMYK_K") |
| 17067 |
ti1 = None |
| 17068 |
ti3_ref = None |
| 17069 |
gray = None |
| 17070 |
try: |
| 17071 |
if not isinstance(cgats, CGATS): |
| 17072 |
cgats = CGATS(cgats, True) |
| 17073 |
else: |
| 17074 |
# Always make a copy and do not alter a passed in CGATS instance! |
| 17075 |
cgats_filename = cgats.filename |
| 17076 |
cgats = CGATS(bytes(cgats)) |
| 17077 |
cgats.filename = cgats_filename |
| 17078 |
if 0 in cgats: |
| 17079 |
# only look at the first section |
| 17080 |
cgats[0].filename = cgats.filename |
| 17081 |
cgats = cgats[0] |
| 17082 |
primaries = cgats.queryi(labels) |
| 17083 |
if primaries and not as_ti3: |
| 17084 |
primaries.fix_device_values_scaling(profile.colorSpace) |
| 17085 |
cgats.type = b"CTI1" |
| 17086 |
cgats.COLOR_REP = profile.colorSpace |
| 17087 |
ti1, ti3_ref, gray = self.ti1_lookup_to_ti3( |
| 17088 |
cgats, |
| 17089 |
profile, |
| 17090 |
function, |
| 17091 |
pcs, |
| 17092 |
"r", |
| 17093 |
white_patches, |
| 17094 |
white_patches_total, |
| 17095 |
) |
| 17096 |
if bt1886 or intent == "a": |
| 17097 |
cat = profile.guess_cat() or "Bradford" |
| 17098 |
for item in ti3_ref.DATA.values(): |
| 17099 |
if pcs == "l": |
| 17100 |
X, Y, Z = colormath.Lab2XYZ( |
| 17101 |
item["LAB_L"], item["LAB_A"], item["LAB_B"] |
| 17102 |
) |
| 17103 |
else: |
| 17104 |
X, Y, Z = ( |
| 17105 |
v / 100.0 |
| 17106 |
for v in (item["XYZ_X"], item["XYZ_Y"], item["XYZ_Z"]) |
| 17107 |
) |
| 17108 |
if bt1886: |
| 17109 |
X, Y, Z = bt1886.apply(X, Y, Z) |
| 17110 |
if intent == "a": |
| 17111 |
X, Y, Z = colormath.adapt( |
| 17112 |
X, |
| 17113 |
Y, |
| 17114 |
Z, |
| 17115 |
"D50", |
| 17116 |
list(profile.tags.wtpt.values()), |
| 17117 |
cat=cat, |
| 17118 |
) |
| 17119 |
X, Y, Z = [v * 100 for v in (X, Y, Z)] |
| 17120 |
if pcs == "l": |
| 17121 |
( |
| 17122 |
item["LAB_L"], |
| 17123 |
item["LAB_A"], |
| 17124 |
item["LAB_B"], |
| 17125 |
) = colormath.XYZ2Lab(X, Y, Z) |
| 17126 |
else: |
| 17127 |
item["XYZ_X"], item["XYZ_Y"], item["XYZ_Z"] = X, Y, Z |
| 17128 |
else: |
| 17129 |
if not primaries and check_missing_fields: |
| 17130 |
raise ValueError( |
| 17131 |
lang.getstr( |
| 17132 |
"error.testchart.missing_fields", |
| 17133 |
(cgats.filename, ", ".join(labels)), |
| 17134 |
) |
| 17135 |
) |
| 17136 |
ti1, ti3_ref = self.ti3_lookup_to_ti1( |
| 17137 |
cgats, profile, fields, intent, white_patches |
| 17138 |
) |
| 17139 |
except Exception as exception: |
| 17140 |
traceback.print_exc() |
| 17141 |
if raise_exceptions: |
| 17142 |
raise exception |
| 17143 |
if not isinstance(exception, (TypeError, ValueError)) or isinstance( |
| 17144 |
exception, UnicodeError |
| 17145 |
): |
| 17146 |
handle_error(exception, self.owner) |
| 17147 |
else: |
| 17148 |
show_result_dialog(exception, self.owner) |
| 17149 |
return ti1, ti3_ref, gray |
| 17150 |
|
| 17151 |
def ti1_lookup_to_ti3( |
| 17152 |
self, |
| 17153 |
ti1, |
| 17154 |
profile, |
| 17155 |
function="f", |
| 17156 |
pcs=None, |
| 17157 |
intent="r", |
| 17158 |
white_patches=4, |
| 17159 |
white_patches_total=True, |
| 17160 |
): |
| 17161 |
"""Read TI1 (filename or CGATS instance) and lookup device->pcs values. |
| 17162 |
|
| 17163 |
Lookup device->pcs values colorimetrically through profile using |
| 17164 |
Argyll's xicclu utility and return TI3 (CGATS instance). |
| 17165 |
|
| 17166 |
Args: |
| 17167 |
ti1 (str or CGATS): Filename of TI1 file or CGATS instance. |
| 17168 |
profile (ICCProfile): ICC profile to use for lookup. |
| 17169 |
function (str): Function to use for lookup, 'f' for forward, |
| 17170 |
'b' for backward, 'a' for adapt. |
| 17171 |
pcs (str): PCS color space, 'l' for Lab, 'x' for XYZ. |
| 17172 |
intent (str): Rendering intent, 'r' for relative colorimetric, |
| 17173 |
'a' for absolute colorimetric. |
| 17174 |
white_patches (int): Number of white patches to add to the TI1. |
| 17175 |
white_patches_total (bool): If True, ensure total of n white |
| 17176 |
patches, if False, add exactly n white patches. |
| 17177 |
|
| 17178 |
Raises: |
| 17179 |
TypeError: If `ti1` is not a CGATS instance or a valid filename. |
| 17180 |
ValueError: If `ti1` is invalid or missing required fields. |
| 17181 |
|
| 17182 |
Returns: |
| 17183 |
tuple: A tuple containing: |
| 17184 |
- CGATS instance of TI3 with device->pcs values. |
| 17185 |
- CGATS instance of TI3 with reference values (if available). |
| 17186 |
- Gray patch data (if available). |
| 17187 |
""" |
| 17188 |
# ti1 |
| 17189 |
if isinstance(ti1, str): |
| 17190 |
ti1 = CGATS(ti1) |
| 17191 |
if not isinstance(ti1, CGATS): |
| 17192 |
raise TypeError( |
| 17193 |
"Wrong type for ti1, needs to be a CGATS instance, " |
| 17194 |
f"not {ti1.__class__.__name__}" |
| 17195 |
) |
| 17196 |
|
| 17197 |
# profile |
| 17198 |
if isinstance(profile, str): |
| 17199 |
profile = ICCProfile(profile) |
| 17200 |
if not isinstance(profile, ICCProfile): |
| 17201 |
raise TypeError( |
| 17202 |
"Wrong type for profile, needs to be a ICCProfile instance, " |
| 17203 |
f"not {profile.__class__.__name__}" |
| 17204 |
) |
| 17205 |
|
| 17206 |
# determine pcs for lookup |
| 17207 |
color_rep = profile.connectionColorSpace.upper() |
| 17208 |
if color_rep == b"RGB": |
| 17209 |
pcs = None |
| 17210 |
elif not pcs: |
| 17211 |
if color_rep == b"LAB": |
| 17212 |
pcs = "l" |
| 17213 |
elif color_rep == b"XYZ": |
| 17214 |
pcs = "x" |
| 17215 |
else: |
| 17216 |
raise ValueError("Unknown CIE color representation " + color_rep) |
| 17217 |
elif pcs == "l": |
| 17218 |
color_rep = b"LAB" |
| 17219 |
elif pcs == "x": |
| 17220 |
color_rep = b"XYZ" |
| 17221 |
|
| 17222 |
# get profile color space |
| 17223 |
colorspace = profile.colorSpace |
| 17224 |
|
| 17225 |
# required fields for ti1 |
| 17226 |
if colorspace == b"CMYK": |
| 17227 |
required = ("CMYK_C", "CMYK_M", "CMYK_Y", "CMYK_K") |
| 17228 |
else: |
| 17229 |
required = ("RGB_R", "RGB_G", "RGB_B") |
| 17230 |
ti1_filename = ti1.filename |
| 17231 |
try: |
| 17232 |
ti1 = verify_cgats(ti1, required, True) |
| 17233 |
except CGATSInvalidError as e: |
| 17234 |
raise ValueError( |
| 17235 |
lang.getstr("error.testchart.invalid", ti1_filename) |
| 17236 |
) from e |
| 17237 |
except CGATSKeyError as e: |
| 17238 |
raise ValueError( |
| 17239 |
lang.getstr( |
| 17240 |
"error.testchart.missing_fields", |
| 17241 |
(ti1_filename, ", ".join(required)), |
| 17242 |
) |
| 17243 |
) from e |
| 17244 |
|
| 17245 |
# read device values from ti1 |
| 17246 |
data = ti1.queryv1("DATA") |
| 17247 |
if not data: |
| 17248 |
raise ValueError(lang.getstr("error.testchart.invalid", ti1_filename)) |
| 17249 |
device_data = data.queryv(required) |
| 17250 |
if not device_data: |
| 17251 |
raise ValueError( |
| 17252 |
lang.getstr( |
| 17253 |
"error.testchart.missing_fields", |
| 17254 |
(ti1_filename, ", ".join(required)), |
| 17255 |
) |
| 17256 |
) |
| 17257 |
|
| 17258 |
if colorspace == b"RGB" and white_patches: |
| 17259 |
# make sure the first four patches are white so the whitepoint can be |
| 17260 |
# averaged |
| 17261 |
white_rgb = {"RGB_R": 100, "RGB_G": 100, "RGB_B": 100} |
| 17262 |
white = dict(white_rgb) |
| 17263 |
wp = ti1.queryv1("APPROX_WHITE_POINT") |
| 17264 |
if wp: |
| 17265 |
wp = [float(v) for v in wp.split()] |
| 17266 |
wp = [rpad((v / wp[1]) * 100.0, data.vmaxlen) for v in wp] |
| 17267 |
else: |
| 17268 |
wp = colormath.get_standard_illuminant("D65", scale=100) |
| 17269 |
for label in list(data.parent.DATA_FORMAT.values()): |
| 17270 |
label = label.decode("utf-8") |
| 17271 |
if label not in white: |
| 17272 |
if label.upper() == "LAB_L": |
| 17273 |
value = 100 |
| 17274 |
elif label.upper() in ("LAB_A", "LAB_B"): |
| 17275 |
value = 0 |
| 17276 |
elif label.upper() == "XYZ_X": |
| 17277 |
value = wp[0] |
| 17278 |
elif label.upper() == "XYZ_Y": |
| 17279 |
value = 100 |
| 17280 |
elif label.upper() == "XYZ_Z": |
| 17281 |
value = wp[2] |
| 17282 |
else: |
| 17283 |
value = b"0" |
| 17284 |
white.update({label: value}) |
| 17285 |
white_added_count = 0 |
| 17286 |
if profile.profileClass != b"link": |
| 17287 |
if white_patches_total: |
| 17288 |
# Ensure total of n white patches |
| 17289 |
while len(data.queryi(white_rgb)) < white_patches: |
| 17290 |
data.insert(0, white) |
| 17291 |
white_added_count += 1 |
| 17292 |
else: |
| 17293 |
# Add exactly n white patches |
| 17294 |
while white_added_count < white_patches: |
| 17295 |
data.insert(0, white) |
| 17296 |
white_added_count += 1 |
| 17297 |
print(f"Added {white_added_count:d} white patch(es)") |
| 17298 |
|
| 17299 |
idata = [list(primaries.values()) for primaries in list(device_data.values())] |
| 17300 |
if DEBUG: |
| 17301 |
print(f"ti1_lookup_to_ti3 {profile.colorSpace} -> {color_rep} idata") |
| 17302 |
for v in idata: |
| 17303 |
print(" ".join(("{:3.4f}",) * len(v)).format(*v)) |
| 17304 |
|
| 17305 |
# lookup device->cie values through profile using (x)icclu |
| 17306 |
# |
| 17307 |
# Under older ArgyllCMS versions, we have to use DeviceLink profile with |
| 17308 |
# icclu, because older xicclu cannot handle devicelink |
| 17309 |
use_icclu = not (pcs or self.argyll_version >= [1, 6]) |
| 17310 |
|
| 17311 |
input_encoding = None |
| 17312 |
output_encoding = None |
| 17313 |
if not pcs: |
| 17314 |
# Try to determine input/output encoding for devicelink |
| 17315 |
if isinstance(profile.tags.get("meta"), DictType): |
| 17316 |
input_encoding = profile.tags.meta.getvalue("encoding.input") |
| 17317 |
output_encoding = profile.tags.meta.getvalue("encoding.output") |
| 17318 |
if input_encoding == "T": |
| 17319 |
# 'T' (clip wtw on input) not supported for xicclu |
| 17320 |
input_encoding = "t" |
| 17321 |
# Fall back to configured 3D LUT encoding |
| 17322 |
if ( |
| 17323 |
not input_encoding |
| 17324 |
or input_encoding not in config.VALID_VALUES["3dlut.encoding.input"] |
| 17325 |
): |
| 17326 |
input_encoding = getcfg("3dlut.encoding.input") |
| 17327 |
if input_encoding == "T": |
| 17328 |
# 'T' (clip wtw on input) not supported for xicclu |
| 17329 |
input_encoding = "t" |
| 17330 |
if ( |
| 17331 |
not output_encoding |
| 17332 |
or output_encoding not in config.VALID_VALUES["3dlut.encoding.output"] |
| 17333 |
): |
| 17334 |
output_encoding = getcfg("3dlut.encoding.output") |
| 17335 |
if self.argyll_version < [1, 6] and not ( |
| 17336 |
input_encoding == output_encoding == "n" |
| 17337 |
): |
| 17338 |
# Fail if encoding is not n (data levels) |
| 17339 |
raise ValueError( |
| 17340 |
"The used version of ArgyllCMS only" |
| 17341 |
"supports full range RGB encoding." |
| 17342 |
) |
| 17343 |
|
| 17344 |
odata = self.xicclu( |
| 17345 |
profile, |
| 17346 |
idata, |
| 17347 |
intent, |
| 17348 |
function, |
| 17349 |
pcs=pcs, |
| 17350 |
scale=100, |
| 17351 |
use_icclu=use_icclu, |
| 17352 |
input_encoding=input_encoding, |
| 17353 |
output_encoding=output_encoding, |
| 17354 |
) |
| 17355 |
|
| 17356 |
gray = [] |
| 17357 |
igray = [] |
| 17358 |
igray_idx = [] |
| 17359 |
if colorspace == b"RGB": |
| 17360 |
# treat r=g=b specially: set expected a=b=0 |
| 17361 |
for i, cie in enumerate(odata): |
| 17362 |
r, g, b = idata[i] |
| 17363 |
if r == g == b < 100: |
| 17364 |
# if grayscale and not white |
| 17365 |
if pcs == "x": |
| 17366 |
# Need to scale XYZ coming from xicclu |
| 17367 |
# Lab is already scaled |
| 17368 |
cie = colormath.XYZ2Lab(*[n * 100.0 for n in cie]) |
| 17369 |
cie = (cie[0], 0, 0) # set a=b=0 |
| 17370 |
igray.append("{} {} {}".format(*cie)) |
| 17371 |
igray_idx.append(i) |
| 17372 |
if pcs == "x": |
| 17373 |
cie = colormath.Lab2XYZ(*cie) |
| 17374 |
luminance = cie[1] |
| 17375 |
else: |
| 17376 |
luminance = colormath.Lab2XYZ(*cie)[1] |
| 17377 |
if luminance * 100.0 >= 1: |
| 17378 |
# only add if luminance is greater or equal 1% because |
| 17379 |
# dark tones fluctuate too much |
| 17380 |
gray.append((r, g, b)) |
| 17381 |
if False: # NEVER? |
| 17382 |
# set cie in odata to a=b=0 |
| 17383 |
odata[i] = cie |
| 17384 |
|
| 17385 |
if False: # if igray: # NEVER? |
| 17386 |
# lookup cie->device values for grays through profile using xicclu |
| 17387 |
gray = [] |
| 17388 |
ogray = self.xicclu(profile, igray, "r", "b", pcs="l", scale=100) |
| 17389 |
for i, rgb in enumerate(ogray): |
| 17390 |
cie = idata[i] |
| 17391 |
if colormath.Lab2XYZ(cie[0], 0, 0)[1] * 100.0 >= 1: |
| 17392 |
# only add if luminance is greater or equal 1% because |
| 17393 |
# dark tones fluctuate too much |
| 17394 |
gray.append(rgb) |
| 17395 |
# update values in ti1 and data for ti3 |
| 17396 |
for n, channel in enumerate(("R", "G", "B")): |
| 17397 |
data[igray_idx[i] + white_added_count]["RGB_" + channel] = rgb[n] |
| 17398 |
odata[igray_idx[i]] = cie |
| 17399 |
|
| 17400 |
# write output ti3 |
| 17401 |
ofile = BytesIO() |
| 17402 |
if pcs: |
| 17403 |
ofile.write(b"CTI3 \n") |
| 17404 |
ofile.write( |
| 17405 |
b'\nDESCRIPTOR "Argyll Calibration Target chart information 3"\n' |
| 17406 |
) |
| 17407 |
else: |
| 17408 |
ofile.write(b"CTI1 \n") |
| 17409 |
ofile.write( |
| 17410 |
b'\nDESCRIPTOR "Argyll Calibration Target chart information 1"\n' |
| 17411 |
) |
| 17412 |
ofile.write(b'KEYWORD "DEVICE_CLASS"\n') |
| 17413 |
ofile.write( |
| 17414 |
b'DEVICE_CLASS "' |
| 17415 |
+ (b"DISPLAY" if colorspace == b"RGB" else b"OUTPUT") |
| 17416 |
+ b'"\n' |
| 17417 |
) |
| 17418 |
include_sample_name = False |
| 17419 |
for i, cie in enumerate(odata): |
| 17420 |
if i == 0: |
| 17421 |
icolor = profile.colorSpace |
| 17422 |
if icolor == b"RGB": |
| 17423 |
olabel = b"RGB_R RGB_G RGB_B" |
| 17424 |
elif icolor == b"CMYK": |
| 17425 |
olabel = b"CMYK_C CMYK_M CMYK_Y CMYK_K" |
| 17426 |
else: |
| 17427 |
raise ValueError("Unknown color representation " + icolor) |
| 17428 |
if color_rep == b"LAB": |
| 17429 |
ilabel = b"LAB_L LAB_A LAB_B" |
| 17430 |
elif color_rep in (b"XYZ", b"RGB"): |
| 17431 |
ilabel = b"XYZ_X XYZ_Y XYZ_Z" |
| 17432 |
else: |
| 17433 |
raise ValueError("Unknown CIE color representation " + color_rep) |
| 17434 |
ofile.write(b'KEYWORD "COLOR_REP"\n') |
| 17435 |
if icolor == color_rep: |
| 17436 |
ofile.write(b'COLOR_REP "' + icolor + b'"\n') |
| 17437 |
else: |
| 17438 |
ofile.write(b'COLOR_REP "' + icolor + b"_" + color_rep + b'"\n') |
| 17439 |
|
| 17440 |
ofile.write(b"\n") |
| 17441 |
ofile.write(b"NUMBER_OF_FIELDS ") |
| 17442 |
if include_sample_name: |
| 17443 |
ofile.write( |
| 17444 |
bytes(str(2 + len(icolor) + len(color_rep)), "utf-8") + b"\n" |
| 17445 |
) |
| 17446 |
else: |
| 17447 |
ofile.write( |
| 17448 |
bytes(str(1 + len(icolor) + len(color_rep)), "utf-8") + b"\n" |
| 17449 |
) |
| 17450 |
ofile.write(b"BEGIN_DATA_FORMAT\n") |
| 17451 |
ofile.write(b"SAMPLE_ID ") |
| 17452 |
if include_sample_name: |
| 17453 |
ofile.write(b"SAMPLE_NAME " + olabel + b" " + ilabel + b"\n") |
| 17454 |
else: |
| 17455 |
ofile.write(olabel + b" " + ilabel + b"\n") |
| 17456 |
ofile.write(b"END_DATA_FORMAT\n") |
| 17457 |
ofile.write(b"\n") |
| 17458 |
ofile.write( |
| 17459 |
b"NUMBER_OF_SETS " + bytes(str(len(odata)), "utf-8") + b"\n" |
| 17460 |
) |
| 17461 |
ofile.write(b"BEGIN_DATA\n") |
| 17462 |
if pcs == "x": |
| 17463 |
# Need to scale XYZ coming from xicclu, Lab is already scaled |
| 17464 |
cie = [round(n * 100.0, 5 - len(str(int(abs(n * 100.0))))) for n in cie] |
| 17465 |
elif not pcs: |
| 17466 |
# Actually CIE = RGB because Devicelink |
| 17467 |
idata[i] = cie |
| 17468 |
cie = [ |
| 17469 |
round(n * 100.0, 5 - len(str(int(abs(n * 100.0))))) |
| 17470 |
for n in colormath.RGB2XYZ(*[n / 100.0 for n in cie]) |
| 17471 |
] |
| 17472 |
device = [bytes(str(n), "utf-8") for n in idata[i]] |
| 17473 |
cie = [bytes(str(n), "utf-8") for n in cie] |
| 17474 |
if include_sample_name: |
| 17475 |
ofile.write( |
| 17476 |
bytes(str(i), "utf-8") |
| 17477 |
+ b" " |
| 17478 |
+ data[i - 1][1].strip(b'"') |
| 17479 |
+ b" " |
| 17480 |
+ b" ".join(device) |
| 17481 |
+ b" " |
| 17482 |
+ b" ".join(cie) |
| 17483 |
+ b"\n" |
| 17484 |
) |
| 17485 |
else: |
| 17486 |
ofile.write( |
| 17487 |
bytes(str(i), "utf-8") |
| 17488 |
+ b" " |
| 17489 |
+ b" ".join(device) |
| 17490 |
+ b" " |
| 17491 |
+ b" ".join(cie) |
| 17492 |
+ b"\n" |
| 17493 |
) |
| 17494 |
ofile.write(b"END_DATA\n") |
| 17495 |
ofile.seek(0) |
| 17496 |
ti3 = CGATS(ofile)[0] |
| 17497 |
|
| 17498 |
if colorspace == b"RGB" and white_patches and profile.profileClass == b"link": |
| 17499 |
if white_patches_total: |
| 17500 |
# Ensure total of n white patches |
| 17501 |
while len(ti3.DATA.queryi(white_rgb)) < white_patches: |
| 17502 |
ti3.DATA.insert(0, white) |
| 17503 |
white_added_count += 1 |
| 17504 |
else: |
| 17505 |
# Add exactly n white patches |
| 17506 |
while white_added_count < white_patches: |
| 17507 |
ti3.DATA.insert(0, white) |
| 17508 |
white_added_count += 1 |
| 17509 |
print(f"Added {white_added_count:d} white patch(es)") |
| 17510 |
|
| 17511 |
if DEBUG: |
| 17512 |
print(f"ti3: {ti3}") |
| 17513 |
return ti1, ti3, list(map(list, gray)) |
| 17514 |
|
| 17515 |
def ti3_lookup_to_ti1( |
| 17516 |
self, ti3, profile, fields=None, intent="r", add_white_patches=4 |
| 17517 |
): |
| 17518 |
"""Read TI3 (filename or CGATS instance) and lookup cie->device values. |
| 17519 |
|
| 17520 |
Lookup cie->device values colorimetrically through profile using |
| 17521 |
Argyll's xicclu utility and return TI1 and compatible TI3 (CGATS |
| 17522 |
instances). |
| 17523 |
|
| 17524 |
Args: |
| 17525 |
ti3 (str or CGATS): TI3 filename or CGATS instance. |
| 17526 |
profile (str or ICCProfile): Profile filename or ICCProfile |
| 17527 |
instance. |
| 17528 |
fields (str): CIE color representation to use, either "XYZ" or |
| 17529 |
"LAB". |
| 17530 |
intent (str): Rendering intent to use, either "r" for relative |
| 17531 |
colorimetric or "a" for absolute colorimetric. |
| 17532 |
add_white_patches (int): Number of white patches to add to the |
| 17533 |
TI1/ti3 file. If set to 0, no white patches are added. If set |
| 17534 |
to a positive integer, the first n patches will be white, so |
| 17535 |
the whitepoint can be averaged. Defaults to 4. |
| 17536 |
|
| 17537 |
Raises: |
| 17538 |
TypeError: If `ti3` is not a CGATS instance or a valid filename. |
| 17539 |
ValueError: If `ti3` is invalid or missing required fields. |
| 17540 |
|
| 17541 |
Returns: |
| 17542 |
tuple: A tuple containing: |
| 17543 |
- CGATS instance of TI1 with device->cie values. |
| 17544 |
- CGATS instance of TI3 with device->cie values. |
| 17545 |
- Gray patch data (if available). |
| 17546 |
""" |
| 17547 |
# ti3 |
| 17548 |
copy = True |
| 17549 |
if isinstance(ti3, (str, bytes)): |
| 17550 |
copy = False |
| 17551 |
ti3 = CGATS(ti3) |
| 17552 |
if not isinstance(ti3, CGATS): |
| 17553 |
raise TypeError( |
| 17554 |
"Wrong type for ti3, needs to be CGATS instance, " |
| 17555 |
f"not {ti3.__class__.__name__}" |
| 17556 |
) |
| 17557 |
ti3_filename = ti3.filename |
| 17558 |
if copy: |
| 17559 |
# Make a copy and do not alter a passed in CGATS instance! |
| 17560 |
ti3 = CGATS(bytes(ti3)) |
| 17561 |
|
| 17562 |
if fields == "XYZ": |
| 17563 |
labels = ("XYZ_X", "XYZ_Y", "XYZ_Z") |
| 17564 |
else: |
| 17565 |
labels = ("LAB_L", "LAB_A", "LAB_B") |
| 17566 |
|
| 17567 |
try: |
| 17568 |
ti3v = verify_cgats(ti3, labels, True) |
| 17569 |
except CGATSInvalidError as exception: |
| 17570 |
raise ValueError( |
| 17571 |
f"{lang.getstr('error.testchart.invalid', ti3_filename)}\n" |
| 17572 |
f"{lang.getstr(str(exception))}" |
| 17573 |
) from exception |
| 17574 |
except CGATSKeyError: |
| 17575 |
try: |
| 17576 |
if fields: |
| 17577 |
raise |
| 17578 |
labels = ("XYZ_X", "XYZ_Y", "XYZ_Z") |
| 17579 |
ti3v = verify_cgats(ti3, labels, True) |
| 17580 |
except CGATSKeyError as e: |
| 17581 |
missing = ", ".join(labels) |
| 17582 |
if not fields: |
| 17583 |
missing = f"{missing} {lang.getstr('or')} LAB_L, LAB_A, LAB_B" |
| 17584 |
raise ValueError( |
| 17585 |
lang.getstr( |
| 17586 |
"error.testchart.missing_fields", (ti3_filename, missing) |
| 17587 |
) |
| 17588 |
) from e |
| 17589 |
else: |
| 17590 |
color_rep = "XYZ" |
| 17591 |
else: |
| 17592 |
color_rep = fields or "LAB" |
| 17593 |
|
| 17594 |
# profile |
| 17595 |
if isinstance(profile, str): |
| 17596 |
profile = ICCProfile(profile) |
| 17597 |
if not isinstance(profile, ICCProfile): |
| 17598 |
raise TypeError( |
| 17599 |
"Wrong type for profile, needs to be ICCProfile instance, " |
| 17600 |
f"not {profile.__class__.__name__}" |
| 17601 |
) |
| 17602 |
|
| 17603 |
# determine pcs for lookup |
| 17604 |
if color_rep == "LAB": |
| 17605 |
pcs = "l" |
| 17606 |
required = ("LAB_L", "LAB_A", "LAB_B") |
| 17607 |
elif color_rep == "XYZ": |
| 17608 |
pcs = "x" |
| 17609 |
required = ("XYZ_X", "XYZ_Y", "XYZ_Z") |
| 17610 |
else: |
| 17611 |
raise ValueError("Unknown CIE color representation " + color_rep) |
| 17612 |
|
| 17613 |
# get profile color space |
| 17614 |
colorspace = profile.colorSpace |
| 17615 |
|
| 17616 |
# read cie values from ti3 |
| 17617 |
data = ti3v.queryv1("DATA") |
| 17618 |
if not data: |
| 17619 |
raise ValueError(lang.getstr("error.testchart.invalid", ti3_filename)) |
| 17620 |
cie_data = data.queryv(required) |
| 17621 |
if not cie_data: |
| 17622 |
raise ValueError( |
| 17623 |
lang.getstr( |
| 17624 |
"error.testchart.missing_fields", |
| 17625 |
(ti3_filename, ", ".join(required)), |
| 17626 |
) |
| 17627 |
) |
| 17628 |
idata = [] |
| 17629 |
if colorspace == "RGB" and add_white_patches: |
| 17630 |
# make sure the first four patches are white so the whitepoint can be |
| 17631 |
# averaged |
| 17632 |
wp = [n * 100.0 for n in list(profile.tags.wtpt.values())] |
| 17633 |
if color_rep == "LAB": |
| 17634 |
wp = colormath.XYZ2Lab(*wp) |
| 17635 |
wp = {"L": wp[0], "a": wp[1], "b": wp[2]} |
| 17636 |
else: |
| 17637 |
wp = {"X": wp[0], "Y": wp[1], "Z": wp[2]} |
| 17638 |
wp = [wp] * int(add_white_patches) |
| 17639 |
print(f"Added {add_white_patches:d} white patches") |
| 17640 |
else: |
| 17641 |
wp = [] |
| 17642 |
|
| 17643 |
for cie in wp + list(cie_data.values()): |
| 17644 |
cie = list(cie.values()) |
| 17645 |
if color_rep == "XYZ": |
| 17646 |
# assume scale 0...100 in ti3, we need to convert to 0...1 |
| 17647 |
cie = [n / 100.0 for n in cie] |
| 17648 |
idata.append(cie) |
| 17649 |
|
| 17650 |
if DEBUG: |
| 17651 |
print(f"ti3_lookup_to_ti1 {color_rep} -> {profile.colorSpace} idata") |
| 17652 |
for v in idata: |
| 17653 |
print(" ".join(("{:3.4f}",) * len(v)).format(*v)) |
| 17654 |
|
| 17655 |
# lookup cie->device values through profile.icc using xicclu |
| 17656 |
odata = self.xicclu(profile, idata, intent, "b", pcs=pcs, scale=100) |
| 17657 |
|
| 17658 |
# write output ti1/ti3 |
| 17659 |
ti1out = BytesIO() |
| 17660 |
ti1out.write(b"CTI1\n") |
| 17661 |
ti1out.write(b"\n") |
| 17662 |
ti1out.write(b'DESCRIPTOR "Argyll Calibration Target chart information 1"\n') |
| 17663 |
include_sample_name = False |
| 17664 |
for i, device in enumerate(odata): |
| 17665 |
if i == 0: |
| 17666 |
if color_rep == "LAB": |
| 17667 |
ilabel = b"LAB_L LAB_A LAB_B" |
| 17668 |
elif color_rep == "XYZ": |
| 17669 |
ilabel = b"XYZ_X XYZ_Y XYZ_Z" |
| 17670 |
else: |
| 17671 |
raise ValueError(f"Unknown CIE color representation {color_rep}") |
| 17672 |
ocolor = profile.colorSpace.upper() |
| 17673 |
if ocolor == b"RGB": |
| 17674 |
olabel = b"RGB_R RGB_G RGB_B" |
| 17675 |
elif ocolor == b"CMYK": |
| 17676 |
olabel = b"CMYK_C CMYK_M CMYK_Y CMYK_K" |
| 17677 |
else: |
| 17678 |
raise ValueError(f"Unknown color representation {ocolor}") |
| 17679 |
olabels = olabel.split() |
| 17680 |
# add device fields to DATA_FORMAT if not yet present |
| 17681 |
if ( |
| 17682 |
olabels[0] not in list(ti3v.DATA_FORMAT.values()) |
| 17683 |
and olabels[1] not in list(ti3v.DATA_FORMAT.values()) |
| 17684 |
and olabels[2] not in list(ti3v.DATA_FORMAT.values()) |
| 17685 |
and ( |
| 17686 |
ocolor == b"RGB" |
| 17687 |
or ( |
| 17688 |
ocolor == b"CMYK" |
| 17689 |
and olabels[3] not in list(ti3v.DATA_FORMAT.values()) |
| 17690 |
) |
| 17691 |
) |
| 17692 |
): |
| 17693 |
ti3v.DATA_FORMAT.add_data(olabels) |
| 17694 |
# add required fields to DATA_FORMAT if not yet present |
| 17695 |
if ( |
| 17696 |
bytes(required[0], "utf-8") not in list(ti3v.DATA_FORMAT.values()) |
| 17697 |
and bytes(required[1], "utf-8") |
| 17698 |
not in list(ti3v.DATA_FORMAT.values()) |
| 17699 |
and bytes(required[2], "utf-8") |
| 17700 |
not in list(ti3v.DATA_FORMAT.values()) |
| 17701 |
): |
| 17702 |
ti3v.DATA_FORMAT.add_data(required) |
| 17703 |
ti1out.write(b'KEYWORD "COLOR_REP"\n') |
| 17704 |
ti1out.write(b'COLOR_REP "%s"\n' % ocolor) |
| 17705 |
ti1out.write(b"\n") |
| 17706 |
ti1out.write(b"NUMBER_OF_FIELDS ") |
| 17707 |
if include_sample_name: |
| 17708 |
ti1out.write( |
| 17709 |
bytes(str(2 + len(color_rep) + len(ocolor)), "utf-8") + b"\n" |
| 17710 |
) |
| 17711 |
else: |
| 17712 |
ti1out.write( |
| 17713 |
bytes(str(1 + len(color_rep) + len(ocolor)), "utf-8") + b"\n" |
| 17714 |
) |
| 17715 |
ti1out.write(b"BEGIN_DATA_FORMAT\n") |
| 17716 |
ti1out.write(b"SAMPLE_ID ") |
| 17717 |
if include_sample_name: |
| 17718 |
ti1out.write(b"SAMPLE_NAME %s %s\n" % (olabel, ilabel)) |
| 17719 |
else: |
| 17720 |
ti1out.write(b"%s %s\n" % (olabel, ilabel)) |
| 17721 |
ti1out.write(b"END_DATA_FORMAT\n") |
| 17722 |
ti1out.write(b"\n") |
| 17723 |
ti1out.write(b"NUMBER_OF_SETS %s\n" % bytes(str(len(odata)), "utf-8")) |
| 17724 |
ti1out.write(b"BEGIN_DATA\n") |
| 17725 |
if i < len(wp): |
| 17726 |
device = [100.00, 100.00, 100.00] if ocolor == b"RGB" else [0, 0, 0, 0] |
| 17727 |
# Make sure device values do not exceed valid range of 0..100 |
| 17728 |
device = [bytes(str(max(0, min(v, 100))), "utf-8") for v in device] |
| 17729 |
cie = list((wp + list(cie_data.values()))[i].values()) |
| 17730 |
cie = [bytes(str(n), "utf-8") for n in cie] |
| 17731 |
if include_sample_name: |
| 17732 |
cie_ = b"%s %s %s %s\n" % ( |
| 17733 |
bytes(str(i + 1)), |
| 17734 |
data[i][1].strip(b'"'), |
| 17735 |
b" ".join(device), |
| 17736 |
b" ".join(cie), |
| 17737 |
) |
| 17738 |
ti1out.write(cie_) |
| 17739 |
else: |
| 17740 |
cie_ = b"%s %s %s\n" % ( |
| 17741 |
bytes(str(i + 1), "utf-8"), |
| 17742 |
b" ".join(device), |
| 17743 |
b" ".join(cie), |
| 17744 |
) |
| 17745 |
ti1out.write(cie_) |
| 17746 |
if i > len(wp) - 1: # don't include whitepoint patches in ti3 |
| 17747 |
# set device values in ti3 |
| 17748 |
for n, v in enumerate(olabels): |
| 17749 |
# Assuming 0..100, 4 decimal digits is |
| 17750 |
# enough for roughly 19 bits integer |
| 17751 |
# device values |
| 17752 |
ti3v.DATA[i - len(wp)][v.decode("utf-8")] = round( |
| 17753 |
float(device[n]), 4 |
| 17754 |
) |
| 17755 |
# set PCS values in ti3 |
| 17756 |
for n, v in enumerate(cie): |
| 17757 |
ti3v.DATA[i - len(wp)][required[n]] = float(v) |
| 17758 |
ti1out.write(b"END_DATA\n") |
| 17759 |
ti1out.seek(0) |
| 17760 |
ti1 = CGATS(ti1out) |
| 17761 |
if DEBUG: |
| 17762 |
print(ti1) |
| 17763 |
return ti1, ti3v |
| 17764 |
|
| 17765 |
def download(self, uri, force=False, download_dir=None): |
| 17766 |
"""Download a file from the specified URI. |
| 17767 |
|
| 17768 |
Args: |
| 17769 |
uri (str): The URI of the file to download. |
| 17770 |
force (bool, optional): If True, forces a re-download even if the |
| 17771 |
file exists locally. Defaults to False. |
| 17772 |
download_dir (str, optional): Directory to save the downloaded |
| 17773 |
file. If None, uses a default download directory. |
| 17774 |
""" |
| 17775 |
# Set timeout to a sane value |
| 17776 |
default_timeout = socket.getdefaulttimeout() |
| 17777 |
socket.setdefaulttimeout(20) # 20 seconds |
| 17778 |
try: |
| 17779 |
max_attempts = 3 |
| 17780 |
retry_wait = 1.0 |
| 17781 |
for attempt in range(1, max_attempts + 1): |
| 17782 |
result = self._download(uri, force=force, download_dir=download_dir) |
| 17783 |
if not isinstance(result, Exception): |
| 17784 |
return result |
| 17785 |
if ( |
| 17786 |
self.thread_abort |
| 17787 |
or attempt >= max_attempts |
| 17788 |
or not self._is_retryable_download_error(result) |
| 17789 |
): |
| 17790 |
return result |
| 17791 |
wait_seconds = retry_wait + random.uniform(0, 0.25) |
| 17792 |
print( |
| 17793 |
f"{result}\n" |
| 17794 |
f"{lang.getstr('download.retrying', (attempt + 1, max_attempts, wait_seconds))}" |
| 17795 |
) |
| 17796 |
sleep(wait_seconds) |
| 17797 |
retry_wait *= 2 |
| 17798 |
# Ensure next attempt refreshes server state and local file. |
| 17799 |
force = True |
| 17800 |
finally: |
| 17801 |
socket.setdefaulttimeout(default_timeout) |
| 17802 |
|
| 17803 |
@staticmethod |
| 17804 |
def _is_retryable_download_error(error: Exception) -> bool: |
| 17805 |
"""Return True for network/transient download errors.""" |
| 17806 |
return bool(getattr(error, "retryable", False)) |
| 17807 |
|
| 17808 |
def _download(self, uri, force=False, download_dir=None): |
| 17809 |
"""Download a file from the specified URI. |
| 17810 |
|
| 17811 |
Optional hash verification and progress reporting are available. |
| 17812 |
|
| 17813 |
This method handles downloading files (such as ArgyllCMS archives) from |
| 17814 |
a given URI. It supports forced downloads, custom download directories, |
| 17815 |
and can verify file hashes if available. The method also manages HTTP |
| 17816 |
redirects, SSL certificate verification, and provides progress feedback |
| 17817 |
during the download. |
| 17818 |
|
| 17819 |
Notes: |
| 17820 |
- For certain domains, the method always forces a download to |
| 17821 |
ensure hash checking. |
| 17822 |
- Handles SSL certificate errors and HTTP redirects. |
| 17823 |
- If the file already exists and matches the expected size, it is |
| 17824 |
not re-downloaded unless forced. |
| 17825 |
- If hash verification is enabled, the method checks the downloaded |
| 17826 |
file's hash. |
| 17827 |
- Provides progress updates during the download process. |
| 17828 |
|
| 17829 |
Args: |
| 17830 |
uri (str): The URI of the file to download. |
| 17831 |
force (bool, optional): If True, forces a re-download even if the |
| 17832 |
file exists locally. Defaults to False. |
| 17833 |
download_dir (str, optional): Directory to save the downloaded |
| 17834 |
file. If None, uses a default download directory. |
| 17835 |
|
| 17836 |
Returns: |
| 17837 |
str: The path to the downloaded file if successful. |
| 17838 |
Exception: An Exception object if the download fails. |
| 17839 |
""" |
| 17840 |
if TEST_BADSSL: |
| 17841 |
uri = f"https://{TEST_BADSSL}.badssl.com/" |
| 17842 |
orig_uri = uri |
| 17843 |
total_size = None |
| 17844 |
filename = os.path.basename(uri) |
| 17845 |
if not download_dir: |
| 17846 |
download_dir = os.path.join(config.DATA_HOME, "dl") |
| 17847 |
download_path = os.path.join(download_dir, filename) |
| 17848 |
response = None |
| 17849 |
hashes = None |
| 17850 |
expectedhash_hex = None |
| 17851 |
actualhash = None |
| 17852 |
|
| 17853 |
def make_download_error(message: str, retryable: bool = False) -> DownloadError: |
| 17854 |
error = DownloadError(message, orig_uri) |
| 17855 |
error.retryable = retryable |
| 17856 |
return error |
| 17857 |
|
| 17858 |
is_main_dl = uri.startswith(f"https://{DOMAIN}/download/") |
| 17859 |
if is_main_dl: |
| 17860 |
# Always force connection to server even if local file exists for |
| 17861 |
# displaycal.net/downloads/* and displaycal.net/Argyll/* |
| 17862 |
# to force a hash check |
| 17863 |
force = True |
| 17864 |
if force or not os.path.isfile(download_path): |
| 17865 |
cafile = None |
| 17866 |
try: |
| 17867 |
import ssl |
| 17868 |
from ssl import CertificateError, SSLError |
| 17869 |
except ImportError: |
| 17870 |
CertificateError = ValueError |
| 17871 |
SSLError = socket.error |
| 17872 |
else: |
| 17873 |
if hasattr(ssl, "get_default_verify_paths"): |
| 17874 |
cafile = ssl.get_default_verify_paths().cafile |
| 17875 |
if cafile: |
| 17876 |
print("Using CA file", cafile) |
| 17877 |
components = urllib.parse.urlparse(uri) |
| 17878 |
# Don't use socket.getservbyname, as it apparently can fail with |
| 17879 |
# socket.error under Windows 10 (although why remains a mystery, |
| 17880 |
# we're only dealing with HTTP and HTTPS protocols...) |
| 17881 |
scheme2port = {"http": 80, "https": 443} |
| 17882 |
print( |
| 17883 |
lang.getstr( |
| 17884 |
"connecting.to", |
| 17885 |
( |
| 17886 |
f"{components.scheme}://{components.hostname}", |
| 17887 |
components.port or scheme2port.get(components.scheme, "?"), |
| 17888 |
), |
| 17889 |
) |
| 17890 |
) |
| 17891 |
LoggingHTTPRedirectHandler.newurl = uri |
| 17892 |
opener = urllib.request.build_opener(LoggingHTTPRedirectHandler) |
| 17893 |
opener.addheaders = list(get_default_headers().items()) |
| 17894 |
argyllcms_binaries_base = ( |
| 17895 |
"https://github.com/eoyilmaz/argyllcms-binaries/releases/download/" |
| 17896 |
) |
| 17897 |
try: |
| 17898 |
response = opener.open(uri) |
| 17899 |
if ALWAYS_FAIL_DOWNLOAD or TEST_BADSSL: |
| 17900 |
raise urllib.error.URLError("") |
| 17901 |
newurl = getattr(LoggingHTTPRedirectHandler, "newurl", uri) |
| 17902 |
if not orig_uri.startswith(argyllcms_binaries_base) and ( |
| 17903 |
is_main_dl or not newurl.startswith(f"https://{DOMAIN}/") |
| 17904 |
): |
| 17905 |
# Get SHA-256 hashes so we can verify the downloaded file. |
| 17906 |
# Only do this for 3rd party hosts/mirrors (no sense |
| 17907 |
# doing it for files downloaded securely directly from |
| 17908 |
# displaycal.net when that is also the source of our hashes |
| 17909 |
# file, unless we are verifying an existing local app setup |
| 17910 |
# or portable archive). argyllcms-binaries uses the GitHub |
| 17911 |
# API digest field instead (handled below). |
| 17912 |
noredir = urllib.request.build_opener(NoHTTPRedirectHandler) |
| 17913 |
noredir.addheaders = list(get_default_headers().items()) |
| 17914 |
hashes = noredir.open(f"https://{DOMAIN}/sha256sums.txt") |
| 17915 |
except ( |
| 17916 |
OSError, |
| 17917 |
urllib.error.URLError, |
| 17918 |
http.client.HTTPException, |
| 17919 |
CertificateError, |
| 17920 |
SSLError, |
| 17921 |
) as exception: |
| 17922 |
if response: |
| 17923 |
response.close() |
| 17924 |
if "CERTIFICATE_VERIFY_FAILED" in safe_str(exception): |
| 17925 |
ekey = "ssl.certificate_verify_failed" |
| 17926 |
if not cafile and ISAPP: |
| 17927 |
ekey += ".root_ca_missing" |
| 17928 |
print(lang.getstr(ekey)) |
| 17929 |
elif "SSLV3_ALERT_HANDSHAKE_FAILURE" in safe_str(exception): |
| 17930 |
print(lang.getstr("ssl.handshake_failure")) |
| 17931 |
elif "SSL:" not in safe_str(exception): |
| 17932 |
exception.retryable = True |
| 17933 |
return exception |
| 17934 |
else: |
| 17935 |
print(exception) |
| 17936 |
if getattr(LoggingHTTPRedirectHandler, "newurl", uri) != uri: |
| 17937 |
uri = LoggingHTTPRedirectHandler.newurl |
| 17938 |
return make_download_error( |
| 17939 |
lang.getstr("download.fail") |
| 17940 |
+ " " |
| 17941 |
+ lang.getstr("connection.fail", uri), |
| 17942 |
retryable=True, |
| 17943 |
) |
| 17944 |
uri = response.geturl() |
| 17945 |
filename = os.path.basename(Path(uri).name) |
| 17946 |
actualhash = sha256() |
| 17947 |
if orig_uri.startswith(argyllcms_binaries_base): |
| 17948 |
# Use the GitHub API digest field, available for every release |
| 17949 |
# asset without any separate upload step. |
| 17950 |
# URL: .../releases/download/{version}/{filename} |
| 17951 |
path_tail = orig_uri[len("https://github.com/"):] |
| 17952 |
parts = path_tail.split("/") |
| 17953 |
# parts: ["eoyilmaz", "argyllcms-binaries", "releases", "download", version, filename] |
| 17954 |
if len(parts) >= 6: |
| 17955 |
version, asset_name = parts[4], parts[5] |
| 17956 |
api_url = ( |
| 17957 |
"https://api.github.com/repos/eoyilmaz/argyllcms-binaries" |
| 17958 |
f"/releases/tags/{version}" |
| 17959 |
) |
| 17960 |
try: |
| 17961 |
import json |
| 17962 |
|
| 17963 |
api_resp = urllib.request.urlopen(api_url, timeout=20) # noqa: S310 |
| 17964 |
release_data = json.loads(api_resp.read()) |
| 17965 |
for asset in release_data.get("assets", []): |
| 17966 |
if asset["name"] == asset_name: |
| 17967 |
digest = asset.get("digest", "") |
| 17968 |
if digest.startswith("sha256:"): |
| 17969 |
expectedhash_hex = digest[7:].lower() |
| 17970 |
break |
| 17971 |
except (urllib.error.URLError, OSError, KeyError, ValueError): |
| 17972 |
pass |
| 17973 |
if hashes: |
| 17974 |
# Read max. 64 KB hashes |
| 17975 |
hashesdata = hashes.read(1024 * 64) |
| 17976 |
hashes.close() |
| 17977 |
hashesdict = {} |
| 17978 |
for line in hashesdata.splitlines(): |
| 17979 |
if not line.strip(): |
| 17980 |
continue |
| 17981 |
name_hash = [value.strip() for value in line.split(None, 1)] |
| 17982 |
if len(name_hash) != 2 or b"" in name_hash: |
| 17983 |
response.close() |
| 17984 |
return make_download_error( |
| 17985 |
lang.getstr("file.hash.malformed", filename), |
| 17986 |
retryable=False, |
| 17987 |
) |
| 17988 |
hash_filename = Path( |
| 17989 |
name_hash[1].decode("utf-8", "replace").lstrip("*") |
| 17990 |
) |
| 17991 |
hashesdict[hash_filename.name] = ( |
| 17992 |
name_hash[0].decode("ascii", "replace").lower() |
| 17993 |
) |
| 17994 |
expectedhash_hex = hashesdict.get(filename) |
| 17995 |
if not expectedhash_hex: |
| 17996 |
response.close() |
| 17997 |
return make_download_error( |
| 17998 |
lang.getstr("file.hash.missing", filename), retryable=False |
| 17999 |
) |
| 18000 |
total_size = response.info().get("Content-Length") |
| 18001 |
if total_size is not None: |
| 18002 |
try: |
| 18003 |
total_size = int(total_size) |
| 18004 |
except (TypeError, ValueError): |
| 18005 |
return make_download_error( |
| 18006 |
lang.getstr( |
| 18007 |
"download.fail.wrong_size", |
| 18008 |
("<{}>".format(lang.getstr("unknown")),) * 2, |
| 18009 |
), |
| 18010 |
retryable=True, |
| 18011 |
) |
| 18012 |
else: |
| 18013 |
if not total_size: |
| 18014 |
total_size = None |
| 18015 |
contentdispo = response.info().get("Content-Disposition") |
| 18016 |
if contentdispo: |
| 18017 |
m = re.search(r'filename[*]?=(?:"([^"]+)"|([^\s;]+))', contentdispo, re.I) |
| 18018 |
if m: |
| 18019 |
filename = (m.group(1) or m.group(2)).strip() |
| 18020 |
if not filename: |
| 18021 |
filename = make_filename_safe(uri.rstrip("/"), concat=False) |
| 18022 |
content_type = response.info().get("Content-Type") |
| 18023 |
if content_type: |
| 18024 |
content_type = content_type.split(";", 1)[0] |
| 18025 |
ext = mimetypes.guess_extension(content_type or "", False) |
| 18026 |
filename += ext or ".html" |
| 18027 |
download_path = os.path.join(download_dir, filename) |
| 18028 |
if not os.path.isfile(download_path) or ( |
| 18029 |
total_size is not None and os.stat(download_path).st_size != total_size |
| 18030 |
): |
| 18031 |
if not os.path.isdir(download_dir): |
| 18032 |
os.makedirs(download_dir) |
| 18033 |
|
| 18034 |
# Acquire files safely so no-one but us can mess with them |
| 18035 |
download_path = mksfile(download_path) |
| 18036 |
tmp_download_path = mksfile(f"{download_path}.download") |
| 18037 |
print(lang.getstr("downloading"), uri, "\u2192", download_path) |
| 18038 |
self.recent.write(lang.getstr(f"downloading {filename}\n")) |
| 18039 |
min_chunk_size = 1024 * 8 |
| 18040 |
chunk_size = min_chunk_size |
| 18041 |
bytes_so_far = 0 |
| 18042 |
prev_bytes_so_far = 0 |
| 18043 |
unit = "Bytes" |
| 18044 |
unit_size = 1.0 |
| 18045 |
if total_size and total_size > 1048576: |
| 18046 |
unit = "MiB" |
| 18047 |
unit_size = 1048576.0 |
| 18048 |
elif total_size and total_size > 1024: |
| 18049 |
unit = "KiB" |
| 18050 |
unit_size = 1024.0 |
| 18051 |
|
| 18052 |
ts = time() |
| 18053 |
bps = 0 |
| 18054 |
|
| 18055 |
prev_percent = -1 |
| 18056 |
update_ts = time() |
| 18057 |
fps = 20 |
| 18058 |
frametime = 1.0 / fps |
| 18059 |
|
| 18060 |
download_file_exception = None |
| 18061 |
download_succeeded = False |
| 18062 |
try: |
| 18063 |
with open(tmp_download_path, "wb+") as tmp_download_file: |
| 18064 |
while True: |
| 18065 |
if self.thread_abort: |
| 18066 |
print(lang.getstr("aborted")) |
| 18067 |
return False |
| 18068 |
chunk = response.read(chunk_size) |
| 18069 |
if not chunk: |
| 18070 |
break |
| 18071 |
bytes_read = len(chunk) |
| 18072 |
bytes_so_far += bytes_read |
| 18073 |
tmp_download_file.write(chunk) |
| 18074 |
if expectedhash_hex: |
| 18075 |
actualhash.update(chunk) |
| 18076 |
|
| 18077 |
# Determine data rate |
| 18078 |
tdiff = time() - ts |
| 18079 |
if tdiff >= 1: |
| 18080 |
bps = (bytes_so_far - prev_bytes_so_far) / tdiff |
| 18081 |
prev_bytes_so_far = bytes_so_far |
| 18082 |
ts = time() |
| 18083 |
elif not bps: |
| 18084 |
bps = bytes_so_far / tdiff if tdiff else bytes_read |
| 18085 |
bps_unit = "Bytes" |
| 18086 |
bps_unit_size = 1.0 |
| 18087 |
if bps > 1048576: |
| 18088 |
bps_unit = "MiB" |
| 18089 |
bps_unit_size = 1048576.0 |
| 18090 |
elif bps > 1024: |
| 18091 |
bps_unit = "KiB" |
| 18092 |
bps_unit_size = 1024.0 |
| 18093 |
|
| 18094 |
if total_size: |
| 18095 |
percent = math.floor(float(bytes_so_far) / total_size * 100) |
| 18096 |
if ( |
| 18097 |
percent > prev_percent |
| 18098 |
or time() >= update_ts + frametime |
| 18099 |
): |
| 18100 |
self.lastmsg.write( |
| 18101 |
f"\r{percent:d}% ({bytes_so_far / unit_size:.1f} " |
| 18102 |
f"/ {total_size / unit_size:.1f} {unit}, " |
| 18103 |
f"{round(bps / bps_unit_size, 2):.2f} {bps_unit}/s)" |
| 18104 |
) |
| 18105 |
prev_percent = percent |
| 18106 |
update_ts = time() |
| 18107 |
elif time() >= update_ts + frametime: |
| 18108 |
if bytes_so_far > 1048576 > unit_size: |
| 18109 |
unit = "MiB" |
| 18110 |
unit_size = 1048576.0 |
| 18111 |
elif bytes_so_far > 1024 > unit_size: |
| 18112 |
unit = "KiB" |
| 18113 |
unit_size = 1024.0 |
| 18114 |
self.lastmsg.write( |
| 18115 |
f"\r{bytes_so_far / unit_size:.1f} {unit} " |
| 18116 |
f"({round(bps / bps_unit_size, 2):.2f} " |
| 18117 |
f"{bps_unit}/s)" |
| 18118 |
) |
| 18119 |
update_ts = time() |
| 18120 |
|
| 18121 |
# Adjust chunk size based on DL rate |
| 18122 |
if int(bps / fps) > chunk_size or min_chunk_size <= int( |
| 18123 |
bps / fps |
| 18124 |
) < int(chunk_size * 0.75): |
| 18125 |
if DEBUG or TEST or VERBOSE > 1: |
| 18126 |
print( |
| 18127 |
"Download buffer size changed from " |
| 18128 |
f"{chunk_size / 1024.0:0.0f} KB to " |
| 18129 |
f"{bps / fps / 1024:0.0f} KB" |
| 18130 |
) |
| 18131 |
chunk_size = int(bps / fps) |
| 18132 |
|
| 18133 |
if not bytes_so_far: |
| 18134 |
return make_download_error( |
| 18135 |
lang.getstr("download.fail.empty_response", uri), |
| 18136 |
retryable=True, |
| 18137 |
) |
| 18138 |
if total_size is not None and bytes_so_far != total_size: |
| 18139 |
return make_download_error( |
| 18140 |
lang.getstr( |
| 18141 |
"download.fail.wrong_size", (total_size, bytes_so_far) |
| 18142 |
), |
| 18143 |
retryable=True, |
| 18144 |
) |
| 18145 |
if total_size is None or bytes_so_far == total_size: |
| 18146 |
# Successful download, persist and atomically place file. |
| 18147 |
download_succeeded = True |
| 18148 |
tmp_download_file.flush() |
| 18149 |
os.fsync(tmp_download_file.fileno()) |
| 18150 |
|
| 18151 |
if download_succeeded: |
| 18152 |
try: |
| 18153 |
os.replace(tmp_download_path, download_path) |
| 18154 |
except OSError as e: |
| 18155 |
return e |
| 18156 |
print(lang.getstr("success")) |
| 18157 |
finally: |
| 18158 |
if response: |
| 18159 |
response.close() |
| 18160 |
if ( |
| 18161 |
self.thread_abort |
| 18162 |
or download_file_exception |
| 18163 |
or not download_succeeded |
| 18164 |
): |
| 18165 |
# Remove destination file if download aborted, incomplete |
| 18166 |
# or there was an error writing destination. |
| 18167 |
try: |
| 18168 |
os.remove(download_path) |
| 18169 |
except OSError as exception: |
| 18170 |
print(exception) |
| 18171 |
if not download_succeeded: |
| 18172 |
try: |
| 18173 |
os.remove(tmp_download_path) |
| 18174 |
except OSError as exception: |
| 18175 |
print(exception) |
| 18176 |
else: |
| 18177 |
# File already exists |
| 18178 |
if response: |
| 18179 |
response.close() |
| 18180 |
if expectedhash_hex: |
| 18181 |
# Verify hash. Get hash of existing file |
| 18182 |
with open(download_path, "rb") as download_file: |
| 18183 |
while True: |
| 18184 |
chunk = download_file.read(1024 * 1024) |
| 18185 |
if not chunk: |
| 18186 |
break |
| 18187 |
actualhash.update(chunk) |
| 18188 |
if expectedhash_hex: |
| 18189 |
# Verify hash. Compare to expected hash |
| 18190 |
actualhash_hex = actualhash.hexdigest().lower() |
| 18191 |
if actualhash_hex != expectedhash_hex: |
| 18192 |
if os.path.isfile(download_path): |
| 18193 |
os.remove(download_path) |
| 18194 |
return Error( |
| 18195 |
lang.getstr( |
| 18196 |
"file.hash.verification.fail", |
| 18197 |
( |
| 18198 |
download_path, |
| 18199 |
f"SHA-256= {expectedhash_hex}", |
| 18200 |
f"SHA-256= {actualhash_hex}", |
| 18201 |
), |
| 18202 |
) |
| 18203 |
) |
| 18204 |
print(f"Verified hash SHA-256= {actualhash_hex}") |
| 18205 |
return download_path |
| 18206 |
|
| 18207 |
def process_argyll_download(self, result, exit_=False): |
| 18208 |
"""Handle the result of an ArgyllCMS download operation. |
| 18209 |
|
| 18210 |
This method processes the outcome of downloading an ArgyllCMS archive |
| 18211 |
(ZIP or TGZ). If the result is an Exception, it displays an error |
| 18212 |
dialog. If the result is a valid archive file, it starts extraction of |
| 18213 |
the archive and sets the Argyll bin directory upon success. If the |
| 18214 |
result is not a supported archive file, it displays an error dialog. |
| 18215 |
|
| 18216 |
Side Effects: |
| 18217 |
- May display dialogs to the user. |
| 18218 |
- May start extraction of the downloaded archive. |
| 18219 |
- May update the Argyll bin directory configuration. |
| 18220 |
|
| 18221 |
Args: |
| 18222 |
result (str or Exception): The result of the download operation. |
| 18223 |
This can be a file path to the downloaded archive or an |
| 18224 |
Exception if the download failed. |
| 18225 |
exit_ (bool, optional): If True, closes the owner window or exits |
| 18226 |
the application after processing. Defaults to False. |
| 18227 |
""" |
| 18228 |
if isinstance(result, Exception): |
| 18229 |
if isinstance(result, DownloadError): |
| 18230 |
# DownloadError would otherwise force a "go to URL" prompt. |
| 18231 |
retry = show_result_dialog( |
| 18232 |
Error(str(result)), |
| 18233 |
self.owner, |
| 18234 |
confirm=lang.getstr("retry"), |
| 18235 |
) |
| 18236 |
if retry: |
| 18237 |
self._reopen_argyll_download_prompt() |
| 18238 |
else: |
| 18239 |
show_result_dialog(result, self.owner) |
| 18240 |
elif result: |
| 18241 |
if result.lower().endswith(".zip") or result.lower().endswith(".tgz"): |
| 18242 |
self.start( |
| 18243 |
self.set_argyll_bin, |
| 18244 |
self.extract_archive, |
| 18245 |
cargs=(result,), |
| 18246 |
wargs=(result,), |
| 18247 |
progress_msg=lang.getstr("please_wait"), |
| 18248 |
fancy=False, |
| 18249 |
) |
| 18250 |
else: |
| 18251 |
show_result_dialog( |
| 18252 |
f"{lang.getstr('error.file_type_unsupported')}\n{result}", |
| 18253 |
self.owner, |
| 18254 |
) |
| 18255 |
|
| 18256 |
def extract_archive(self, filename): |
| 18257 |
"""Extract the contents of a ZIP or TGZ archive file. |
| 18258 |
|
| 18259 |
Notes: |
| 18260 |
- For ZIP files, files are extracted using the `zipfile.ZipFile` |
| 18261 |
class. |
| 18262 |
- For TGZ files, files are extracted using the `TarFileProper.open` |
| 18263 |
method. |
| 18264 |
- The method ensures that all extracted files remain within the |
| 18265 |
intended output directory to prevent directory traversal |
| 18266 |
vulnerabilities. |
| 18267 |
- If the archive is invalid or extraction fails, the method may |
| 18268 |
delete the archive file. |
| 18269 |
|
| 18270 |
Args: |
| 18271 |
filename (str): The path to the archive file to extract. Supported |
| 18272 |
formats are .zip and .tgz. |
| 18273 |
|
| 18274 |
Raises: |
| 18275 |
EOFError: If the archive file is incomplete or corrupted (e.g., |
| 18276 |
unexpected end of file). |
| 18277 |
Exception: If a file in the archive would be extracted outside the |
| 18278 |
intended directory. |
| 18279 |
|
| 18280 |
Returns: |
| 18281 |
list: A list of extracted file paths. If the archive is invalid or |
| 18282 |
extraction fails, returns an empty list or an Exception. |
| 18283 |
|
| 18284 |
""" |
| 18285 |
extracted = [] |
| 18286 |
if filename.lower().endswith(".zip"): |
| 18287 |
cls = zipfile.ZipFile |
| 18288 |
mode = "r" |
| 18289 |
elif filename.lower().endswith(".tgz"): |
| 18290 |
cls = TarFileProper.open # classmethod |
| 18291 |
mode = "r:gz" |
| 18292 |
else: |
| 18293 |
return extracted |
| 18294 |
try: |
| 18295 |
with cls(filename, mode) as z: |
| 18296 |
outdir = os.path.realpath(os.path.dirname(filename)) |
| 18297 |
method = z.getnames if cls is not zipfile.ZipFile else z.namelist |
| 18298 |
names = method() |
| 18299 |
names.sort() |
| 18300 |
extracted = [ |
| 18301 |
os.path.join(outdir, os.path.normpath(name)) for name in names |
| 18302 |
] |
| 18303 |
if names: |
| 18304 |
name0 = os.path.normpath(names[0]) |
| 18305 |
for outpath in extracted: |
| 18306 |
if not os.path.realpath(outpath).startswith( |
| 18307 |
os.path.join(outdir, name0) |
| 18308 |
): |
| 18309 |
return Error(lang.getstr("file.invalid") + "\n" + filename) |
| 18310 |
if cls is not zipfile.ZipFile: |
| 18311 |
z.extractall(outdir) |
| 18312 |
else: |
| 18313 |
for name in names: |
| 18314 |
# If the ZIP file was created with Unicode names stored |
| 18315 |
# in the file, 'name' will already be Unicode. |
| 18316 |
# Otherwise, it'll either be 7-bit ASCII or (legacy) |
| 18317 |
# cp437 encoding |
| 18318 |
outname = name |
| 18319 |
outpath = os.path.join(outdir, os.path.normpath(outname)) |
| 18320 |
if outname.endswith("/"): |
| 18321 |
if not os.path.isdir(outpath): |
| 18322 |
os.makedirs(outpath) |
| 18323 |
elif not os.path.isfile(outpath): |
| 18324 |
with open(outpath, "wb") as outfile: |
| 18325 |
outfile.write(z.read(name)) |
| 18326 |
except Exception: |
| 18327 |
# Corrupt/incomplete archive. Delete it so a retry gets a clean file. |
| 18328 |
if os.path.isfile(filename): |
| 18329 |
print(lang.getstr("archive.extract.fail.delete", filename)) |
| 18330 |
os.remove(filename) |
| 18331 |
raise |
| 18332 |
return extracted |
| 18333 |
|
| 18334 |
def _reopen_argyll_download_prompt(self): |
| 18335 |
"""Re-open the Argyll download prompt after a failed archive download.""" |
| 18336 |
if not self.owner: |
| 18337 |
return |
| 18338 |
from DisplayCAL.display_cal import app_update_check |
| 18339 |
|
| 18340 |
app_update_check(self.owner, argyll=True) |
| 18341 |
|
| 18342 |
def set_argyll_bin(self, result, filename): |
| 18343 |
"""Set Argyll bin directory. |
| 18344 |
|
| 18345 |
Args: |
| 18346 |
result (str | Exception): Either a str showing the result message |
| 18347 |
or an Exception. |
| 18348 |
filename (str): The archive filename. |
| 18349 |
""" |
| 18350 |
if isinstance(result, Exception): |
| 18351 |
if not os.path.isfile(filename): |
| 18352 |
retry = show_result_dialog( |
| 18353 |
result, |
| 18354 |
self.owner, |
| 18355 |
confirm=lang.getstr("retry"), |
| 18356 |
) |
| 18357 |
if retry: |
| 18358 |
self._reopen_argyll_download_prompt() |
| 18359 |
else: |
| 18360 |
show_result_dialog(result, self.owner) |
| 18361 |
elif result and os.path.isdir(result[0]): |
| 18362 |
setcfg("argyll.dir", os.path.join(result[0], "bin")) |
| 18363 |
# Always write cfg directly after setting Argyll directory so |
| 18364 |
# subprocesses that read the configuration will use the right |
| 18365 |
# executables |
| 18366 |
writecfg() |
| 18367 |
from DisplayCAL.display_cal import check_donation |
| 18368 |
|
| 18369 |
snapshot = False |
| 18370 |
self.owner.set_argyll_bin_handler( |
| 18371 |
None, |
| 18372 |
True, |
| 18373 |
self.owner.check_instrument_setup, |
| 18374 |
(check_donation, (self.owner, snapshot)), |
| 18375 |
) |
| 18376 |
else: |
| 18377 |
show_result_dialog( |
| 18378 |
lang.getstr("error.no_files_extracted_from_archive", filename), |
| 18379 |
self.owner, |
| 18380 |
) |
| 18381 |
|
| 18382 |
def process_download(self, result, exit_=False): |
| 18383 |
"""Process download. |
| 18384 |
|
| 18385 |
Args: |
| 18386 |
result (str, Exception): Either a str or an Exception to process. |
| 18387 |
exit_ (bool): If True close the owner window if any otherwise close |
| 18388 |
the main application. If False do not do anything. |
| 18389 |
""" |
| 18390 |
if isinstance(result, Exception): |
| 18391 |
show_result_dialog(result, self.owner) |
| 18392 |
elif result: |
| 18393 |
if exit_: |
| 18394 |
if self.owner: |
| 18395 |
self.owner.Close() |
| 18396 |
else: |
| 18397 |
wx.GetApp().ExitMainLoop() |
| 18398 |
launch_file(result) |
| 18399 |
|
| 18400 |
def verify_calibration(self): |
| 18401 |
"""Verify the current calibration. |
| 18402 |
|
| 18403 |
Returns: |
| 18404 |
str or Exception: The result of the verification, which can be a |
| 18405 |
str indicating success or an Exception if an error occurred. |
| 18406 |
""" |
| 18407 |
result = self.detect_video_levels() |
| 18408 |
if isinstance(result, Exception) or not result: |
| 18409 |
return result |
| 18410 |
cmd, args = self.prepare_dispcal(calibrate=False, verify=True) |
| 18411 |
if not isinstance(cmd, Exception): |
| 18412 |
result = self.exec_cmd(cmd, args, capture_output=True, skip_scripts=True) |
| 18413 |
else: |
| 18414 |
result = cmd |
| 18415 |
return result |
| 18416 |
|
| 18417 |
def measure_ti1( |
| 18418 |
self, ti1_path, cal_path=None, colormanaged=False, allow_video_levels=True |
| 18419 |
): |
| 18420 |
"""Measure a TI1 testchart file. |
| 18421 |
|
| 18422 |
Args: |
| 18423 |
ti1_path (str): Path to the TI1 file to measure. |
| 18424 |
cal_path (str): Path to the calibration file, if any. |
| 18425 |
colormanaged (bool): Whether the measurement is color managed. |
| 18426 |
allow_video_levels (bool): Whether to allow video levels in the |
| 18427 |
measurement. |
| 18428 |
|
| 18429 |
Returns: |
| 18430 |
str or Exception: The path to the measured TI1 file, or an |
| 18431 |
Exception if an error occurred. |
| 18432 |
""" |
| 18433 |
if allow_video_levels: |
| 18434 |
result = self.detect_video_levels() |
| 18435 |
if isinstance(result, Exception) or not result: |
| 18436 |
return result |
| 18437 |
if config.get_display_name() == "Untethered": |
| 18438 |
cmd, args = get_argyll_util("spotread"), ["-v", "-e"] |
| 18439 |
if getcfg("extra_args.spotread").strip(): |
| 18440 |
args += parse_argument_string(getcfg("extra_args.spotread")) |
| 18441 |
result = self.set_terminal_cgats(ti1_path) |
| 18442 |
if isinstance(result, Exception): |
| 18443 |
return result |
| 18444 |
else: |
| 18445 |
cmd = get_argyll_util("dispread") |
| 18446 |
args = ["-v"] |
| 18447 |
if getcfg("argyll.debug"): |
| 18448 |
args.append("-D8") |
| 18449 |
if config.get_display_name() in ("madVR", "Prisma") and colormanaged: |
| 18450 |
args.append("-V") |
| 18451 |
if cal_path: |
| 18452 |
if self.argyll_version >= [1, 3, 3] and ( |
| 18453 |
not self.has_lut_access() or not getcfg("calibration.use_video_lut") |
| 18454 |
): |
| 18455 |
args.append("-K") |
| 18456 |
else: |
| 18457 |
args.append("-k") |
| 18458 |
args.append(cal_path) |
| 18459 |
if getcfg("extra_args.dispread").strip(): |
| 18460 |
args += parse_argument_string(getcfg("extra_args.dispread")) |
| 18461 |
if sys.platform == "win32": |
| 18462 |
args = quote_args(args) |
| 18463 |
result = self.add_measurement_features( |
| 18464 |
args, |
| 18465 |
cmd == get_argyll_util("dispread"), |
| 18466 |
allow_nondefault_observer=is_ccxx_testchart(), |
| 18467 |
allow_video_levels=allow_video_levels, |
| 18468 |
quantize=True, |
| 18469 |
) |
| 18470 |
if isinstance(result, Exception): |
| 18471 |
return result |
| 18472 |
self.options_dispread = list(args) |
| 18473 |
if config.get_display_name() != "Untethered": |
| 18474 |
args.append(os.path.splitext(ti1_path)[0]) |
| 18475 |
return self.exec_cmd(cmd, args, skip_scripts=True) |
| 18476 |
|
| 18477 |
def wrapup(self, copy=True, remove=True, dst_path=None, ext_filter=None): |
| 18478 |
"""Wrap up - copy and/or clean temporary file(s). |
| 18479 |
|
| 18480 |
Args: |
| 18481 |
copy (bool or Exception): If True, copy temporary files to |
| 18482 |
`dst_path` (if given) or to the default save path. |
| 18483 |
If False, do not copy temporary files. |
| 18484 |
remove (bool): If True, remove temporary files. |
| 18485 |
dst_path (str): Destination path to copy temporary files to. |
| 18486 |
ext_filter (list of str): List of file extensions to filter out |
| 18487 |
when copying temporary files. If None, defaults to a |
| 18488 |
predefined list of common file extensions. |
| 18489 |
|
| 18490 |
Returns: |
| 18491 |
bool or Exception: True if successful, False if nothing to do, |
| 18492 |
or an Exception if an error occurred. |
| 18493 |
""" |
| 18494 |
if DEBUG: |
| 18495 |
print(f"[D] wrapup(copy={copy}, remove={remove})") |
| 18496 |
if not self.tempdir or not os.path.isdir(self.tempdir): |
| 18497 |
return None # nothing to do |
| 18498 |
if ( |
| 18499 |
isinstance(copy, Exception) |
| 18500 |
and not isinstance(copy, (UnloggedError, UnloggedInfo, UnloggedWarning)) |
| 18501 |
and self.sessionlogfile |
| 18502 |
): |
| 18503 |
# This is an incomplete run, log exception to session logfile |
| 18504 |
self.sessionlogfile.write(safe_basestring(copy)) |
| 18505 |
while self.sessionlogfiles: |
| 18506 |
self.sessionlogfiles.popitem()[1].close() |
| 18507 |
self.sessionlogfile = None |
| 18508 |
if isinstance(copy, Exception): |
| 18509 |
# This is an incomplete run, check if any files have been added or |
| 18510 |
# modified (except log files and 'hidden' temporary files) |
| 18511 |
changes = False |
| 18512 |
for filename in os.listdir(self.tempdir): |
| 18513 |
if filename.endswith(".log") or filename in ( |
| 18514 |
".abort", |
| 18515 |
".ok", |
| 18516 |
".wait", |
| 18517 |
".wait.cmd", |
| 18518 |
".wait.py", |
| 18519 |
): |
| 18520 |
# Skip log files and 'hidden' temporary files |
| 18521 |
continue |
| 18522 |
if ( |
| 18523 |
filename not in self.tmpfiles |
| 18524 |
or os.stat(os.path.join(self.tempdir, filename)).st_mtime |
| 18525 |
!= self.tmpfiles[filename] |
| 18526 |
): |
| 18527 |
changes = True |
| 18528 |
break |
| 18529 |
if not changes: |
| 18530 |
copy = False |
| 18531 |
result = True |
| 18532 |
if copy: |
| 18533 |
try: |
| 18534 |
src_listdir = os.listdir(self.tempdir) |
| 18535 |
except Exception as exception: |
| 18536 |
result = exception |
| 18537 |
remove = False |
| 18538 |
if not isinstance(result, Exception) and src_listdir: |
| 18539 |
if not ext_filter: |
| 18540 |
ext_filter = [ |
| 18541 |
".app", |
| 18542 |
".cal", |
| 18543 |
".ccmx", |
| 18544 |
".ccss", |
| 18545 |
".cmd", |
| 18546 |
".command", |
| 18547 |
".gam", |
| 18548 |
".gz", |
| 18549 |
".icc", |
| 18550 |
".icm", |
| 18551 |
".log", |
| 18552 |
".png", |
| 18553 |
".sh", |
| 18554 |
".ti1", |
| 18555 |
".ti3", |
| 18556 |
".wrl", |
| 18557 |
".wrz", |
| 18558 |
] |
| 18559 |
save_path = getcfg("profile.save_path") |
| 18560 |
if dst_path is None: |
| 18561 |
dst_path = os.path.join( |
| 18562 |
save_path, |
| 18563 |
getcfg("profile.name.expanded"), |
| 18564 |
getcfg("profile.name.expanded") + ".ext", |
| 18565 |
) |
| 18566 |
if isinstance(copy, Exception): |
| 18567 |
# This is an incomplete run |
| 18568 |
parts = os.path.normpath(dst_path).split(os.sep) |
| 18569 |
# DON'T use os.path.join due to how it works under Windows: |
| 18570 |
# os.path.join("c:", "foo") represents a path relative to |
| 18571 |
# the current directory on drive C: (c:foo), not c:\foo. |
| 18572 |
|
| 18573 |
# Save incomplete runs to different directory |
| 18574 |
parts = [config.DATA_HOME, "incomplete"] + parts[-2:] |
| 18575 |
dst_path = os.sep.join(parts) |
| 18576 |
result = check_create_dir(os.path.dirname(dst_path)) |
| 18577 |
if isinstance(result, Exception): |
| 18578 |
remove = False |
| 18579 |
else: |
| 18580 |
if isinstance(copy, Exception): |
| 18581 |
print( |
| 18582 |
"Moving files of incomplete run to", |
| 18583 |
os.path.dirname(dst_path), |
| 18584 |
) |
| 18585 |
for basename in src_listdir: |
| 18586 |
name, ext = os.path.splitext(basename) |
| 18587 |
if ext_filter is None or ext.lower() in ext_filter: |
| 18588 |
src = os.path.join(self.tempdir, basename) |
| 18589 |
dst = os.path.join(os.path.dirname(dst_path), basename) |
| 18590 |
if sys.platform == "win32": |
| 18591 |
dst = make_win32_compatible_long_path(dst) |
| 18592 |
if os.path.exists(dst): |
| 18593 |
if os.path.isdir(dst): |
| 18594 |
if VERBOSE >= 2: |
| 18595 |
print( |
| 18596 |
f"{APPNAME}: Removing existing destination " |
| 18597 |
"directory tree", |
| 18598 |
dst, |
| 18599 |
) |
| 18600 |
try: |
| 18601 |
shutil.rmtree(dst, True) |
| 18602 |
except Exception as exception: |
| 18603 |
print( |
| 18604 |
f"Warning - directory '{dst}' " |
| 18605 |
f"could not be removed: {exception}" |
| 18606 |
) |
| 18607 |
else: |
| 18608 |
if VERBOSE >= 2: |
| 18609 |
print( |
| 18610 |
f"{APPNAME}: Removing existing destination " |
| 18611 |
"file", |
| 18612 |
dst, |
| 18613 |
) |
| 18614 |
try: |
| 18615 |
os.remove(dst) |
| 18616 |
except Exception as exception: |
| 18617 |
print( |
| 18618 |
f"Warning - file '{dst}' " |
| 18619 |
f"could not be removed: {exception}" |
| 18620 |
) |
| 18621 |
if remove: |
| 18622 |
if VERBOSE >= 2: |
| 18623 |
print( |
| 18624 |
f"{APPNAME}: Moving temporary object " |
| 18625 |
f"{src} to {dst}" |
| 18626 |
) |
| 18627 |
try: |
| 18628 |
shutil.move(src, dst) |
| 18629 |
except Exception as exception: |
| 18630 |
print( |
| 18631 |
f"Warning - temporary object '{src}' could not " |
| 18632 |
f"be moved to '{dst}': {exception}" |
| 18633 |
) |
| 18634 |
try: |
| 18635 |
shutil.copyfile(src, dst) |
| 18636 |
except Exception as exception: |
| 18637 |
result2 = Error( |
| 18638 |
lang.getstr("error.copy_failed", (src, dst)) |
| 18639 |
+ "\n" |
| 18640 |
+ str(exception) |
| 18641 |
) |
| 18642 |
if isinstance(result, Exception): |
| 18643 |
result = "\n".join( |
| 18644 |
str(error) |
| 18645 |
for error in (result, result2) |
| 18646 |
) |
| 18647 |
else: |
| 18648 |
result = result2 |
| 18649 |
remove = False |
| 18650 |
elif os.path.isdir(src): |
| 18651 |
if VERBOSE >= 2: |
| 18652 |
print( |
| 18653 |
f"{APPNAME}: Copying temporary " |
| 18654 |
f"directory tree {src} to {dst}" |
| 18655 |
) |
| 18656 |
try: |
| 18657 |
shutil.copytree(src, dst) |
| 18658 |
except Exception as exception: |
| 18659 |
print( |
| 18660 |
f"Warning - temporary directory '{src}' " |
| 18661 |
"could not be copied to " |
| 18662 |
f"'{dst}': {exception}" |
| 18663 |
) |
| 18664 |
else: |
| 18665 |
if VERBOSE >= 2: |
| 18666 |
print( |
| 18667 |
f"{APPNAME}: Copying temporary " |
| 18668 |
f"file {src} to {dst}" |
| 18669 |
) |
| 18670 |
try: |
| 18671 |
shutil.copyfile(src, dst) |
| 18672 |
except Exception as exception: |
| 18673 |
print( |
| 18674 |
f"Warning - temporary file '{src}' could " |
| 18675 |
f"not be copied to '{dst}': {exception}" |
| 18676 |
) |
| 18677 |
if remove: |
| 18678 |
try: |
| 18679 |
src_listdir = os.listdir(self.tempdir) |
| 18680 |
except Exception as exception: |
| 18681 |
print(f"Error - directory '{self.tempdir}' listing failed: {exception}") |
| 18682 |
else: |
| 18683 |
for basename in src_listdir: |
| 18684 |
name, ext = os.path.splitext(basename) |
| 18685 |
if ext_filter is None or ext.lower() not in ext_filter: |
| 18686 |
src = os.path.join(self.tempdir, basename) |
| 18687 |
isdir = os.path.isdir(src) |
| 18688 |
if isdir: |
| 18689 |
if VERBOSE >= 2: |
| 18690 |
print( |
| 18691 |
f"{APPNAME}: Removing temporary directory tree", |
| 18692 |
src, |
| 18693 |
) |
| 18694 |
try: |
| 18695 |
shutil.rmtree(src, True) |
| 18696 |
except Exception as exception: |
| 18697 |
print( |
| 18698 |
f"Warning - temporary directory '{src}' could not " |
| 18699 |
f"be removed: {exception}" |
| 18700 |
) |
| 18701 |
else: |
| 18702 |
if VERBOSE >= 2: |
| 18703 |
print(f"{APPNAME}: Removing temporary file", src) |
| 18704 |
try: |
| 18705 |
os.remove(src) |
| 18706 |
except Exception as exception: |
| 18707 |
print( |
| 18708 |
f"Warning - temporary file '{src}' could not be " |
| 18709 |
f"removed: {exception}" |
| 18710 |
) |
| 18711 |
try: |
| 18712 |
src_listdir = os.listdir(self.tempdir) |
| 18713 |
except Exception as exception: |
| 18714 |
print(f"Error - directory '{self.tempdir}' listing failed: {exception}") |
| 18715 |
else: |
| 18716 |
if not src_listdir: |
| 18717 |
if VERBOSE >= 2: |
| 18718 |
print( |
| 18719 |
f"{APPNAME}: Removing empty temporary directory", |
| 18720 |
self.tempdir, |
| 18721 |
) |
| 18722 |
try: |
| 18723 |
shutil.rmtree(self.tempdir, True) |
| 18724 |
except Exception as exception: |
| 18725 |
print( |
| 18726 |
f"Warning - temporary directory '{self.tempdir}' could " |
| 18727 |
f"not be removed: {exception}" |
| 18728 |
) |
| 18729 |
if isinstance(result, Exception): |
| 18730 |
result = Error( |
| 18731 |
"{}\n\n{}".format( |
| 18732 |
result, |
| 18733 |
lang.getstr("tempdir_should_still_contain_files", self.tempdir), |
| 18734 |
) |
| 18735 |
) |
| 18736 |
return result |
| 18737 |
|
| 18738 |
def write(self, txt): |
| 18739 |
"""Write text to the terminal. |
| 18740 |
|
| 18741 |
Args: |
| 18742 |
txt (str): Text to write. |
| 18743 |
""" |
| 18744 |
if True: |
| 18745 |
# Don't buffer |
| 18746 |
self._write(txt) |
| 18747 |
return |
| 18748 |
# NEVER - Use line buffer |
| 18749 |
self.buffer.append(txt) |
| 18750 |
self.buffer = list(StringIO("".join(self.buffer))) |
| 18751 |
for line in self.buffer: |
| 18752 |
if not ( |
| 18753 |
line.endswith("\n") |
| 18754 |
or line.rstrip().endswith(":") |
| 18755 |
or line.rstrip().endswith(",") |
| 18756 |
or line.rstrip().endswith(".") |
| 18757 |
): |
| 18758 |
break |
| 18759 |
self._write(line) |
| 18760 |
self.buffer = self.buffer[1:] |
| 18761 |
|
| 18762 |
def _write(self, txt): |
| 18763 |
if isinstance(txt, bytes): |
| 18764 |
txt = txt.decode() |
| 18765 |
|
| 18766 |
wx.CallAfter(self.audio_visual_feedback, txt) |
| 18767 |
if getattr(self, "measure_cmd", None): |
| 18768 |
# i1 Pro, Spyders: Instrument Type |
| 18769 |
# i1D3: Product Name |
| 18770 |
# K10: Model |
| 18771 |
# specbos: Identification |
| 18772 |
instrument = re.search( |
| 18773 |
r"(?:Instrument Type|Product Name|Model|Identificaton):\s+([^\r\n]+)", |
| 18774 |
txt, |
| 18775 |
re.I, |
| 18776 |
) |
| 18777 |
if instrument: |
| 18778 |
self._detected_instrument = instrument.group(1) |
| 18779 |
serial = re.search(r"(?:Serial Number):\s+([^\r\n]+)", txt, re.I) |
| 18780 |
if serial: |
| 18781 |
self._detected_instrument_serial = serial.group(1) |
| 18782 |
if re.search(r"press 1|space when done|patch 1 of ", txt, re.I) and ( |
| 18783 |
# There are some intial measurements which we can't check for |
| 18784 |
# unless -D (debug) is used for Argyll tools |
| 18785 |
"patch 1 of " not in txt.lower() or not self.patch_sequence |
| 18786 |
): |
| 18787 |
if "patch 1 of " in txt.lower(): |
| 18788 |
self.patch_sequence = True |
| 18789 |
self.patch_count = 0 |
| 18790 |
self.patterngenerator_sent_count = 0 |
| 18791 |
update = re.search( |
| 18792 |
r"[/\\] current|patch \d+ of |" |
| 18793 |
r"the instrument can be removed from the screen", |
| 18794 |
txt, |
| 18795 |
re.I, |
| 18796 |
) |
| 18797 |
# Send colors to pattern generator |
| 18798 |
use_patterngenerator = ( |
| 18799 |
self.use_patterngenerator |
| 18800 |
and self.patterngenerator |
| 18801 |
and hasattr(self.patterngenerator, "conn") |
| 18802 |
) |
| 18803 |
if use_patterngenerator or self.use_madnet_tpg or self._use_patternwindow: |
| 18804 |
# sometimes the data is not fully received |
| 18805 |
if self.partial_data != "": |
| 18806 |
# combine the partial data with the currently received one |
| 18807 |
self.log(f"Combining previous data of: {self.partial_data}") |
| 18808 |
self.log(f"with : {txt}") |
| 18809 |
txt = self.partial_data + txt |
| 18810 |
self.log(f"to : {txt}") |
| 18811 |
|
| 18812 |
rgb = re.search(r"Current RGB(?:\s+\d+){3}((?:\s+\d+(?:\.\d+)){3})", txt) |
| 18813 |
# Check if the data is partial |
| 18814 |
if "Current RGB" in txt and rgb is None: |
| 18815 |
self.log(f"Data is not fully received, storing partial data: {txt}") |
| 18816 |
self.partial_data = txt |
| 18817 |
|
| 18818 |
if rgb: |
| 18819 |
# reset the partial data storage, as we fully received the data |
| 18820 |
self.partial_data = "" |
| 18821 |
update_ffp_insertion_ts = False |
| 18822 |
if ( |
| 18823 |
getcfg("patterngenerator.ffp_insertion") |
| 18824 |
and self.patterngenerator_sent_count > 1 |
| 18825 |
): |
| 18826 |
# Frame insertion |
| 18827 |
frq = getcfg("patterngenerator.ffp_insertion.interval") |
| 18828 |
if time() - getattr(self, "_ffp_insertion_ts", 0) > frq: |
| 18829 |
dur = getcfg("patterngenerator.ffp_insertion.duration") |
| 18830 |
lvl = getcfg("patterngenerator.ffp_insertion.level") |
| 18831 |
self.log( |
| 18832 |
f"{APPNAME}: Frame insertion duration {dur:d}s, " |
| 18833 |
f"level = {lvl * 100:d}%" |
| 18834 |
) |
| 18835 |
ts = time() |
| 18836 |
patternconfig = [] |
| 18837 |
if self.use_madnet_tpg: |
| 18838 |
patternconfig = self.madtpg.get_pattern_config() |
| 18839 |
self.madtpg.set_pattern_config( |
| 18840 |
patternconfig[0], int(lvl * 100), 0, 0 |
| 18841 |
) |
| 18842 |
self.madtpg.show_rgb(lvl, lvl, lvl) |
| 18843 |
self.madtpg.set_pattern_config(100, 0, 0, 0) |
| 18844 |
else: |
| 18845 |
self.patterngenerator_send((lvl, lvl, lvl), (lvl, lvl, lvl)) |
| 18846 |
while time() - ts < dur and not ( |
| 18847 |
self.subprocess_abort or self.thread_abort |
| 18848 |
): |
| 18849 |
sleep(0.05) |
| 18850 |
if self.use_madnet_tpg: |
| 18851 |
self.madtpg.set_pattern_config(*patternconfig) |
| 18852 |
update_ffp_insertion_ts = True |
| 18853 |
if ( |
| 18854 |
not hasattr(self, "_ffp_insertion_ts") |
| 18855 |
or update_ffp_insertion_ts |
| 18856 |
): |
| 18857 |
self._ffp_insertion_ts = time() |
| 18858 |
rgb = [float(v) for v in rgb.groups()[0].strip().split()] |
| 18859 |
if self.use_madnet_tpg: |
| 18860 |
if self.madtpg.show_rgb(*rgb): |
| 18861 |
self.patterngenerator_sent_count += 1 |
| 18862 |
self.log( |
| 18863 |
f"{APPNAME}: MadTPG_Net sent count: " |
| 18864 |
f"{self.patterngenerator_sent_count}" |
| 18865 |
) |
| 18866 |
else: |
| 18867 |
self.exec_cmd_returnvalue = Error( |
| 18868 |
lang.getstr("patterngenerator.sync_lost") |
| 18869 |
) |
| 18870 |
self.abort_subprocess() |
| 18871 |
else: |
| 18872 |
self.patterngenerator_send(rgb) |
| 18873 |
if getcfg("patterngenerator.ffp_insertion") and update_ffp_insertion_ts: |
| 18874 |
# Delay to allow patch update and settle time after |
| 18875 |
# frame insertion. If display update delay is bigger, |
| 18876 |
# do not use extra delay. Otherwise, subtract display |
| 18877 |
# update delay from fixed delay. |
| 18878 |
if getcfg("measure.override_min_display_update_delay_ms"): |
| 18879 |
dur = getcfg("measure.min_display_update_delay_ms") / 1000.0 |
| 18880 |
else: |
| 18881 |
dur = 0 |
| 18882 |
ts = time() |
| 18883 |
while time() - ts < max(0.8 - dur, 0) and not ( |
| 18884 |
self.subprocess_abort or self.thread_abort |
| 18885 |
): |
| 18886 |
sleep(0.05) |
| 18887 |
# Create .ok file which will be picked up by .wait script |
| 18888 |
okfilename = os.path.join(self.tempdir, ".ok") |
| 18889 |
open(okfilename, "w").close() |
| 18890 |
if update and ( |
| 18891 |
# Check if patch count is higher than patterngenerator sent count |
| 18892 |
self.patch_count > self.patterngenerator_sent_count |
| 18893 |
and self.exec_cmd_returnvalue is None |
| 18894 |
): |
| 18895 |
# XXX: This can happen when pausing/unpausing? |
| 18896 |
# Need to investigate |
| 18897 |
self.log("Warning - did we loose sync with the pattern generator?") |
| 18898 |
# self.exec_cmd_returnvalue = ( |
| 18899 |
# Error(lang.getstr("patterngenerator.sync_lost")) |
| 18900 |
# ) |
| 18901 |
# self.abort_subprocess() |
| 18902 |
if update and not ( |
| 18903 |
self.subprocess_abort |
| 18904 |
or self.thread_abort |
| 18905 |
or "the instrument can be removed from the screen" in txt.lower() |
| 18906 |
): |
| 18907 |
self.patch_count += 1 |
| 18908 |
if use_patterngenerator or self.use_madnet_tpg: |
| 18909 |
self.log(f"{APPNAME}: Patch update count: {self.patch_count:d}") |
| 18910 |
if self.use_madnet_tpg: |
| 18911 |
progress = re.search( |
| 18912 |
r"(?:Patch (\d+) of|Number of patches =) (\d+)", txt, re.I |
| 18913 |
) |
| 18914 |
if progress: |
| 18915 |
# Set madTPG progress bar |
| 18916 |
try: |
| 18917 |
start = int(progress.group(1) or 0) |
| 18918 |
end = int(progress.group(2)) |
| 18919 |
except ValueError: |
| 18920 |
pass |
| 18921 |
else: |
| 18922 |
self.madtpg.set_progress_bar_pos(start, end) |
| 18923 |
# Parse |
| 18924 |
wx.CallAfter(self.parse, txt) |
| 18925 |
|
| 18926 |
@property |
| 18927 |
def _use_patternwindow(self): |
| 18928 |
# Preliminary Wayland support. This still needs a lot |
| 18929 |
# of work as Argyll doesn't support Wayland natively yet, |
| 18930 |
# so we use virtual display to drive our own patch window. |
| 18931 |
return ( |
| 18932 |
not config.is_virtual_display() |
| 18933 |
and ( |
| 18934 |
# os.getenv("XDG_SESSION_TYPE") == "wayland" |
| 18935 |
getcfg("patterngenerator.use_pattern_window") |
| 18936 |
) |
| 18937 |
and self.argyll_virtual_display |
| 18938 |
) |