| 1 |
"""Runtime configuration and user settings parser.""" |
| 2 |
|
| 3 |
# Standard Library Imports |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import configparser |
| 7 |
import contextlib |
| 8 |
import locale |
| 9 |
import math |
| 10 |
import os |
| 11 |
import re |
| 12 |
import string |
| 13 |
import sys |
| 14 |
import tempfile |
| 15 |
import time |
| 16 |
from decimal import Decimal |
| 17 |
from enum import IntEnum |
| 18 |
from typing import TYPE_CHECKING, Any |
| 19 |
|
| 20 |
|
| 21 |
# Local Imports |
| 22 |
import DisplayCAL |
| 23 |
from DisplayCAL import colormath |
| 24 |
from DisplayCAL.argyll_names import INTENTS, OBSERVERS, VIDEO_ENCODINGS, VIEWCONDS |
| 25 |
|
| 26 |
if sys.platform == "win32": |
| 27 |
from DisplayCAL.defaultpaths import COMMON_PROGRAM_FILES |
| 28 |
elif sys.platform == "darwin": |
| 29 |
from DisplayCAL.defaultpaths import LIBRARY, LIBRARY_HOME, PREFS, PREFS_HOME |
| 30 |
else: |
| 31 |
from DisplayCAL.defaultpaths import ( |
| 32 |
XDG_CONFIG_DIR_DEFAULT, |
| 33 |
XDG_CONFIG_HOME, |
| 34 |
XDG_DATA_DIRS, |
| 35 |
XDG_DATA_HOME, |
| 36 |
XDG_DATA_HOME_DEFAULT, |
| 37 |
) |
| 38 |
|
| 39 |
from DisplayCAL.defaultpaths import ( # noqa: F401 |
| 40 |
APPDATA, |
| 41 |
AUTOSTART, # don't remove this, imported by other modules |
| 42 |
AUTOSTART_HOME, # don't remove this, imported by other modules |
| 43 |
COMMONAPPDATA, |
| 44 |
HOME, # don't remove this, imported by other modules |
| 45 |
ICCPROFILES, |
| 46 |
ICCPROFILES_HOME, |
| 47 |
) |
| 48 |
from DisplayCAL.meta import VERSION_STRING |
| 49 |
from DisplayCAL.meta import NAME as APPNAME |
| 50 |
from DisplayCAL.options import DEBUG |
| 51 |
from DisplayCAL.safe_print import ( # noqa: F401 |
| 52 |
ENC, # don't remove this, imported by other modules |
| 53 |
FS_ENC, |
| 54 |
) |
| 55 |
from DisplayCAL.util_io import StringIOu as StringIO |
| 56 |
from DisplayCAL.util_os import ( |
| 57 |
FileLock, |
| 58 |
expanduseru, |
| 59 |
getenvu, |
| 60 |
is_superuser, |
| 61 |
listdir_re, |
| 62 |
which, |
| 63 |
) |
| 64 |
from DisplayCAL.util_str import create_replace_function, strtr |
| 65 |
|
| 66 |
if TYPE_CHECKING: |
| 67 |
from DisplayCAL.icc_profile import ICCProfile |
| 68 |
from DisplayCAL.worker import Worker |
| 69 |
from DisplayCAL.wx_addons import wx # noqa: TC004 |
| 70 |
|
| 71 |
configparser.DEFAULTSECT = "Default" # Sadly, this line needs to be here. |
| 72 |
|
| 73 |
EXE = sys.executable |
| 74 |
EXEDIR = os.path.dirname(EXE) |
| 75 |
EXENAME = os.path.basename(EXE) |
| 76 |
|
| 77 |
ISEXE = sys.platform != "darwin" and getattr(sys, "frozen", False) |
| 78 |
|
| 79 |
if ISEXE and (_meipass2 := os.getenv("_MEIPASS2")): |
| 80 |
os.environ["_MEIPASS2"] = _meipass2.replace("/", os.path.sep) |
| 81 |
|
| 82 |
PYFILE = ( |
| 83 |
EXE |
| 84 |
if ISEXE |
| 85 |
else (os.path.isfile(sys.argv[0]) and sys.argv[0]) |
| 86 |
or os.path.join(os.path.dirname(__file__), "main.py") |
| 87 |
) |
| 88 |
PYPATH = EXE if ISEXE else os.path.abspath(PYFILE) |
| 89 |
# Mac OS X: isapp should only be true for standalone, not 0install |
| 90 |
ISAPP = ( |
| 91 |
sys.platform == "darwin" |
| 92 |
and EXE.split(os.path.sep)[-3:-1] == ["Contents", "MacOS"] |
| 93 |
and os.path.exists(os.path.join(EXEDIR, "..", "Resources", "xrc")) |
| 94 |
) |
| 95 |
if ISAPP: |
| 96 |
PYNAME, PYEXT = os.path.splitext(EXE.split(os.path.sep)[-4]) |
| 97 |
PYDIR = os.path.normpath(os.path.join(EXEDIR, "..", "Resources")) |
| 98 |
else: |
| 99 |
PYNAME, PYEXT = os.path.splitext(os.path.basename(PYPATH)) |
| 100 |
PYDIR = os.path.dirname( |
| 101 |
EXE if ISEXE else os.path.abspath(os.path.dirname(__file__)) |
| 102 |
) |
| 103 |
|
| 104 |
# TODO: Modifying ``data_dirs`` here was not an elegant solution, |
| 105 |
# and it is not solving the problem either. |
| 106 |
DATA_DIRS = [ |
| 107 |
# venv/share/DisplayCAL |
| 108 |
os.path.join(os.path.dirname(os.path.dirname(PYPATH)), "share", "DisplayCAL"), |
| 109 |
# venv/lib/python3.x/site-packages/DisplayCAL |
| 110 |
PYDIR, |
| 111 |
# venv/share |
| 112 |
os.path.join(os.path.dirname(PYDIR), "share"), |
| 113 |
# venv/lib/python3.x/site-packages/DisplayCAL-*.egg/share/DisplayCAL |
| 114 |
os.path.join(os.path.dirname(PYDIR), "share", "DisplayCAL"), |
| 115 |
] |
| 116 |
|
| 117 |
|
| 118 |
EXTRA_DATA_DIRS = [] |
| 119 |
# Search directories on PATH for data directories so Argyll reference files can |
| 120 |
# be found automatically if Argyll directory not explicitly configured |
| 121 |
for dir_ in getenvu("PATH", "").split(os.pathsep): |
| 122 |
dir_parent = os.path.dirname(dir_) |
| 123 |
if os.path.isdir(os.path.join(dir_parent, "ref")): |
| 124 |
EXTRA_DATA_DIRS.append(dir_parent) |
| 125 |
|
| 126 |
APPBASENAME = APPNAME |
| 127 |
# If old user data directory exists, use its basename |
| 128 |
if os.path.isdir(os.path.join(APPDATA, "dispcalGUI")): |
| 129 |
APPBASENAME = "dispcalGUI" |
| 130 |
DATA_DIRS.append(os.path.join(APPDATA, APPNAME)) |
| 131 |
DATA_HOME = os.path.join(APPDATA, APPBASENAME) |
| 132 |
if sys.platform == "win32": |
| 133 |
if PYDIR.lower().startswith(EXEDIR.lower()) and PYDIR != EXEDIR: |
| 134 |
# We are installed in a subfolder of the executable directory |
| 135 |
# (e.g. C:\Python26\Lib\site-packages\DisplayCAL) |
| 136 |
# we need to add the executable directory to the data directories so |
| 137 |
# files in subfolders of the executable directory which are not in |
| 138 |
# Lib\site-packages\DisplayCAL can be found |
| 139 |
# (e.g. Scripts\displaycal-apply-profiles) |
| 140 |
DATA_DIRS.append(EXEDIR) |
| 141 |
SCRIPT_EXT = ".cmd" |
| 142 |
SCALE_ADJUSTMENT_FACTOR = 1.0 |
| 143 |
CONFIG_SYS = os.path.join(COMMONAPPDATA[0], APPBASENAME) |
| 144 |
CONFIG_HOME = os.path.join(APPDATA, APPBASENAME) |
| 145 |
LOGDIR = os.path.join(DATA_HOME, "logs") |
| 146 |
if APPBASENAME != APPNAME: |
| 147 |
DATA_DIRS.extend(os.path.join(dir_, APPNAME) for dir_ in COMMONAPPDATA) |
| 148 |
DATA_DIRS.append(os.path.join(COMMON_PROGRAM_FILES, APPNAME)) |
| 149 |
DATA_DIRS.append(DATA_HOME) |
| 150 |
DATA_DIRS.extend(os.path.join(dir_, APPBASENAME) for dir_ in COMMONAPPDATA) |
| 151 |
DATA_DIRS.append(os.path.join(COMMON_PROGRAM_FILES, APPBASENAME)) |
| 152 |
EXE_EXT = ".exe" |
| 153 |
PROFILE_EXT = ".icm" |
| 154 |
elif sys.platform == "darwin": |
| 155 |
SCRIPT_EXT = ".command" |
| 156 |
MAC_CREATE_APP = True |
| 157 |
SCALE_ADJUSTMENT_FACTOR = 1.0 |
| 158 |
CONFIG_SYS = os.path.join(PREFS, APPBASENAME) |
| 159 |
CONFIG_HOME = os.path.join(PREFS_HOME, APPBASENAME) |
| 160 |
LOGDIR = os.path.join(expanduseru("~"), "Library", "Logs", APPBASENAME) |
| 161 |
if APPBASENAME != APPNAME: |
| 162 |
DATA_DIRS.append(os.path.join(COMMONAPPDATA[0], APPNAME)) |
| 163 |
DATA_DIRS.append(DATA_HOME) |
| 164 |
DATA_DIRS.append(os.path.join(COMMONAPPDATA[0], APPBASENAME)) |
| 165 |
EXE_EXT = "" |
| 166 |
PROFILE_EXT = ".icc" |
| 167 |
else: # Linux |
| 168 |
SCRIPT_EXT = ".sh" |
| 169 |
SCALE_ADJUSTMENT_FACTOR = 1.0 |
| 170 |
CONFIG_SYS = os.path.join(XDG_CONFIG_DIR_DEFAULT, APPBASENAME) |
| 171 |
CONFIG_HOME = os.path.join(XDG_CONFIG_HOME, APPBASENAME) |
| 172 |
LOGDIR = os.path.join(DATA_HOME, "logs") |
| 173 |
if APPBASENAME != APPNAME: |
| 174 |
DATA_HOME_DEFAULT = os.path.join(XDG_DATA_HOME_DEFAULT, APPNAME) |
| 175 |
if DATA_HOME_DEFAULT not in DATA_DIRS: |
| 176 |
DATA_DIRS.append(DATA_HOME_DEFAULT) |
| 177 |
DATA_DIRS.extend(os.path.join(dir_, APPNAME) for dir_ in XDG_DATA_DIRS) |
| 178 |
DATA_DIRS.append(DATA_HOME) |
| 179 |
DATA_HOME_DEFAULT = os.path.join(XDG_DATA_HOME_DEFAULT, APPBASENAME) |
| 180 |
if DATA_HOME_DEFAULT not in DATA_DIRS: |
| 181 |
DATA_DIRS.append(DATA_HOME_DEFAULT) |
| 182 |
DATA_DIRS.extend(os.path.join(dir_, APPBASENAME) for dir_ in XDG_DATA_DIRS) |
| 183 |
EXTRA_DATA_DIRS.extend(os.path.join(dir_, "argyllcms") for dir_ in XDG_DATA_DIRS) |
| 184 |
EXTRA_DATA_DIRS.extend( |
| 185 |
os.path.join(dir_, "color", "argyll") for dir_ in XDG_DATA_DIRS |
| 186 |
) |
| 187 |
EXE_EXT = "" |
| 188 |
PROFILE_EXT = ".icc" |
| 189 |
|
| 190 |
STORAGE = os.path.join(DATA_HOME, "storage") |
| 191 |
|
| 192 |
RES_FILES = [ |
| 193 |
# Only essentials |
| 194 |
"lang/en.yaml", |
| 195 |
"beep.wav", |
| 196 |
"camera_shutter.wav", |
| 197 |
"linear.cal", |
| 198 |
"test.cal", |
| 199 |
"ref/ClayRGB1998.gam", |
| 200 |
"ref/sRGB.gam", |
| 201 |
"ref/verify_extended.ti1", |
| 202 |
"ti1/d3-e4-s2-g28-m0-b0-f0.ti1", |
| 203 |
"ti1/d3-e4-s3-g52-m3-b0-f0.ti1", |
| 204 |
"ti1/d3-e4-s4-g52-m4-b0-f0.ti1", |
| 205 |
"ti1/d3-e4-s5-g52-m5-b0-f0.ti1", |
| 206 |
"xrc/extra.xrc", |
| 207 |
"xrc/gamap.xrc", |
| 208 |
"xrc/main.xrc", |
| 209 |
"xrc/mainmenu.xrc", |
| 210 |
"xrc/report.xrc", |
| 211 |
"xrc/synthicc.xrc", |
| 212 |
] |
| 213 |
|
| 214 |
BITMAPS = {} |
| 215 |
|
| 216 |
# Does the device not support iterative calibration? |
| 217 |
UNCALIBRATABLE_DISPLAYS = ("Untethered$",) |
| 218 |
|
| 219 |
# Can the device generate patterns of its own? |
| 220 |
PATTERN_GENERATORS = ("madVR$", "Resolve$", "Chromecast ", "Prisma ", "Prisma$") |
| 221 |
|
| 222 |
NON_ARGYLL_DISPLAYS = (*UNCALIBRATABLE_DISPLAYS, "Resolve$") |
| 223 |
|
| 224 |
# Is the device directly connected or e.g. driven via network? |
| 225 |
# (note that madVR can technically be both, but the endpoint is always directly |
| 226 |
# connected to a display so we have videoLUT access via madVR's API. |
| 227 |
# Only devices which don't support that are considered 'untethered' in this context) |
| 228 |
UNTETHERED_DISPLAYS = ( |
| 229 |
*NON_ARGYLL_DISPLAYS, |
| 230 |
"Web$", |
| 231 |
"Chromecast ", |
| 232 |
"Prisma ", |
| 233 |
"Prisma$", |
| 234 |
) |
| 235 |
|
| 236 |
# Is the device not an actual display device (i.e. is it not a TV or monitor)? |
| 237 |
VIRTUAL_DISPLAYS = (*UNTETHERED_DISPLAYS, "madVR$") |
| 238 |
|
| 239 |
DPISET = False |
| 240 |
|
| 241 |
|
| 242 |
class BitmapSizeType(IntEnum): |
| 243 |
"""Enum for bitmap size types.""" |
| 244 |
|
| 245 |
HighDPI_Normal = 0 |
| 246 |
HighDPI_4x = 1 |
| 247 |
HighDPI_2x = 2 |
| 248 |
HighDPI_2x_Original = 3 |
| 249 |
Original = 4 |
| 250 |
|
| 251 |
def __repr__(self) -> str: |
| 252 |
"""Return the enum name for str(). |
| 253 |
|
| 254 |
Returns: |
| 255 |
str: The name as the string representation of this |
| 256 |
ScheduleConstraint. |
| 257 |
""" |
| 258 |
return self.name if self.name != "NONE" else "None" |
| 259 |
|
| 260 |
__str__ = __repr__ |
| 261 |
|
| 262 |
@classmethod |
| 263 |
def to_type(cls, type_: int | str | BitmapSizeType) -> BitmapSizeType: |
| 264 |
"""Convert the given type value to a BitmapSizeType enum. |
| 265 |
|
| 266 |
Args: |
| 267 |
type_ (int | str | BitmapSizeType]): The value to convert to a |
| 268 |
BitmapSizeType to. |
| 269 |
|
| 270 |
Raises: |
| 271 |
TypeError: Input value type is invalid. |
| 272 |
ValueError: Input value is invalid. |
| 273 |
|
| 274 |
Returns: |
| 275 |
BitmapSizeType: The enum. |
| 276 |
""" |
| 277 |
acceptable_type_values = [t.name for t in cls] + [t.value for t in cls] |
| 278 |
if not isinstance(type_, (int, str, BitmapSizeType)): |
| 279 |
raise TypeError( |
| 280 |
"type_ should be a BitmapSizeType enum value or one of " |
| 281 |
f"{acceptable_type_values}, not {type_.__class__.__name__}: '{type_}'" |
| 282 |
) |
| 283 |
if isinstance(type_, str): |
| 284 |
type_name_lut = {t.name.lower(): t.name for t in cls} |
| 285 |
type_name_lut.update({t.value: t.name for t in cls}) |
| 286 |
type_lower_case = type_.lower() |
| 287 |
if type_lower_case not in type_name_lut: |
| 288 |
raise ValueError( |
| 289 |
"type_ should be a BitmapSizeType enum value or one of " |
| 290 |
f"{acceptable_type_values}, not '{type_}'" |
| 291 |
) |
| 292 |
|
| 293 |
return cls.__members__[type_name_lut[type_lower_case]] |
| 294 |
|
| 295 |
return type_ |
| 296 |
|
| 297 |
|
| 298 |
def debug_print(*args: Any, **kwargs: Any) -> None: # noqa: ANN401 |
| 299 |
"""Print debug messages if DEBUG is enabled.""" |
| 300 |
if DEBUG: |
| 301 |
print(*args, **kwargs) |
| 302 |
|
| 303 |
|
| 304 |
def is_special_display( |
| 305 |
display: None | str = None, tests: list[str] = VIRTUAL_DISPLAYS |
| 306 |
) -> bool: |
| 307 |
"""Check if the display is a special display. |
| 308 |
|
| 309 |
Args: |
| 310 |
display (str): The display name. |
| 311 |
tests (list): List of special display patterns. |
| 312 |
|
| 313 |
Returns: |
| 314 |
bool: True if the display is special, False otherwise. |
| 315 |
""" |
| 316 |
if not isinstance(display, str): |
| 317 |
display = get_display_name(display) |
| 318 |
return any(re.match(test, display) for test in tests) |
| 319 |
|
| 320 |
|
| 321 |
def is_uncalibratable_display(display: None | str = None) -> bool: |
| 322 |
"""Check if the display is uncalibratable. |
| 323 |
|
| 324 |
Args: |
| 325 |
display (None | str): The display name. |
| 326 |
|
| 327 |
Returns: |
| 328 |
bool: True if the display is uncalibratable, False otherwise. |
| 329 |
""" |
| 330 |
return is_special_display(display, UNCALIBRATABLE_DISPLAYS) |
| 331 |
|
| 332 |
|
| 333 |
def is_patterngenerator(display: None | str = None) -> bool: |
| 334 |
"""Check if the display is a pattern generator. |
| 335 |
|
| 336 |
Args: |
| 337 |
display (None | str): The display name. |
| 338 |
|
| 339 |
Returns: |
| 340 |
bool: True if the display is a pattern generator, False otherwise. |
| 341 |
""" |
| 342 |
return is_special_display(display, PATTERN_GENERATORS) |
| 343 |
|
| 344 |
|
| 345 |
def is_non_argyll_display(display: None | str = None) -> bool: |
| 346 |
"""Check if the display is a non-Argyll display. |
| 347 |
|
| 348 |
Args: |
| 349 |
display (None | str): The display name. |
| 350 |
|
| 351 |
Returns: |
| 352 |
bool: True if the display is a non-Argyll display, False otherwise. |
| 353 |
""" |
| 354 |
return is_special_display(display, NON_ARGYLL_DISPLAYS) |
| 355 |
|
| 356 |
|
| 357 |
def is_untethered_display(display: None | str = None) -> bool: |
| 358 |
"""Check if the display is untethered. |
| 359 |
|
| 360 |
Args: |
| 361 |
display (None | str): The display name. |
| 362 |
|
| 363 |
Returns: |
| 364 |
bool: True if the display is untethered, False otherwise. |
| 365 |
""" |
| 366 |
return is_special_display(display, UNTETHERED_DISPLAYS) |
| 367 |
|
| 368 |
|
| 369 |
def is_virtual_display(display: None | str = None) -> bool: |
| 370 |
"""Check if the display is virtual. |
| 371 |
|
| 372 |
Args: |
| 373 |
display (None | str): The display name. |
| 374 |
|
| 375 |
Returns: |
| 376 |
bool: True if the display is virtual, False otherwise. |
| 377 |
""" |
| 378 |
return is_special_display(display, VIRTUAL_DISPLAYS) |
| 379 |
|
| 380 |
|
| 381 |
def check_3dlut_format(devicename: str) -> bool: |
| 382 |
"""Check the 3D LUT format for the given device. |
| 383 |
|
| 384 |
Args: |
| 385 |
devicename (str): The name of the device. |
| 386 |
|
| 387 |
Returns: |
| 388 |
bool: True if the 3D LUT format is correct, False otherwise. |
| 389 |
""" |
| 390 |
if get_display_name(None, True) == devicename and devicename == "Prisma": |
| 391 |
return ( |
| 392 |
getcfg("3dlut.format") == "3dl" |
| 393 |
and getcfg("3dlut.size") == 17 |
| 394 |
and getcfg("3dlut.bitdepth.input") == 10 |
| 395 |
and getcfg("3dlut.bitdepth.output") == 12 |
| 396 |
) |
| 397 |
return False |
| 398 |
|
| 399 |
|
| 400 |
def get_bitmap( |
| 401 |
name: str, |
| 402 |
display_missing_icon: bool = True, |
| 403 |
scale: bool = True, |
| 404 |
use_mask: bool = False, |
| 405 |
) -> wx.Bitmap: |
| 406 |
"""Create (if necessary) and return a named bitmap. |
| 407 |
|
| 408 |
Args: |
| 409 |
name (str): Has to be a relative path to a png file, omitting the extension, |
| 410 |
e.g. 'theme/mybitmap' or 'theme/icons/16x16/myicon', which is searched |
| 411 |
for in the data directories. If a matching file is not found, a |
| 412 |
placeholder bitmap is returned. The special name 'empty' will always |
| 413 |
return a transparent bitmap of the given size, e.g. '16x16/empty' |
| 414 |
or just 'empty' (size defaults to 16x16 if not given). |
| 415 |
display_missing_icon (bool): Whether to display a missing icon if the bitmap. |
| 416 |
scale (bool): Whether to scale the bitmap. |
| 417 |
use_mask (bool): Whether to use a mask for the bitmap. |
| 418 |
|
| 419 |
Returns: |
| 420 |
wx.Bitmap: The bitmap. |
| 421 |
""" |
| 422 |
if name not in BITMAPS: |
| 423 |
BITMAPS[name] = create_bitmap(name, display_missing_icon, scale, use_mask) |
| 424 |
return BITMAPS[name] |
| 425 |
|
| 426 |
|
| 427 |
def create_bitmap( |
| 428 |
name: str, display_missing_icon: bool, scale: bool, use_mask: bool |
| 429 |
) -> wx.Bitmap: |
| 430 |
"""Create a bitmap with the specified name and dimensions. |
| 431 |
|
| 432 |
Args: |
| 433 |
name (str): The name of the bitmap. |
| 434 |
display_missing_icon (bool): Whether to display a missing icon if the |
| 435 |
bitmap is not found. |
| 436 |
scale (bool): Whether to scale the bitmap. |
| 437 |
use_mask (bool): Whether to use a mask for the bitmap. |
| 438 |
|
| 439 |
Returns: |
| 440 |
wx.Bitmap: The created bitmap. |
| 441 |
""" |
| 442 |
parts = name.split("/") |
| 443 |
width = 16 |
| 444 |
height = 16 |
| 445 |
size = [] |
| 446 |
if len(parts) > 1: |
| 447 |
size = parts[-2].split("x") |
| 448 |
if len(size) == 2: |
| 449 |
try: |
| 450 |
width, height = list(map(int, size)) |
| 451 |
except ValueError: |
| 452 |
size = [] |
| 453 |
orig_width, orig_height = width, height |
| 454 |
set_default_app_dpi() |
| 455 |
scale = getcfg("app.dpi") / get_default_dpi() if scale else 1 |
| 456 |
if scale > 1: |
| 457 |
# HighDPI support |
| 458 |
width = round(width * scale) |
| 459 |
height = round(height * scale) |
| 460 |
if parts[-1] == "empty": |
| 461 |
return create_empty_bitmap(width, height, use_mask) |
| 462 |
return load_bitmap( |
| 463 |
name, |
| 464 |
parts, |
| 465 |
orig_width, |
| 466 |
orig_height, |
| 467 |
width, |
| 468 |
height, |
| 469 |
scale, |
| 470 |
display_missing_icon, |
| 471 |
) |
| 472 |
|
| 473 |
|
| 474 |
def create_empty_bitmap(w: int, h: int, use_mask: bool) -> wx.Bitmap: |
| 475 |
"""Create an empty bitmap with the specified dimensions. |
| 476 |
|
| 477 |
Args: |
| 478 |
w (int): Width of the bitmap. |
| 479 |
h (int): Height of the bitmap. |
| 480 |
use_mask (bool): Whether to use a mask for the bitmap. |
| 481 |
|
| 482 |
Returns: |
| 483 |
wx.Bitmap: The created empty bitmap. |
| 484 |
""" |
| 485 |
from DisplayCAL.wx_addons import wx |
| 486 |
|
| 487 |
if wx.VERSION[0] < 3: |
| 488 |
use_mask = True |
| 489 |
if use_mask and sys.platform == "win32": |
| 490 |
bmp = wx.EmptyBitmap(w, h) |
| 491 |
bmp.SetMaskColour(wx.Colour(0, 0, 0)) |
| 492 |
else: |
| 493 |
bmp = wx.EmptyBitmapRGBA(w, h, 255, 0, 255, 0) |
| 494 |
return bmp |
| 495 |
|
| 496 |
|
| 497 |
def load_bitmap( |
| 498 |
name: str, |
| 499 |
parts: list[str], |
| 500 |
orig_width: int, |
| 501 |
orig_height: int, |
| 502 |
width: int, |
| 503 |
height: int, |
| 504 |
scale: float, |
| 505 |
display_missing_icon: bool = True, |
| 506 |
) -> wx.Bitmap: |
| 507 |
"""Load a bitmap from the specified parts and dimensions. |
| 508 |
|
| 509 |
Args: |
| 510 |
name (str): The name of the bitmap. |
| 511 |
parts (list): A list of parts representing the path to the bitmap. |
| 512 |
orig_width (int): Original width of the bitmap. |
| 513 |
orig_height (int): Original height of the bitmap. |
| 514 |
width (int): New width of the bitmap. |
| 515 |
height (int): New height of the bitmap. |
| 516 |
scale (float): Scale factor for the bitmap. |
| 517 |
display_missing_icon (bool): Whether to display a missing icon if the |
| 518 |
bitmap is not found. |
| 519 |
|
| 520 |
Returns: |
| 521 |
wx.Bitmap: The loaded bitmap. |
| 522 |
""" |
| 523 |
from DisplayCAL.wx_addons import wx |
| 524 |
|
| 525 |
bmp = None |
| 526 |
width, height, orig_name, name2x, name4x, color, inverted, size = ( |
| 527 |
extract_image_properties(parts) |
| 528 |
) |
| 529 |
|
| 530 |
path, bitmap_size_type = get_scaled_image_path( |
| 531 |
parts, |
| 532 |
orig_name, |
| 533 |
orig_width, |
| 534 |
orig_height, |
| 535 |
width, |
| 536 |
height, |
| 537 |
scale, |
| 538 |
name2x, |
| 539 |
name4x, |
| 540 |
size, |
| 541 |
) |
| 542 |
if path: |
| 543 |
bmp = wx.Bitmap(path) |
| 544 |
if not bmp.IsOk(): |
| 545 |
path = None |
| 546 |
if path: |
| 547 |
width, height, path, bmp = resize_and_adjust_bitmap( |
| 548 |
path, |
| 549 |
parts, |
| 550 |
orig_name, |
| 551 |
orig_width, |
| 552 |
orig_height, |
| 553 |
scale, |
| 554 |
color, |
| 555 |
inverted, |
| 556 |
size, |
| 557 |
bitmap_size_type, |
| 558 |
bmp, |
| 559 |
) |
| 560 |
if not path: |
| 561 |
print(f"Warning: Missing bitmap '{name}'") |
| 562 |
img = wx.Image(width, height) |
| 563 |
img.SetMaskColour(0, 0, 0) |
| 564 |
img.InitAlpha() |
| 565 |
bmp = img.ConvertToBitmap() |
| 566 |
dc = wx.MemoryDC() |
| 567 |
dc.SelectObject(bmp) |
| 568 |
if display_missing_icon: |
| 569 |
art = wx.ArtProvider.GetBitmap(wx.ART_MISSING_IMAGE, size=(width, height)) |
| 570 |
dc.DrawBitmap(art, 0, 0, True) |
| 571 |
dc.SelectObject(wx.NullBitmap) |
| 572 |
return bmp |
| 573 |
|
| 574 |
|
| 575 |
def extract_image_properties( |
| 576 |
parts: list[str], |
| 577 |
) -> tuple[int, int, str, str, str, bool, list[str]]: |
| 578 |
"""Extract image properties from the parts list. |
| 579 |
|
| 580 |
Args: |
| 581 |
parts (list): A list of parts representing the path to the bitmap. |
| 582 |
|
| 583 |
Returns: |
| 584 |
tuple[int, int, str, str, bool, list]: A tuple containing width, |
| 585 |
height, original name, color, inverted flag, and size. |
| 586 |
""" |
| 587 |
width = None |
| 588 |
height = None |
| 589 |
if parts[-1].startswith(APPNAME): |
| 590 |
parts[-1] = parts[-1].lower() |
| 591 |
orig_name = parts[-1] |
| 592 |
if "#" in orig_name: |
| 593 |
# Hex format, RRGGBB or RRGGBBAA |
| 594 |
orig_name, color = orig_name.split("#", 1) |
| 595 |
parts[-1] = orig_name |
| 596 |
else: |
| 597 |
color = None |
| 598 |
if inverted := orig_name.endswith("-inverted"): |
| 599 |
orig_name = parts[-1] = orig_name.split("-inverted")[0] |
| 600 |
size = [] |
| 601 |
if len(parts) > 1: |
| 602 |
size = parts[-2].split("x") |
| 603 |
if len(size) == 2: |
| 604 |
try: |
| 605 |
width, height = list(map(int, size)) |
| 606 |
except ValueError: |
| 607 |
size = [] |
| 608 |
name2x = f"{orig_name}@2x" |
| 609 |
name4x = f"{orig_name}@4x" |
| 610 |
|
| 611 |
return width, height, orig_name, name2x, name4x, color, inverted, size |
| 612 |
|
| 613 |
|
| 614 |
def get_non_scaled_image_path(parts: list[str]) -> tuple[str | None, BitmapSizeType]: |
| 615 |
"""Get the path for a non-scaled image. |
| 616 |
|
| 617 |
Args: |
| 618 |
parts (list): A list of parts representing the path to the bitmap. |
| 619 |
|
| 620 |
Returns: |
| 621 |
tuple[str | None, BitmapSizeType]: A tuple containing the path to the |
| 622 |
bitmap and the BitmapSizeType. |
| 623 |
""" |
| 624 |
path = None |
| 625 |
if sys.platform not in ("darwin", "win32") and parts[-1].startswith( |
| 626 |
APPNAME.lower() |
| 627 |
): |
| 628 |
# Search /usr/share/icons on Linux first |
| 629 |
path = get_data_path( |
| 630 |
"{}.png".format(os.path.join(parts[-2], "apps", parts[-1])) |
| 631 |
) |
| 632 |
if not path: |
| 633 |
path = get_data_path(f"{os.path.sep.join(parts)}.png") |
| 634 |
return path, BitmapSizeType.Original |
| 635 |
|
| 636 |
|
| 637 |
def get_scaled_image_path( |
| 638 |
parts: list[str], |
| 639 |
orig_name: str, |
| 640 |
orig_width: int, |
| 641 |
orig_height: int, |
| 642 |
width: int, |
| 643 |
height: int, |
| 644 |
scale: float, |
| 645 |
name2x: str, |
| 646 |
name4x: str, |
| 647 |
size: list[str], |
| 648 |
) -> tuple[None | str, BitmapSizeType]: |
| 649 |
"""Get the path for a scaled image. |
| 650 |
|
| 651 |
Args: |
| 652 |
parts (list[str]): A list of parts representing the path to the bitmap. |
| 653 |
orig_name (str): Original name of the bitmap. |
| 654 |
orig_width (int): Original width of the bitmap. |
| 655 |
orig_height (int): Original height of the bitmap. |
| 656 |
width (int): New width of the bitmap. |
| 657 |
height (int): New height of the bitmap. |
| 658 |
scale (float): Scale factor for the bitmap. |
| 659 |
name2x (str): Name for the 2x scaled version. |
| 660 |
name4x (str): Name for the 4x scaled version. |
| 661 |
size (list[str]): Size information from parts. |
| 662 |
|
| 663 |
Returns: |
| 664 |
tuple[None | str, BitmapSizeType]: A tuple containing the path to the |
| 665 |
bitmap and the BitmapSizeType. |
| 666 |
""" |
| 667 |
path = None |
| 668 |
bitmap_size_type = BitmapSizeType.Original |
| 669 |
|
| 670 |
if scale == 1: |
| 671 |
return get_non_scaled_image_path(parts) |
| 672 |
|
| 673 |
for i in range(5): |
| 674 |
bitmap_size_type = BitmapSizeType.to_type(i) |
| 675 |
if len(size) == 2: |
| 676 |
result = get_scaled_icon_path( |
| 677 |
parts, |
| 678 |
orig_name, |
| 679 |
orig_width, |
| 680 |
orig_height, |
| 681 |
width, |
| 682 |
height, |
| 683 |
scale, |
| 684 |
name2x, |
| 685 |
name4x, |
| 686 |
bitmap_size_type, |
| 687 |
) |
| 688 |
if not result: |
| 689 |
continue |
| 690 |
else: |
| 691 |
result = get_scaled_theme_path( |
| 692 |
parts, |
| 693 |
orig_name, |
| 694 |
scale, |
| 695 |
name2x, |
| 696 |
name4x, |
| 697 |
bitmap_size_type, |
| 698 |
) |
| 699 |
if not result: |
| 700 |
continue |
| 701 |
if sys.platform not in ("darwin", "win32") and parts[-1].startswith( |
| 702 |
APPNAME.lower() |
| 703 |
): |
| 704 |
# Search /usr/share/icons on Linux first |
| 705 |
path = get_data_path( |
| 706 |
"{}.png".format(os.path.join(parts[-2], "apps", parts[-1])) |
| 707 |
) |
| 708 |
if not path: |
| 709 |
path = get_data_path(f"{os.path.sep.join(parts)}.png") |
| 710 |
if path: |
| 711 |
break |
| 712 |
return path, bitmap_size_type |
| 713 |
|
| 714 |
|
| 715 |
def get_scaled_icon_path( |
| 716 |
parts: list[str], |
| 717 |
orig_name: str, |
| 718 |
orig_width: int, |
| 719 |
orig_height: int, |
| 720 |
width: int, |
| 721 |
height: int, |
| 722 |
scale: float, |
| 723 |
name2x: str, |
| 724 |
name4x: str, |
| 725 |
bitmap_size_type: BitmapSizeType, |
| 726 |
) -> bool: |
| 727 |
"""Get the path for a scaled icon. |
| 728 |
|
| 729 |
Args: |
| 730 |
parts (list): A list of parts representing the path to the bitmap. |
| 731 |
orig_name (str): Original name of the bitmap. |
| 732 |
orig_width (int): Original width of the bitmap. |
| 733 |
orig_height (int): Original height of the bitmap. |
| 734 |
width (int): New width of the bitmap. |
| 735 |
height (int): New height of the bitmap. |
| 736 |
scale (float): Scale factor for the bitmap. |
| 737 |
name2x (str): Name for the 2x scaled version. |
| 738 |
name4x (str): Name for the 4x scaled version. |
| 739 |
bitmap_size_type (BitmapSizeType): The bitmap size type. |
| 740 |
|
| 741 |
Returns: |
| 742 |
bool: True if the path was successfully set, False otherwise. |
| 743 |
""" |
| 744 |
# Icon |
| 745 |
if bitmap_size_type == BitmapSizeType.HighDPI_Normal: |
| 746 |
# HighDPI support. Try scaled size |
| 747 |
parts[-2] = f"{width:d}x{height:d}" |
| 748 |
elif bitmap_size_type == BitmapSizeType.HighDPI_4x: |
| 749 |
if scale < 1.75 or scale == 2: |
| 750 |
return False |
| 751 |
# HighDPI support. Try @4x version |
| 752 |
parts[-2] = f"{orig_width:d}x{orig_height:d}" |
| 753 |
parts[-1] = name4x |
| 754 |
elif bitmap_size_type == BitmapSizeType.HighDPI_2x: |
| 755 |
# HighDPI support. Try @2x version |
| 756 |
parts[-2] = f"{orig_width:d}x{orig_height:d}" |
| 757 |
parts[-1] = name2x |
| 758 |
elif bitmap_size_type == BitmapSizeType.HighDPI_2x_Original: |
| 759 |
# HighDPI support. Try original size times two |
| 760 |
parts[-2] = f"{orig_width * 2:d}x{orig_height * 2: d}" |
| 761 |
parts[-1] = orig_name |
| 762 |
else: |
| 763 |
# Try original size |
| 764 |
parts[-2] = f"{orig_width:d}x{orig_height:d}" |
| 765 |
return True |
| 766 |
|
| 767 |
|
| 768 |
def get_scaled_theme_path( |
| 769 |
parts: list[str], |
| 770 |
orig_name: str, |
| 771 |
scale: float, |
| 772 |
name2x: str, |
| 773 |
name4x: str, |
| 774 |
bitmap_size_type: BitmapSizeType, |
| 775 |
) -> bool: |
| 776 |
"""Get the path for a scaled theme image. |
| 777 |
|
| 778 |
Args: |
| 779 |
parts (list): A list of parts representing the path to the bitmap. |
| 780 |
orig_name (str): Original name of the bitmap. |
| 781 |
scale (float): Scale factor for the bitmap. |
| 782 |
name2x (str): Name for the 2x scaled version. |
| 783 |
name4x (str): Name for the 4x scaled version. |
| 784 |
bitmap_size_type (BitmapSizeType): The bitmap size type. |
| 785 |
|
| 786 |
Returns: |
| 787 |
bool: True if the path was successfully set, False otherwise. |
| 788 |
""" |
| 789 |
# Theme graphic |
| 790 |
if bitmap_size_type in ( |
| 791 |
BitmapSizeType.HighDPI_Normal, |
| 792 |
BitmapSizeType.HighDPI_2x_Original, |
| 793 |
): |
| 794 |
return False |
| 795 |
if bitmap_size_type == BitmapSizeType.HighDPI_4x: |
| 796 |
if scale < 1.75 or scale == 2: |
| 797 |
return False |
| 798 |
# HighDPI support. Try @4x version |
| 799 |
parts[-1] = name4x |
| 800 |
elif bitmap_size_type == BitmapSizeType.HighDPI_2x: |
| 801 |
# HighDPI support. Try @2x version |
| 802 |
parts[-1] = name2x |
| 803 |
else: |
| 804 |
# Try original size |
| 805 |
parts[-1] = orig_name |
| 806 |
return True |
| 807 |
|
| 808 |
|
| 809 |
def resize_and_adjust_bitmap( |
| 810 |
path: str, |
| 811 |
parts: list[str], |
| 812 |
orig_name: str, |
| 813 |
orig_width: int, |
| 814 |
orig_height: int, |
| 815 |
scale: float, |
| 816 |
color: None | str, |
| 817 |
inverted: bool, |
| 818 |
size: list[str], |
| 819 |
bitmap_size_type: BitmapSizeType, |
| 820 |
bmp: wx.Bitmap, |
| 821 |
) -> tuple[int, int, None | str]: |
| 822 |
"""Resize and adjust the bitmap based on the given parameters. |
| 823 |
|
| 824 |
Args: |
| 825 |
path (str): The path to the bitmap. |
| 826 |
parts (list): A list of parts representing the path to the bitmap. |
| 827 |
orig_name (str): Original name of the bitmap. |
| 828 |
orig_width (int): Original width of the bitmap. |
| 829 |
orig_height (int): Original height of the bitmap. |
| 830 |
scale (float): Scale factor for the bitmap. |
| 831 |
color (None | str): Color in hex format, RRGGBB or RRGGBBAA. |
| 832 |
inverted (bool): Whether the bitmap should be inverted. |
| 833 |
size (list): Size information from parts. |
| 834 |
bitmap_size_type (BitmapSizeType): The bitmap size type. |
| 835 |
bmp (wx.Bitmap): The original bitmap. |
| 836 |
|
| 837 |
Returns: |
| 838 |
tuple[int, int, None | str]: A tuple containing the width, height, |
| 839 |
and path to the bitmap. |
| 840 |
""" |
| 841 |
from DisplayCAL.wx_addons import wx |
| 842 |
|
| 843 |
img = None |
| 844 |
img, width, height = adjust_bitmap_size( |
| 845 |
scale, orig_name, size, bitmap_size_type, bmp |
| 846 |
) |
| 847 |
if ( |
| 848 |
not inverted |
| 849 |
and len(parts) > 2 |
| 850 |
and parts[-3] == "icons" |
| 851 |
and (orig_width, orig_height) != (10, 10) |
| 852 |
and orig_name not in ("black_luminance", "check_all", "contrast", "luminance") |
| 853 |
and max(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)[:3]) < 102 |
| 854 |
): |
| 855 |
# Automatically invert B&W image if background is dark (exceptions do apply) |
| 856 |
if not img: |
| 857 |
img = bmp.ConvertToImage() |
| 858 |
if img.IsBW(): |
| 859 |
inverted = True |
| 860 |
# Invert after resize (avoids jaggies) |
| 861 |
if inverted or color: |
| 862 |
img = configure_image_channels(orig_name, color, inverted, bmp, img) |
| 863 |
if img: |
| 864 |
bmp = img.ConvertToBitmap() |
| 865 |
if not bmp.IsOk(): |
| 866 |
path = None |
| 867 |
return width, height, path, bmp |
| 868 |
|
| 869 |
|
| 870 |
def adjust_bitmap_size( |
| 871 |
scale: float, |
| 872 |
orig_name: str, |
| 873 |
size: list[str], |
| 874 |
bitmap_size_type: BitmapSizeType, |
| 875 |
bmp: wx.Bitmap, |
| 876 |
) -> tuple[None | wx.Image, None | int, None | int]: |
| 877 |
"""Adjust the bitmap size based on the scale and bitmap size type. |
| 878 |
|
| 879 |
Args: |
| 880 |
scale (float): Scale factor for the bitmap. |
| 881 |
orig_name (str): Original name of the bitmap. |
| 882 |
size (list[str]): Size information from parts. |
| 883 |
bitmap_size_type (BitmapSizeType): The bitmap size type. |
| 884 |
bmp (wx.Bitmap): The original bitmap. |
| 885 |
|
| 886 |
Returns: |
| 887 |
tuple[None | wx.Image, None | int, None | int]: A tuple containing |
| 888 |
the image, width, and height of the bitmap. |
| 889 |
""" |
| 890 |
img = None |
| 891 |
w = None |
| 892 |
h = None |
| 893 |
if scale == 1 or bitmap_size_type == BitmapSizeType.HighDPI_Normal: |
| 894 |
return img, w, h |
| 895 |
rescale = False |
| 896 |
if bitmap_size_type in (BitmapSizeType.HighDPI_4x, BitmapSizeType.HighDPI_2x): |
| 897 |
# HighDPI support. 4x/2x version, determine scaled size |
| 898 |
w, h = [round(v / (2 * (3 - bitmap_size_type)) * scale) for v in bmp.Size] |
| 899 |
rescale = True |
| 900 |
elif len(size) == 2: |
| 901 |
# HighDPI support. Icon |
| 902 |
rescale = True |
| 903 |
if rescale and (bmp.Size[0] != w or bmp.Size[1] != h): |
| 904 |
from DisplayCAL.wx_addons import wx |
| 905 |
|
| 906 |
# HighDPI support. Rescale |
| 907 |
img = bmp.ConvertToImage() |
| 908 |
if not hasattr(wx, "IMAGE_QUALITY_BILINEAR") or orig_name == "list-add": |
| 909 |
# In case bilinear is not supported, |
| 910 |
# and to prevent black borders after resizing for some images |
| 911 |
quality = wx.IMAGE_QUALITY_NORMAL |
| 912 |
elif orig_name in (): |
| 913 |
# Hmm. Everything else looks great with bicubic, |
| 914 |
# but this one gets jaggy unless we use bilinear |
| 915 |
quality = wx.IMAGE_QUALITY_BILINEAR |
| 916 |
elif scale < 1.5 or bitmap_size_type == BitmapSizeType.HighDPI_4x: |
| 917 |
quality = wx.IMAGE_QUALITY_BICUBIC |
| 918 |
else: |
| 919 |
quality = wx.IMAGE_QUALITY_BILINEAR |
| 920 |
img.Rescale(w, h, quality=quality) |
| 921 |
return img, w, h |
| 922 |
|
| 923 |
|
| 924 |
def configure_image_channels( |
| 925 |
orig_name: str, |
| 926 |
color: None | str, |
| 927 |
inverted: bool, |
| 928 |
bmp: None | wx.Image, |
| 929 |
img: None | wx.Image, |
| 930 |
) -> wx.Image: |
| 931 |
"""Configure image channels based on the given parameters. |
| 932 |
|
| 933 |
Args: |
| 934 |
orig_name (str): The original name of the bitmap. |
| 935 |
color (None | str): Color in hex format, RRGGBB or RRGGBBAA. |
| 936 |
inverted (bool): Whether the bitmap should be inverted. |
| 937 |
bmp (wx.Bitmap): The original bitmap. |
| 938 |
img (wx.Image | None): The image to adjust. |
| 939 |
|
| 940 |
Returns: |
| 941 |
wx.Image: The adjusted image. |
| 942 |
""" |
| 943 |
from DisplayCAL.wx_addons import wx |
| 944 |
|
| 945 |
factors = None |
| 946 |
if not img: |
| 947 |
img = bmp.ConvertToImage() |
| 948 |
alpha = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT).alpha |
| 949 |
if orig_name in [ |
| 950 |
"applications-system", |
| 951 |
"color", |
| 952 |
"document-open", |
| 953 |
"document-save-as", |
| 954 |
"edit-delete", |
| 955 |
"image-x-generic", |
| 956 |
"info", |
| 957 |
"install", |
| 958 |
"list-add", |
| 959 |
"package-x-generic", |
| 960 |
"question", |
| 961 |
"rgbsquares", |
| 962 |
"stock_3d-color-picker", |
| 963 |
"stock_lock", |
| 964 |
"stock_lock-open", |
| 965 |
"stock_refresh", |
| 966 |
"web", |
| 967 |
"window-center", |
| 968 |
"zoom-best-fit", |
| 969 |
"zoom-in", |
| 970 |
"zoom-original", |
| 971 |
"zoom-out", |
| 972 |
]: |
| 973 |
# Scale 85 to 255 and adjust alpha |
| 974 |
factors = (3, 3, 3, alpha / 255.0) |
| 975 |
else: |
| 976 |
if inverted: |
| 977 |
img.Invert() |
| 978 |
if alpha != 255: |
| 979 |
# Only adjust alpha |
| 980 |
factors = (1, 1, 1, alpha / 255.0) |
| 981 |
if factors: |
| 982 |
r, g, b = factors[:3] |
| 983 |
alpha = factors[3] if len(factors) > 3 else 1.0 |
| 984 |
img = img.AdjustChannels(r, g, b, alpha) |
| 985 |
if color: |
| 986 |
# Hex format, RRGGBB or RRGGBBAA |
| 987 |
r = int(color[0:2], 16) / 255.0 |
| 988 |
g = int(color[2:4], 16) / 255.0 |
| 989 |
b = int(color[4:6], 16) / 255.0 |
| 990 |
alpha = int(color[6:8], 16) / 255.0 if len(color) > 6 else 1.0 |
| 991 |
img = img.AdjustChannels(r, g, b, alpha) |
| 992 |
return img |
| 993 |
|
| 994 |
|
| 995 |
def get_bitmap_as_icon(size: int, name: str, scale: bool = True) -> wx.Icon: |
| 996 |
"""Return a wx.Icon instance. |
| 997 |
|
| 998 |
This is like get_icon(), but returns a wx.Icon instance instead of a |
| 999 |
wx.Bitmap instance. |
| 1000 |
|
| 1001 |
Get a bitmap as an icon with the specified size and name. |
| 1002 |
|
| 1003 |
Args: |
| 1004 |
size (int): The size of the icon. |
| 1005 |
name (str): The name of the icon. |
| 1006 |
scale (bool): Whether to scale the icon. |
| 1007 |
|
| 1008 |
Returns: |
| 1009 |
wx.Icon: The (created) icon (instance). |
| 1010 |
""" |
| 1011 |
from DisplayCAL.wx_addons import wx |
| 1012 |
|
| 1013 |
icon = wx.EmptyIcon() |
| 1014 |
if sys.platform == "darwin" and wx.VERSION >= (2, 9) and size > 128: |
| 1015 |
# FIXME: wxMac 2.9 doesn't support icon sizes above 128 |
| 1016 |
size = 128 |
| 1017 |
bmp = get_icon(size, name, scale) |
| 1018 |
icon.CopyFromBitmap(bmp) |
| 1019 |
return icon |
| 1020 |
|
| 1021 |
|
| 1022 |
def get_argyll_data_dir() -> str: |
| 1023 |
"""Return ArgyllCMS data dir. |
| 1024 |
|
| 1025 |
Returns: |
| 1026 |
str: The ArgyllCMS data dir. |
| 1027 |
""" |
| 1028 |
argyll_version = getcfg("argyll.version") |
| 1029 |
if isinstance(argyll_version, str): |
| 1030 |
argyll_version = list(map(int, argyll_version.split("."))) |
| 1031 |
|
| 1032 |
argyll_data_dirname = "color" if argyll_version < [1, 5, 0] else "ArgyllCMS" |
| 1033 |
|
| 1034 |
if sys.platform == "darwin" and argyll_version < [1, 5, 0]: |
| 1035 |
return os.path.join( |
| 1036 |
LIBRARY if is_superuser() else LIBRARY_HOME, argyll_data_dirname |
| 1037 |
) |
| 1038 |
return os.path.join( |
| 1039 |
COMMONAPPDATA[0] if is_superuser() else APPDATA, argyll_data_dirname |
| 1040 |
) |
| 1041 |
|
| 1042 |
|
| 1043 |
def get_display_name( |
| 1044 |
disp_index: None | int = None, include_geometry: bool = False |
| 1045 |
) -> str: |
| 1046 |
"""Return name of currently configured display. |
| 1047 |
|
| 1048 |
Args: |
| 1049 |
disp_index (None | int): The index of the display. |
| 1050 |
include_geometry (bool): Whether to include geometry in the display name. |
| 1051 |
|
| 1052 |
Returns: |
| 1053 |
str: The name of the display. |
| 1054 |
""" |
| 1055 |
if disp_index is None: |
| 1056 |
disp_index = getcfg("display.number") - 1 |
| 1057 |
displays = getcfg("displays") |
| 1058 |
if 0 <= disp_index < len(displays): |
| 1059 |
return ( |
| 1060 |
displays[disp_index] |
| 1061 |
if include_geometry |
| 1062 |
else split_display_name(displays[disp_index]) |
| 1063 |
) |
| 1064 |
return "" |
| 1065 |
|
| 1066 |
|
| 1067 |
def split_display_name(display: str) -> str: |
| 1068 |
"""Split and return name part of display. |
| 1069 |
|
| 1070 |
Args: |
| 1071 |
display (str): The display name. |
| 1072 |
|
| 1073 |
Returns: |
| 1074 |
str: The name part of the display. |
| 1075 |
|
| 1076 |
E.g. |
| 1077 |
'LCD2690WUXi @ 0, 0, 1920x1200' -> 'LCD2690WUXi' |
| 1078 |
'madVR' -> 'madVR' |
| 1079 |
""" |
| 1080 |
if "@" in display and not display.startswith("Chromecast "): |
| 1081 |
display = "@".join(display.split("@")[:-1]) |
| 1082 |
return display.strip() |
| 1083 |
|
| 1084 |
|
| 1085 |
def get_argyll_display_number(geometry: tuple[int, int, int, int]) -> None | int: |
| 1086 |
"""Translate from wx display geometry to Argyll display index. |
| 1087 |
|
| 1088 |
Args: |
| 1089 |
geometry (tuple[int, int, int, int]): The geometry of the display. |
| 1090 |
|
| 1091 |
Returns: |
| 1092 |
None | int: The Argyll display index. |
| 1093 |
""" |
| 1094 |
geometry = f"{geometry[0]}, {geometry[1]}, {geometry[2]}x{geometry[3]}" |
| 1095 |
for i, display in enumerate(getcfg("displays")): |
| 1096 |
if display.find(f"@ {geometry}") > -1: |
| 1097 |
debug_print(f"[D] Found display {geometry} at index {i}") |
| 1098 |
return i |
| 1099 |
return None |
| 1100 |
|
| 1101 |
|
| 1102 |
def get_display_number(display_no: int) -> int: |
| 1103 |
"""Translate from Argyll display index to wx display index. |
| 1104 |
|
| 1105 |
Args: |
| 1106 |
display_no (int): The Argyll display index. |
| 1107 |
|
| 1108 |
Returns: |
| 1109 |
int: The wx display index. |
| 1110 |
""" |
| 1111 |
if is_virtual_display(display_no): |
| 1112 |
return 0 |
| 1113 |
from DisplayCAL.wx_addons import wx |
| 1114 |
|
| 1115 |
try: |
| 1116 |
display = getcfg("displays")[display_no] |
| 1117 |
except IndexError: |
| 1118 |
return 0 |
| 1119 |
else: |
| 1120 |
if display.endswith(" [PRIMARY]"): |
| 1121 |
display = " ".join(display.split(" ")[:-1]) |
| 1122 |
for i in range(wx.Display.GetCount()): |
| 1123 |
geometry = "{:d}, {:d}, {:d}x{:d}".format(*wx.Display(i).Geometry) |
| 1124 |
if display.endswith(f"@ {geometry}"): |
| 1125 |
debug_print(f"[D] Found display {geometry} at index {i}") |
| 1126 |
return i |
| 1127 |
return 0 |
| 1128 |
|
| 1129 |
|
| 1130 |
def get_display_rects() -> list[tuple[int, int, int, int]]: |
| 1131 |
"""Return the Argyll enumerated display coordinates and sizes. |
| 1132 |
|
| 1133 |
Returns: |
| 1134 |
list[tuple[int, int, int, int]]: A list of wx.Rect objects representing |
| 1135 |
the display coordinates and sizes. |
| 1136 |
""" |
| 1137 |
from DisplayCAL.wx_addons import wx |
| 1138 |
|
| 1139 |
display_rects = [] |
| 1140 |
for _i, display in enumerate(getcfg("displays")): |
| 1141 |
match = re.search(r"@ (-?\d+), (-?\d+), (\d+)x(\d+)", display) |
| 1142 |
if match: |
| 1143 |
display_rects.append(wx.Rect(*[int(item) for item in match.groups()])) |
| 1144 |
return display_rects |
| 1145 |
|
| 1146 |
|
| 1147 |
def get_icon_bundle(sizes: list[int], name: str) -> wx.IconBundle: |
| 1148 |
"""Return a wx.IconBundle with given icon sizes. |
| 1149 |
|
| 1150 |
Args: |
| 1151 |
sizes (list[int]): A list of icon sizes. |
| 1152 |
name (str): The name of the icon. |
| 1153 |
|
| 1154 |
Returns: |
| 1155 |
wx.IconBundle: The icon bundle. |
| 1156 |
""" |
| 1157 |
from DisplayCAL.wx_addons import wx |
| 1158 |
|
| 1159 |
iconbundle = wx.IconBundle() |
| 1160 |
if not sizes: |
| 1161 |
# Assume ICO format |
| 1162 |
pth = get_data_path(f"theme/icons/{name}.ico") |
| 1163 |
if pth: |
| 1164 |
ico = wx.Icon(pth) |
| 1165 |
if ico.IsOk(): |
| 1166 |
iconbundle.AddIcon(ico) |
| 1167 |
return iconbundle |
| 1168 |
sizes = [16] |
| 1169 |
for size in sizes: |
| 1170 |
iconbundle.AddIcon(get_bitmap_as_icon(size, name, False)) |
| 1171 |
return iconbundle |
| 1172 |
|
| 1173 |
|
| 1174 |
def get_instrument_name() -> str: |
| 1175 |
"""Return name of currently configured instrument. |
| 1176 |
|
| 1177 |
Returns: |
| 1178 |
str: The name of the instrument. |
| 1179 |
""" |
| 1180 |
n = getcfg("comport.number") - 1 |
| 1181 |
instrument_names = getcfg("instruments") |
| 1182 |
if 0 <= n < len(instrument_names): |
| 1183 |
return instrument_names[n] |
| 1184 |
return "" |
| 1185 |
|
| 1186 |
|
| 1187 |
def get_measureframe_dimensions( |
| 1188 |
dimensions_measureframe: None | str = None, percent: int = 10 |
| 1189 |
) -> str: |
| 1190 |
"""Return measurement area size adjusted for percentage of screen area. |
| 1191 |
|
| 1192 |
Args: |
| 1193 |
dimensions_measureframe (str): The dimensions of the measure frame. |
| 1194 |
percent (int): The percentage of screen area. |
| 1195 |
|
| 1196 |
Returns: |
| 1197 |
str: The coma separated measurement frame size. |
| 1198 |
""" |
| 1199 |
if not dimensions_measureframe: |
| 1200 |
dimensions_measureframe = getcfg("dimensions.measureframe") |
| 1201 |
dimensions_measureframe = [float(n) for n in dimensions_measureframe.split(",")] |
| 1202 |
dimensions_measureframe[2] *= DEFAULTS["size.measureframe"] |
| 1203 |
dimensions_measureframe[2] /= get_display_rects()[0][2] |
| 1204 |
dimensions_measureframe[2] *= percent |
| 1205 |
return ",".join([str(min(n, 50)) for n in dimensions_measureframe]) |
| 1206 |
|
| 1207 |
|
| 1208 |
def get_icon( |
| 1209 |
size: int, name: str, scale: bool = True, use_mask: bool = False |
| 1210 |
) -> wx.Bitmap: |
| 1211 |
"""Convenience function for get_bitmap('theme/icons/<size>/<name>'). |
| 1212 |
|
| 1213 |
Args: |
| 1214 |
size (int): The size of the icon. |
| 1215 |
name (str): The name of the icon. |
| 1216 |
scale (bool): Whether to scale the icon. |
| 1217 |
use_mask (bool): Whether to use a mask for the icon. |
| 1218 |
|
| 1219 |
Returns: |
| 1220 |
wx.Bitmap: The icon bitmap. |
| 1221 |
""" |
| 1222 |
return get_bitmap( |
| 1223 |
f"theme/icons/{size}x{size}/{name}", |
| 1224 |
scale=scale, |
| 1225 |
use_mask=use_mask, |
| 1226 |
) |
| 1227 |
|
| 1228 |
|
| 1229 |
def get_data_path(relpath: str, regex: None | str = None) -> None | str | list[str]: |
| 1230 |
"""Search data_dirs for relpath and return the path or a file list. |
| 1231 |
|
| 1232 |
If relpath is a file, return the full path, if relpath is a directory, |
| 1233 |
return a list of files in the intersection of searched directories. |
| 1234 |
|
| 1235 |
Args: |
| 1236 |
relpath (str): The relative path to search for. |
| 1237 |
regex (None | str): A regular expression to filter files. |
| 1238 |
|
| 1239 |
Returns: |
| 1240 |
None | str | list[str]: The full path if a file is found, or a list of |
| 1241 |
files if a directory is found, or None if nothing was found. |
| 1242 |
""" |
| 1243 |
if ( |
| 1244 |
not relpath |
| 1245 |
or relpath.endswith(os.path.sep) |
| 1246 |
or (isinstance(os.path.altsep, str) and relpath.endswith(os.path.altsep)) |
| 1247 |
): |
| 1248 |
return None |
| 1249 |
dirs = list(DATA_DIRS) |
| 1250 |
argyll_dir = getcfg("argyll.dir") or os.path.dirname( |
| 1251 |
os.path.realpath(which(f"dispcal{EXE_EXT}") or "") |
| 1252 |
) |
| 1253 |
if argyll_dir and os.path.isdir(os.path.join(argyll_dir, "..", "ref")): |
| 1254 |
dirs.append(os.path.dirname(argyll_dir)) |
| 1255 |
dirs.extend(EXTRA_DATA_DIRS) |
| 1256 |
intersection = [] |
| 1257 |
paths = [] |
| 1258 |
for dir_ in dirs: |
| 1259 |
curpath = os.path.join(dir_, relpath) |
| 1260 |
if ( |
| 1261 |
dir_.endswith("/argyll") |
| 1262 |
and f"{relpath}/".startswith("ref/") |
| 1263 |
and not os.path.exists(curpath) |
| 1264 |
): |
| 1265 |
# Work-around distribution-specific differences for location of |
| 1266 |
# Argyll reference files |
| 1267 |
# Fedora and Ubuntu: /usr/share/color/argyll/ref |
| 1268 |
# openSUSE: /usr/share/color/argyll |
| 1269 |
pth = relpath.split("/", 1)[-1] |
| 1270 |
curpath = os.path.join(dir_, pth) if pth != "ref" else dir_ |
| 1271 |
if os.path.exists(curpath): |
| 1272 |
curpath = os.path.normpath(curpath) |
| 1273 |
if os.path.isdir(curpath): |
| 1274 |
try: |
| 1275 |
filelist = listdir_re(curpath, regex) |
| 1276 |
except Exception as exception: |
| 1277 |
print(f"Error - directory '{curpath}' listing failed: {exception}") |
| 1278 |
else: |
| 1279 |
for filename in filelist: |
| 1280 |
if filename not in intersection: |
| 1281 |
intersection.append(filename) |
| 1282 |
paths.append(os.path.join(curpath, filename)) |
| 1283 |
else: |
| 1284 |
return curpath |
| 1285 |
if paths: |
| 1286 |
paths.sort(key=lambda path: os.path.basename(path).lower()) |
| 1287 |
return None if len(paths) == 0 else paths |
| 1288 |
|
| 1289 |
|
| 1290 |
def get_default_dpi() -> float: |
| 1291 |
"""Return default DPI depending on the current platform. |
| 1292 |
|
| 1293 |
Returns: |
| 1294 |
float: The DPI value. |
| 1295 |
""" |
| 1296 |
return 72.0 if sys.platform == "darwin" else 96.0 |
| 1297 |
|
| 1298 |
|
| 1299 |
def runtimeconfig(pyfile: str) -> str: |
| 1300 |
"""Configure remaining runtime options and return runtype. |
| 1301 |
|
| 1302 |
You need to pass in a path to the calling script (e.g. use the __file__ |
| 1303 |
attribute). |
| 1304 |
|
| 1305 |
Args: |
| 1306 |
pyfile (str): The path to the calling script. |
| 1307 |
|
| 1308 |
Returns: |
| 1309 |
str: The runtime type. |
| 1310 |
""" |
| 1311 |
# global safe_log |
| 1312 |
from DisplayCAL.log import setup_logging |
| 1313 |
|
| 1314 |
setup_logging(LOGDIR, PYNAME, PYEXT, confighome=CONFIG_HOME) |
| 1315 |
debug_print("[D] pydir:", PYDIR) |
| 1316 |
if ISAPP: |
| 1317 |
runtype = ".app" |
| 1318 |
elif ISEXE: |
| 1319 |
debug_print("[D] _MEIPASS2 or pydir:", getenvu("_MEIPASS2", EXEDIR)) |
| 1320 |
if getenvu("_MEIPASS2", EXEDIR) not in DATA_DIRS: |
| 1321 |
DATA_DIRS.insert(1, getenvu("_MEIPASS2", EXEDIR)) |
| 1322 |
runtype = EXE_EXT |
| 1323 |
else: |
| 1324 |
pydir_parent = os.path.dirname(PYDIR) |
| 1325 |
debug_print( |
| 1326 |
"[D] dirname(os.path.abspath(sys.argv[0])):", |
| 1327 |
os.path.dirname(os.path.abspath(sys.argv[0])), |
| 1328 |
) |
| 1329 |
debug_print("[D] pydir parent:", pydir_parent) |
| 1330 |
if ( |
| 1331 |
os.path.dirname(os.path.abspath(sys.argv[0])) == pydir_parent |
| 1332 |
and pydir_parent not in DATA_DIRS |
| 1333 |
): |
| 1334 |
# Add the parent directory of the package directory to our list of |
| 1335 |
# data directories if it is the directory containing the currently |
| 1336 |
# run script (e.g. when running from source) |
| 1337 |
DATA_DIRS.insert(1, pydir_parent) |
| 1338 |
runtype = PYEXT |
| 1339 |
for dir_ in sys.path: |
| 1340 |
if not isinstance(dir_, str): |
| 1341 |
dir_ = dir_.encode(FS_ENC) |
| 1342 |
dir_ = os.path.abspath(os.path.join(dir_, APPNAME)) |
| 1343 |
if dir_ not in DATA_DIRS and os.path.isdir(dir_): |
| 1344 |
DATA_DIRS.append(dir_) |
| 1345 |
debug_print("[D] from sys.path:", dir_) |
| 1346 |
|
| 1347 |
if sys.platform not in ("darwin", "win32"): |
| 1348 |
DATA_DIRS.extend( |
| 1349 |
[ |
| 1350 |
os.path.join(dir_, "doc", f"{APPNAME}-{VERSION_STRING}") |
| 1351 |
for dir_ in [*XDG_DATA_DIRS, XDG_DATA_HOME] |
| 1352 |
] |
| 1353 |
) |
| 1354 |
DATA_DIRS.extend( |
| 1355 |
[ |
| 1356 |
os.path.join(dir_, "doc", "packages", APPNAME) |
| 1357 |
for dir_ in [*XDG_DATA_DIRS, XDG_DATA_HOME] |
| 1358 |
] |
| 1359 |
) |
| 1360 |
DATA_DIRS.extend( |
| 1361 |
[ |
| 1362 |
os.path.join(dir_, "doc", APPNAME) |
| 1363 |
for dir_ in [*XDG_DATA_DIRS, XDG_DATA_HOME] |
| 1364 |
] |
| 1365 |
) |
| 1366 |
DATA_DIRS.extend( |
| 1367 |
[ |
| 1368 |
os.path.join(dir_, "doc", APPNAME.lower()) # Debian |
| 1369 |
for dir_ in [*XDG_DATA_DIRS, XDG_DATA_HOME] |
| 1370 |
] |
| 1371 |
) |
| 1372 |
DATA_DIRS.extend( |
| 1373 |
[ |
| 1374 |
os.path.join(dir_, "icons", "hicolor") |
| 1375 |
for dir_ in [*XDG_DATA_DIRS, XDG_DATA_HOME] |
| 1376 |
] |
| 1377 |
) |
| 1378 |
debug_print("[D] Data files search paths:\n[D]", "\n[D] ".join(DATA_DIRS)) |
| 1379 |
DEFAULTS["calibration.file"] = get_data_path("presets/default.icc") or "" |
| 1380 |
DEFAULTS["measurement_report.chart"] = ( |
| 1381 |
get_data_path(os.path.join("ref", "verify_extended.ti1")) or "" |
| 1382 |
) |
| 1383 |
return runtype |
| 1384 |
|
| 1385 |
|
| 1386 |
class CaseSensitiveConfigParser(configparser.RawConfigParser): |
| 1387 |
"""Case sensitive config parser.""" |
| 1388 |
|
| 1389 |
def optionxform(self, optionstr: str) -> str: |
| 1390 |
"""Return the option string as is, preserving case sensitivity. |
| 1391 |
|
| 1392 |
Args: |
| 1393 |
optionstr (str): The option string to be processed. |
| 1394 |
""" |
| 1395 |
return optionstr |
| 1396 |
|
| 1397 |
|
| 1398 |
# User settings |
| 1399 |
CFG = CaseSensitiveConfigParser() |
| 1400 |
CFG["Default"] = {} |
| 1401 |
|
| 1402 |
|
| 1403 |
VALID_RANGES = { |
| 1404 |
"3dlut.hdr_peak_luminance": [100.0, 10000.0], |
| 1405 |
"3dlut.hdr_minmll": [0.0, 0.1], |
| 1406 |
"3dlut.hdr_maxmll": [100.0, 10000.0], |
| 1407 |
"3dlut.trc_gamma": [0.000001, 10], |
| 1408 |
"3dlut.hdr_sat": [0.0, 1.0], |
| 1409 |
"3dlut.hdr_hue": [0.0, 1.0], |
| 1410 |
"3dlut.trc_output_offset": [0.0, 1.0], |
| 1411 |
"app.port": [1, 65535], |
| 1412 |
"gamma": [0.000001, 10], |
| 1413 |
"trc": [0.000001, 10], |
| 1414 |
# Argyll dispcal uses 20% of ambient (in lux, fixed steradiant of 3.1415) as |
| 1415 |
# adapting luminance, but we assume it already *is* the adapting luminance. |
| 1416 |
# To correct for this, scale so that dispcal gets the correct value. |
| 1417 |
"calibration.ambient_viewcond_adjust.lux": [0.0, sys.maxsize / 5.0], |
| 1418 |
"calibration.black_luminance": [0.000001, 10], |
| 1419 |
"calibration.black_output_offset": [0, 1], |
| 1420 |
"calibration.black_point_correction": [0, 1], |
| 1421 |
"calibration.black_point_rate": [0.05, 20], |
| 1422 |
"calibration.luminance": [20, 100000], |
| 1423 |
"iccgamut.surface_detail": [1.0, 50.0], |
| 1424 |
"measurement_report.trc_gamma": [0.01, 10], |
| 1425 |
"measurement_report.trc_output_offset": [0.0, 1.0], |
| 1426 |
"measure.display_settle_time_mult": [0.000001, 10000.0], |
| 1427 |
"measure.min_display_update_delay_ms": [20, 60000], |
| 1428 |
"multiprocessing.max_cpus": [0, 65], |
| 1429 |
"patterngenerator.apl": [0.0, 1.0], |
| 1430 |
"patterngenerator.ffp_insertion.duration": [0.1, 60.0], |
| 1431 |
"patterngenerator.ffp_insertion.interval": [0.0, 3600.0], |
| 1432 |
"patterngenerator.ffp_insertion.level": [0.0, 1.0], |
| 1433 |
"patterngenerator.quantize_bits": [0, 32], |
| 1434 |
"patterngenerator.resolve.port": [1, 65535], |
| 1435 |
"profile_loader.quantize_bits": [8, 16], |
| 1436 |
"synthprofile.trc_gamma": [0.01, 10], |
| 1437 |
"synthprofile.trc_output_offset": [0.0, 1.0], |
| 1438 |
"tc_export_repeat_patch_max": [1, 1000], |
| 1439 |
"tc_export_repeat_patch_min": [1, 1000], |
| 1440 |
"tc_vrml_black_offset": [0, 40], |
| 1441 |
"webserver.portnumber": [1, 65535], |
| 1442 |
"whitepoint.colortemp": [1000, 15000], |
| 1443 |
"whitepoint.visual_editor.bg_v": [0, 255], |
| 1444 |
"whitepoint.visual_editor.b": [0, 255], |
| 1445 |
"whitepoint.visual_editor.g": [0, 255], |
| 1446 |
"whitepoint.visual_editor.r": [0, 255], |
| 1447 |
} |
| 1448 |
|
| 1449 |
VALID_VALUES = { |
| 1450 |
"3d.format": ["HTML", "VRML", "X3D"], |
| 1451 |
"3dlut.bitdepth.input": [8, 10, 12, 14, 16], |
| 1452 |
"3dlut.bitdepth.output": [8, 10, 12, 14, 16], |
| 1453 |
"3dlut.encoding.input": list(VIDEO_ENCODINGS), |
| 1454 |
# collink: xvYCC output encoding is not supported |
| 1455 |
"3dlut.encoding.output": [v for v in VIDEO_ENCODINGS if v not in ("T", "x", "X")], |
| 1456 |
"3dlut.format": [ |
| 1457 |
"3dl", |
| 1458 |
"cube", |
| 1459 |
"dcl", |
| 1460 |
"eeColor", |
| 1461 |
"icc", |
| 1462 |
"madVR", |
| 1463 |
"mga", |
| 1464 |
"png", |
| 1465 |
"ReShade", |
| 1466 |
"spi3d", |
| 1467 |
], |
| 1468 |
"3dlut.hdr_display": [0, 1], |
| 1469 |
"3dlut.image.layout": ["h", "v"], |
| 1470 |
"3dlut.image.order": ["rgb", "bgr"], |
| 1471 |
"3dlut.rendering_intent": INTENTS, |
| 1472 |
"3dlut.size": [5, 9, 16, 17, 24, 32, 33, 64, 65], |
| 1473 |
"3dlut.trc": [ |
| 1474 |
"bt1886", |
| 1475 |
"customgamma", |
| 1476 |
"gamma2.2", |
| 1477 |
"smpte2084.hardclip", |
| 1478 |
"smpte2084.rolloffclip", |
| 1479 |
"hlg", |
| 1480 |
], |
| 1481 |
"3dlut.trc_gamma_type": ["b", "B"], |
| 1482 |
"calibration.quality": ["v", "l", "m", "h", "u"], |
| 1483 |
"colorimeter_correction.observer": OBSERVERS, |
| 1484 |
"colorimeter_correction.observer.reference": OBSERVERS, |
| 1485 |
"colorimeter_correction.type": ["matrix", "spectral"], |
| 1486 |
# Measurement modes as supported by Argyll -y parameter |
| 1487 |
# 'l' = 'n' (non-refresh-type display, e.g. LCD) |
| 1488 |
# 'c' = 'r' (refresh-type display, e.g. CRT) |
| 1489 |
# We map 'l' and 'c' to "n" and "r" in |
| 1490 |
# worker.Worker.add_measurement_features if using Argyll >= 1.5 |
| 1491 |
# See http://www.argyllcms.com/doc/instruments.html for description of |
| 1492 |
# per-instrument supported modes |
| 1493 |
"measurement_mode": [None, "auto", *list(string.digits[1:] + string.ascii_letters)], |
| 1494 |
"gamap_default_intent": ["a", "r", "p", "s"], |
| 1495 |
"gamap_perceptual_intent": INTENTS, |
| 1496 |
"gamap_saturation_intent": INTENTS, |
| 1497 |
"gamap_src_viewcond": VIEWCONDS, |
| 1498 |
"gamap_out_viewcond": ["mt", "mb", "md", "jm", "jd"], |
| 1499 |
"measurement_report.trc_gamma_type": ["b", "B"], |
| 1500 |
"observer": OBSERVERS, |
| 1501 |
"patterngenerator.detect_video_levels": [0, 1], |
| 1502 |
"patterngenerator.prisma.preset": [ |
| 1503 |
"Movie", |
| 1504 |
"Sports", |
| 1505 |
"Game", |
| 1506 |
"Animation", |
| 1507 |
"PC/Mac", |
| 1508 |
"Black+White", |
| 1509 |
"Custom-1", |
| 1510 |
"Custom-2", |
| 1511 |
], |
| 1512 |
"patterngenerator.use_video_levels": [0, 1], |
| 1513 |
"profile.black_point_compensation": [0, 1], |
| 1514 |
"profile.install_scope": ["l", "u"], |
| 1515 |
"profile.quality": ["l", "m", "h", "u"], |
| 1516 |
"profile.quality.b2a": ["l", "m", "h", "u", "n", None], |
| 1517 |
"profile.b2a.hires.size": [-1, 9, 17, 33, 45, 65], |
| 1518 |
"profile.type": ["g", "G", "l", "s", "S", "x", "X"], |
| 1519 |
"profile_loader.tray_icon_animation_quality": [0, 1, 2], |
| 1520 |
"synthprofile.black_point_compensation": [0, 1], |
| 1521 |
"synthprofile.trc_gamma_type": ["g", "G"], |
| 1522 |
"tc_algo": ["", "t", "r", "R", "q", "Q", "i", "I"], # Q = Argyll >= 1.1.0 |
| 1523 |
"tc_vrml_use_D50": [0, 1], |
| 1524 |
"tc_vrml_cie_colorspace": [ |
| 1525 |
"DIN99", |
| 1526 |
"DIN99b", |
| 1527 |
"DIN99c", |
| 1528 |
"DIN99d", |
| 1529 |
"ICtCp", |
| 1530 |
"IPT", |
| 1531 |
"LCH(ab)", |
| 1532 |
"LCH(uv)", |
| 1533 |
"Lab", |
| 1534 |
"Lpt", |
| 1535 |
"Luv", |
| 1536 |
"Lu'v'", |
| 1537 |
"xyY", |
| 1538 |
], |
| 1539 |
"tc_vrml_device_colorspace": ["HSI", "HSL", "HSV", "RGB"], |
| 1540 |
"testchart.auto_optimize": list(range(19)), |
| 1541 |
"testchart.patch_sequence": [ |
| 1542 |
"optimize_display_response_delay", |
| 1543 |
"maximize_lightness_difference", |
| 1544 |
"maximize_rec709_luma_difference", |
| 1545 |
"maximize_RGB_difference", |
| 1546 |
"vary_RGB_difference", |
| 1547 |
], |
| 1548 |
"trc": ["240", "709", "l", "s", ""], |
| 1549 |
"trc.type": ["g", "G"], |
| 1550 |
"uniformity.cols": [3, 5, 7, 9], |
| 1551 |
"uniformity.rows": [3, 5, 7, 9], |
| 1552 |
"whitepoint.colortemp.locus": ["t", "T"], |
| 1553 |
} |
| 1554 |
|
| 1555 |
CONTENT_RGB_SPACE = colormath.get_rgb_space("DCI P3 D65") |
| 1556 |
CRX, CRY = CONTENT_RGB_SPACE[2:][0][:2] |
| 1557 |
CGX, CGY = CONTENT_RGB_SPACE[2:][1][:2] |
| 1558 |
CBX, CBY = CONTENT_RGB_SPACE[2:][2][:2] |
| 1559 |
CWX, CWY = colormath.XYZ2xyY(*CONTENT_RGB_SPACE[1])[:2] |
| 1560 |
DEFAULTS = { |
| 1561 |
"3d.format": "HTML", |
| 1562 |
"3dlut.apply_black_offset": 0, |
| 1563 |
"3dlut.apply_trc": 1, |
| 1564 |
"3dlut.bitdepth.input": 10, |
| 1565 |
"3dlut.bitdepth.output": 12, |
| 1566 |
"3dlut.content.colorspace.blue.x": CBX, |
| 1567 |
"3dlut.content.colorspace.blue.y": CBY, |
| 1568 |
"3dlut.content.colorspace.green.x": CGX, |
| 1569 |
"3dlut.content.colorspace.green.y": CGY, |
| 1570 |
"3dlut.content.colorspace.red.x": CRX, |
| 1571 |
"3dlut.content.colorspace.red.y": CRY, |
| 1572 |
"3dlut.content.colorspace.white.x": CWX, |
| 1573 |
"3dlut.content.colorspace.white.y": CWY, |
| 1574 |
"3dlut.create": 0, |
| 1575 |
"3dlut.trc": "bt1886", |
| 1576 |
"3dlut.trc_gamma": 2.4, |
| 1577 |
"3dlut.trc_gamma.backup": 2.4, |
| 1578 |
"3dlut.trc_gamma_type": "B", |
| 1579 |
"3dlut.trc_output_offset": 0.0, |
| 1580 |
"3dlut.encoding.input": "n", |
| 1581 |
"3dlut.encoding.input.backup": "n", |
| 1582 |
"3dlut.encoding.output": "n", |
| 1583 |
"3dlut.encoding.output.backup": "n", |
| 1584 |
"3dlut.format": "cube", |
| 1585 |
"3dlut.gamap.use_b2a": 0, |
| 1586 |
"3dlut.hdr_display": 0, |
| 1587 |
"3dlut.hdr_minmll": 0.0, |
| 1588 |
"3dlut.hdr_maxmll": 10000.0, |
| 1589 |
"3dlut.hdr_maxmll_alt_clip": 1, |
| 1590 |
"3dlut.hdr_peak_luminance": 480.0, |
| 1591 |
"3dlut.hdr_ambient_luminance": 5.0, |
| 1592 |
"3dlut.hdr_sat": 0.5, |
| 1593 |
"3dlut.hdr_hue": 0.5, |
| 1594 |
"3dlut.image.layout": "h", |
| 1595 |
"3dlut.image.order": "rgb", |
| 1596 |
"3dlut.input.profile": "", |
| 1597 |
"3dlut.abstract.profile": "", |
| 1598 |
"3dlut.enable": 1, |
| 1599 |
"3dlut.output.profile": "", |
| 1600 |
"3dlut.output.profile.apply_cal": 1, |
| 1601 |
"3dlut.preserve_sync": 0, |
| 1602 |
"3dlut.rendering_intent": "aw", |
| 1603 |
"3dlut.use_abstract_profile": 0, |
| 1604 |
"3dlut.size": 65, |
| 1605 |
"3dlut.size.backup": 65, |
| 1606 |
"3dlut.tab.enable": 0, |
| 1607 |
"3dlut.tab.enable.backup": 0, |
| 1608 |
"3dlut.whitepoint.x": 0.3127, |
| 1609 |
"3dlut.whitepoint.y": 0.329, |
| 1610 |
"allow_skip_sensor_cal": 0, |
| 1611 |
"app.allow_network_clients": 0, |
| 1612 |
"app.dpi": get_default_dpi(), |
| 1613 |
"app.port": 15411, |
| 1614 |
"argyll.debug": 0, |
| 1615 |
"argyll.dir": None, |
| 1616 |
"argyll.version": "0.0.0", |
| 1617 |
"argyll.domain": "https://github.com/eoyilmaz/argyllcms-binaries", |
| 1618 |
"drift_compensation.blacklevel": 0, |
| 1619 |
"drift_compensation.whitelevel": 0, |
| 1620 |
"calibration.ambient_viewcond_adjust": 0, |
| 1621 |
"calibration.ambient_viewcond_adjust.lux": 32.0, |
| 1622 |
"calibration.autoload": 0, |
| 1623 |
"calibration.black_luminance": 0.000001, |
| 1624 |
"calibration.black_luminance.backup": 0.000001, |
| 1625 |
"calibration.black_output_offset": 1.0, |
| 1626 |
"calibration.black_output_offset.backup": 1.0, |
| 1627 |
"calibration.black_point_correction": 0.0, |
| 1628 |
"calibration.black_point_correction.auto": 0, |
| 1629 |
"calibration.black_point_correction_choice.show": 1, |
| 1630 |
"calibration.black_point_hack": 0, |
| 1631 |
"calibration.black_point_rate": 4.0, |
| 1632 |
"calibration.black_point_rate.enabled": 0, |
| 1633 |
"calibration.continue_next": 0, |
| 1634 |
"calibration.file": "", |
| 1635 |
"calibration.file.previous": None, |
| 1636 |
"calibration.interactive_display_adjustment": 1, |
| 1637 |
"calibration.interactive_display_adjustment.backup": 1, |
| 1638 |
"calibration.luminance": 120.0, |
| 1639 |
"calibration.luminance.backup": 120.0, |
| 1640 |
"calibration.quality": "l", |
| 1641 |
"calibration.update": 0, |
| 1642 |
"calibration.use_video_lut": 1, |
| 1643 |
"calibration.use_video_lut.backup": 1, |
| 1644 |
"ccmx.use_four_color_matrix_method": 0, |
| 1645 |
"colorimeter_correction.instrument": None, |
| 1646 |
"colorimeter_correction.instrument.reference": None, |
| 1647 |
"colorimeter_correction.measurement_mode": "l", |
| 1648 |
"colorimeter_correction.measurement_mode.reference.adaptive": 1, |
| 1649 |
"colorimeter_correction.measurement_mode.reference.highres": 1, |
| 1650 |
"colorimeter_correction.measurement_mode.reference.projector": 0, |
| 1651 |
"colorimeter_correction.measurement_mode.reference": "l", |
| 1652 |
"colorimeter_correction.observer": "1931_2", |
| 1653 |
"colorimeter_correction.observer.reference": "1931_2", |
| 1654 |
"colorimeter_correction.testchart": "ccxx.ti1", |
| 1655 |
"colorimeter_correction_matrix_file": "AUTO:", |
| 1656 |
"colorimeter_correction.type": "matrix", |
| 1657 |
"comport.number": 1, |
| 1658 |
"comport.number.backup": 1, |
| 1659 |
# Note: worker.Worker.enumerate_displays_and_ports() overwrites copyright |
| 1660 |
"copyright": f"No copyright. Created with {APPNAME} {VERSION_STRING} and ArgyllCMS", |
| 1661 |
"dimensions.measureframe": "0.5,0.5,1.0", |
| 1662 |
"dimensions.measureframe.unzoomed": "0.5,0.5,1.0", |
| 1663 |
"dimensions.measureframe.whitepoint.visual_editor": "0.5,0.5,1.0", |
| 1664 |
"display.number": 1, |
| 1665 |
"display_lut.link": 1, |
| 1666 |
"display_lut.number": 1, |
| 1667 |
"display.technology": "LCD", |
| 1668 |
"displays": "", |
| 1669 |
"dry_run": 0, |
| 1670 |
"enumerate_ports.auto": 0, |
| 1671 |
"extra_args.collink": "", |
| 1672 |
"extra_args.colprof": "", |
| 1673 |
"extra_args.dispcal": "", |
| 1674 |
"extra_args.dispread": "", |
| 1675 |
"extra_args.specplot": "", |
| 1676 |
"extra_args.spotread": "", |
| 1677 |
"extra_args.targen": "", |
| 1678 |
"gamap_default_intent": "p", |
| 1679 |
"gamap_out_viewcond": None, |
| 1680 |
"gamap_profile": "", |
| 1681 |
"gamap_perceptual": 0, |
| 1682 |
"gamap_perceptual_intent": "p", |
| 1683 |
"gamap_saturation": 0, |
| 1684 |
"gamap_saturation_intent": "s", |
| 1685 |
"gamap_src_viewcond": None, |
| 1686 |
"gamma": 2.2, |
| 1687 |
"iccgamut.surface_detail": 10.0, |
| 1688 |
"instruments": "", |
| 1689 |
"last_3dlut_path": "", |
| 1690 |
"last_archive_save_path": "", |
| 1691 |
"last_cal_path": "", |
| 1692 |
"last_cal_or_icc_path": "", |
| 1693 |
"last_colorimeter_ti3_path": "", |
| 1694 |
"last_testchart_export_path": "", |
| 1695 |
"last_filedialog_path": "", |
| 1696 |
"last_icc_path": "", |
| 1697 |
"last_launch": "99", # Version |
| 1698 |
"last_reference_ti3_path": "", |
| 1699 |
"last_specplot_path": "", |
| 1700 |
"last_ti1_path": "", |
| 1701 |
"last_ti3_path": "", |
| 1702 |
"last_vrml_path": "", |
| 1703 |
"log.autoshow": 0, |
| 1704 |
"log.show": 0, |
| 1705 |
"lang": "en", |
| 1706 |
# The last_[...]_path defaults are set in localization.py |
| 1707 |
"lut_viewer.show": 0, |
| 1708 |
"lut_viewer.show_actual_lut": 0, |
| 1709 |
"madtpg.host": "localhost", |
| 1710 |
"madtpg.native": 1, |
| 1711 |
"madtpg.port": 60562, |
| 1712 |
"measurement_mode": "l", |
| 1713 |
"measurement_mode.adaptive": 1, |
| 1714 |
"measurement_mode.backup": "l", |
| 1715 |
"measurement_mode.highres": 1, |
| 1716 |
"measurement_mode.projector": 0, |
| 1717 |
"measurement_report.apply_black_offset": 0, |
| 1718 |
"measurement_report.apply_trc": 0, |
| 1719 |
"measurement_report.trc_gamma": 2.4, |
| 1720 |
"measurement_report.trc_gamma.backup": 2.4, |
| 1721 |
"measurement_report.trc_gamma_type": "B", |
| 1722 |
"measurement_report.trc_output_offset": 0.0, |
| 1723 |
"measurement_report.chart": "", |
| 1724 |
"measurement_report.chart.fields": "RGB", |
| 1725 |
"measurement_report.devlink_profile": "", |
| 1726 |
"measurement_report.output_profile": "", |
| 1727 |
"measurement_report.whitepoint.simulate": 0, |
| 1728 |
"measurement_report.whitepoint.simulate.relative": 0, |
| 1729 |
"measurement_report.simulation_profile": "", |
| 1730 |
"measurement_report.use_devlink_profile": 0, |
| 1731 |
"measurement_report.use_simulation_profile": 0, |
| 1732 |
"measurement_report.use_simulation_profile_as_output": 0, |
| 1733 |
"measurement.name.expanded": "", |
| 1734 |
"measurement.play_sound": 1, |
| 1735 |
"measurement.save_path": expanduseru("~"), |
| 1736 |
"measure.darken_background": 0, |
| 1737 |
"measure.darken_background.show_warning": 1, |
| 1738 |
"measure.display_settle_time_mult": 1.0, |
| 1739 |
"measure.display_settle_time_mult.backup": 1.0, |
| 1740 |
"measure.min_display_update_delay_ms": 20, |
| 1741 |
"measure.min_display_update_delay_ms.backup": 20, |
| 1742 |
"measure.override_display_settle_time_mult": 0, |
| 1743 |
"measure.override_display_settle_time_mult.backup": 0, |
| 1744 |
"measure.override_min_display_update_delay_ms": 0, |
| 1745 |
"measure.override_min_display_update_delay_ms.backup": 0, |
| 1746 |
"multiprocessing.max_cpus": 0, |
| 1747 |
"observer": "1931_2", |
| 1748 |
"observer.backup": "1931_2", |
| 1749 |
"patterngenerator.apl": 0.22, |
| 1750 |
"patterngenerator.detect_video_levels": 1, |
| 1751 |
"patterngenerator.ffp_insertion": 0, |
| 1752 |
"patterngenerator.ffp_insertion.duration": 5.0, |
| 1753 |
"patterngenerator.ffp_insertion.interval": 5.0, |
| 1754 |
"patterngenerator.ffp_insertion.level": 0.15, |
| 1755 |
"patterngenerator.prisma.argyll": 0, |
| 1756 |
"patterngenerator.prisma.host": "", |
| 1757 |
"patterngenerator.prisma.preset": "Custom-1", |
| 1758 |
"patterngenerator.prisma.port": 80, |
| 1759 |
"patterngenerator.quantize_bits": 0, |
| 1760 |
"patterngenerator.resolve": "CM", |
| 1761 |
"patterngenerator.resolve.port": 20002, |
| 1762 |
"patterngenerator.use_pattern_window": 0, |
| 1763 |
"patterngenerator.use_video_levels": 0, |
| 1764 |
"position.x": 50, |
| 1765 |
"position.y": 50, |
| 1766 |
"position.info.x": 50, |
| 1767 |
"position.info.y": 50, |
| 1768 |
"position.lut_viewer.x": 50, |
| 1769 |
"position.lut_viewer.y": 50, |
| 1770 |
"position.lut3dframe.x": 50, |
| 1771 |
"position.lut3dframe.y": 50, |
| 1772 |
"position.profile_info.x": 50, |
| 1773 |
"position.profile_info.y": 50, |
| 1774 |
"position.progress.x": 50, |
| 1775 |
"position.progress.y": 50, |
| 1776 |
"position.reportframe.x": 50, |
| 1777 |
"position.reportframe.y": 50, |
| 1778 |
"position.scripting.x": 50, |
| 1779 |
"position.scripting.y": 50, |
| 1780 |
"position.synthiccframe.x": 50, |
| 1781 |
"position.synthiccframe.y": 50, |
| 1782 |
"position.tcgen.x": 50, |
| 1783 |
"position.tcgen.y": 50, |
| 1784 |
# Force black point compensation due to OS X bugs with non BPC profiles |
| 1785 |
"profile.black_point_compensation": 0 if sys.platform != "darwin" else 1, |
| 1786 |
"profile.black_point_correction": 0.0, |
| 1787 |
"profile.create_gamut_views": 1, |
| 1788 |
"profile.install_scope": ( |
| 1789 |
"l" if (sys.platform != "win32" and os.geteuid() == 0) else "u" # Linux, OSX |
| 1790 |
), |
| 1791 |
"profile.license": "Public Domain", |
| 1792 |
"profile.load_on_login": 1, |
| 1793 |
"profile.name": "_".join( # noqa: FLY002 |
| 1794 |
[ |
| 1795 |
"%dns", |
| 1796 |
"%out", |
| 1797 |
"%Y-%m-%d_%H-%M", |
| 1798 |
"%cb", |
| 1799 |
"%wp", |
| 1800 |
"%cB", |
| 1801 |
"%ck", |
| 1802 |
"%cg", |
| 1803 |
"%cq-%pq", |
| 1804 |
"%pt", |
| 1805 |
] |
| 1806 |
), |
| 1807 |
"profile.name.expanded": "", |
| 1808 |
"profile.quality": "h", |
| 1809 |
"profile.quality.b2a": "h", |
| 1810 |
"profile.b2a.hires": 1, |
| 1811 |
"profile.b2a.hires.diagpng": 2, |
| 1812 |
"profile.b2a.hires.size": -1, |
| 1813 |
"profile.b2a.hires.smooth": 1, |
| 1814 |
"profile.save_path": STORAGE, # directory |
| 1815 |
# Force profile type to single shaper + matrix due to OS X bugs with cLUT |
| 1816 |
# profiles and matrix profiles with individual shaper curves |
| 1817 |
"profile.type": "X" if sys.platform != "darwin" else "S", |
| 1818 |
"profile.update": 0, |
| 1819 |
"profile_loader.buggy_video_drivers": "*", |
| 1820 |
"profile_loader.check_gamma_ramps": 1, |
| 1821 |
"profile_loader.error.show_msg": 1, |
| 1822 |
"profile_loader.exceptions": "", |
| 1823 |
"profile_loader.fix_profile_associations": 1, |
| 1824 |
"profile_loader.ignore_unchanged_gamma_ramps": 1, |
| 1825 |
"profile_loader.known_apps": ";".join( # noqa: FLY002 |
| 1826 |
[ |
| 1827 |
"basiccolor display.exe", |
| 1828 |
"calclient.exe", |
| 1829 |
"coloreyes display pro.exe", |
| 1830 |
"colorhcfr.exe", |
| 1831 |
"colormunkidisplay.exe", |
| 1832 |
"colornavigator.exe", |
| 1833 |
"cpkeeper.exe", |
| 1834 |
"dell ultrasharp calibration solution.exe", |
| 1835 |
"hp_dreamcolor_calibration_solution.exe", |
| 1836 |
"i1profiler.exe", |
| 1837 |
"icolordisplay.exe", |
| 1838 |
"spectraview.exe", |
| 1839 |
"spectraview profiler.exe", |
| 1840 |
"spyder3elite.exe", |
| 1841 |
"spyder3express.exe", |
| 1842 |
"spyder3pro.exe", |
| 1843 |
"spyder4elite.exe", |
| 1844 |
"spyder4express.exe", |
| 1845 |
"spyder4pro.exe", |
| 1846 |
"spyder5elite.exe", |
| 1847 |
"spyder5express.exe", |
| 1848 |
"spyder5pro.exe", |
| 1849 |
"spyderxelite.exe", |
| 1850 |
"spyderxpro.exe", |
| 1851 |
"dispcal.exe", |
| 1852 |
"dispread.exe", |
| 1853 |
"dispwin.exe", |
| 1854 |
"flux.exe", |
| 1855 |
"dccw.exe", |
| 1856 |
] |
| 1857 |
), |
| 1858 |
"profile_loader.known_window_classes": "CalClient.exe", |
| 1859 |
# Number of times to (re)try loading calibration when a load doesn't |
| 1860 |
# verify as loaded (e.g. macOS intermittently clobbering the VideoLUT to |
| 1861 |
# black right after loading). See profile_loader.apply_profiles(). |
| 1862 |
"profile_loader.load_retries": 3, |
| 1863 |
# macOS only: keep the apply-profiles process running and periodically |
| 1864 |
# re-load calibration if the OS (WindowServer) has clobbered the VideoLUT |
| 1865 |
# (the "black screen" bug). See profile_loader.ProfileLoader._macos_watch(). |
| 1866 |
"profile_loader.macos_reapply_watch": 1, |
| 1867 |
"profile_loader.macos_reapply_watch_interval": 5, |
| 1868 |
# Maximum number of scan/reload passes the macOS watch will run in a |
| 1869 |
# single tick to converge all displays before giving up until the next |
| 1870 |
# tick. Re-loading one display's calibration can itself trigger the OS to |
| 1871 |
# clobber a *different* display (issue #824), so each pass re-scans and |
| 1872 |
# re-loads every clobbered display together rather than reacting to one |
| 1873 |
# display at a time, which could ping-pong between displays forever. See |
| 1874 |
# profile_loader.ProfileLoader._reload_clobbered_displays(). |
| 1875 |
"profile_loader.macos_reapply_watch_max_passes": 5, |
| 1876 |
# Some multi-display Macs never converge (reloading one display |
| 1877 |
# deterministically clobbers another's VideoLUT and vice-versa, issue |
| 1878 |
# #824). After this many consecutive watch ticks without converging, back |
| 1879 |
# off instead of retrying forever. See |
| 1880 |
# profile_loader.ProfileLoader._macos_watch(). |
| 1881 |
"profile_loader.macos_reapply_watch_unstable_threshold": 3, |
| 1882 |
# How long (in seconds) to stop touching the displays after the unstable |
| 1883 |
# threshold above is hit, before trying again. |
| 1884 |
"profile_loader.macos_reapply_watch_backoff_seconds": 300, |
| 1885 |
# VideoLUT verify discrepancy (in percent) above which the loaded |
| 1886 |
# calibration is considered clobbered/degenerate (e.g. a black screen) |
| 1887 |
# rather than just quantization noise. dispwin's own "is loaded" tolerance |
| 1888 |
# (~0.4%) is far too tight for this purpose, so we use the reported |
| 1889 |
# discrepancy with this much more lenient threshold to avoid needlessly |
| 1890 |
# re-loading (and thereby re-triggering the bug). See |
| 1891 |
# profile_loader.ProfileLoader._calibration_load_discrepancy(). |
| 1892 |
"profile_loader.clobbered_discrepancy_threshold": 25, |
| 1893 |
# VideoLUT maximum output value (0.0 - 1.0) below which the macOS |
| 1894 |
# background watch considers a display's calibration clobbered/black. |
| 1895 |
# Checked directly via CoreGraphics rather than by running `dispwin -V`, |
| 1896 |
# since spawning any dispwin subprocess - even a read-only verify - can |
| 1897 |
# itself trigger the OS to clobber a *different* display (issue #824). |
| 1898 |
# See profile_loader.ProfileLoader._clobbered_displays() and |
| 1899 |
# worker.get_macos_videolut_maxima(). |
| 1900 |
"profile_loader.macos_videolut_black_threshold": 0.05, |
| 1901 |
"profile_loader.quantize_bits": 16, |
| 1902 |
"profile_loader.reset_gamma_ramps": 0, |
| 1903 |
"profile_loader.show_notifications": 0, |
| 1904 |
"profile_loader.smooth_bits": "8", |
| 1905 |
"profile_loader.track_other_processes": 1, |
| 1906 |
"profile_loader.tray_icon_animation_quality": 2, |
| 1907 |
"profile_loader.use_madhcnet": 0, |
| 1908 |
"profile_loader.verify_calibration": 0, |
| 1909 |
"recent_cals": "", |
| 1910 |
"report.pack_js": 1, |
| 1911 |
"settings.changed": 0, |
| 1912 |
"show_advanced_options": 0, |
| 1913 |
"show_donation_message": 1, |
| 1914 |
"size.info.w": 512, |
| 1915 |
"size.info.h": 384, |
| 1916 |
"size.lut3dframe.w": 512, |
| 1917 |
"size.lut3dframe.h": 384, |
| 1918 |
"size.measureframe": 300, |
| 1919 |
"size.profile_info.w": 432, |
| 1920 |
"size.profile_info.split.w": 960, |
| 1921 |
"size.profile_info.h": 552, |
| 1922 |
"size.lut_viewer.w": 432, |
| 1923 |
"size.lut_viewer.h": 552, |
| 1924 |
"size.reportframe.w": 512, |
| 1925 |
"size.reportframe.h": 256, |
| 1926 |
"size.scripting.w": 512, |
| 1927 |
"size.scripting.h": 384, |
| 1928 |
"size.synthiccframe.w": 512, |
| 1929 |
"size.synthiccframe.h": 384, |
| 1930 |
"size.tcgen.w": 0, |
| 1931 |
"size.tcgen.h": 0, |
| 1932 |
"skip_legacy_serial_ports": 1, |
| 1933 |
"skip_scripts": 1, |
| 1934 |
"splash.zoom": 0, |
| 1935 |
"splash.simple": 0, |
| 1936 |
"startup_sound.enable": 1, |
| 1937 |
"sudo.preserve_environment": 1, |
| 1938 |
"synthprofile.black_luminance": 0.0, |
| 1939 |
"synthprofile.luminance": 120.0, |
| 1940 |
"synthprofile.trc_gamma": 2.4, |
| 1941 |
"synthprofile.trc_gamma_type": "G", |
| 1942 |
"synthprofile.trc_output_offset": 0.0, |
| 1943 |
"tc_adaption": 0.1, |
| 1944 |
"tc_add_ti3_relative": 1, |
| 1945 |
"tc_algo": "", |
| 1946 |
"tc_angle": 0.3333, |
| 1947 |
"tc_black_patches": 4, |
| 1948 |
"tc_export_repeat_patch_max": 1, |
| 1949 |
"tc_export_repeat_patch_min": 1, |
| 1950 |
"tc_filter": 0, |
| 1951 |
"tc_filter_L": 50, |
| 1952 |
"tc_filter_a": 0, |
| 1953 |
"tc_filter_b": 0, |
| 1954 |
"tc_filter_rad": 255, |
| 1955 |
"tc_fullspread_patches": 0, |
| 1956 |
"tc_gamma": 1.0, |
| 1957 |
"tc_gray_patches": 9, |
| 1958 |
"tc_multi_bcc": 0, |
| 1959 |
"tc_multi_bcc_steps": 0, |
| 1960 |
"tc_multi_steps": 3, |
| 1961 |
"tc_neutral_axis_emphasis": 0.5, |
| 1962 |
"tc_dark_emphasis": 0.0, |
| 1963 |
"tc_precond": 0, |
| 1964 |
"tc_precond_profile": "", |
| 1965 |
"tc.saturation_sweeps": 5, |
| 1966 |
"tc.saturation_sweeps.custom.R": 0.0, |
| 1967 |
"tc.saturation_sweeps.custom.G": 0.0, |
| 1968 |
"tc.saturation_sweeps.custom.B": 0.0, |
| 1969 |
"tc_single_channel_patches": 0, |
| 1970 |
"tc_vrml_black_offset": 40, |
| 1971 |
"tc_vrml_cie": 0, |
| 1972 |
"tc_vrml_cie_colorspace": "Lab", |
| 1973 |
"tc_vrml_device_colorspace": "RGB", |
| 1974 |
"tc_vrml_device": 1, |
| 1975 |
"tc_vrml_use_D50": 0, |
| 1976 |
"tc_white_patches": 4, |
| 1977 |
"tc.show": 0, |
| 1978 |
# Profile type forced to matrix due to OS X bugs with cLUT profiles. |
| 1979 |
# Set smallest testchart. |
| 1980 |
"testchart.auto_optimize": 4 if sys.platform != "darwin" else 1, |
| 1981 |
"testchart.file": "auto", |
| 1982 |
"testchart.file.backup": "auto", |
| 1983 |
"testchart.patch_sequence": "optimize_display_response_delay", |
| 1984 |
"testchart.reference": "", |
| 1985 |
"ti3.check_sanity.auto": 0, |
| 1986 |
"trc": 2.2, |
| 1987 |
"trc.backup": 2.2, |
| 1988 |
"trc.should_use_viewcond_adjust.show_msg": 1, |
| 1989 |
"trc.type": "g", |
| 1990 |
"trc.type.backup": "g", |
| 1991 |
"uniformity.cols": 5, |
| 1992 |
"uniformity.measure.continuous": 0, |
| 1993 |
"uniformity.rows": 5, |
| 1994 |
"untethered.measure.auto": 1, |
| 1995 |
"untethered.measure.manual.delay": 0.75, |
| 1996 |
"untethered.max_delta.chroma": 0.5, |
| 1997 |
"untethered.min_delta": 1.5, |
| 1998 |
"untethered.min_delta.lightness": 1.0, |
| 1999 |
"update_check": 1, |
| 2000 |
"use_fancy_progress": 1, |
| 2001 |
"use_separate_lut_access": 0, |
| 2002 |
"vrml.compress": 1, |
| 2003 |
"webserver.portnumber": 8080, |
| 2004 |
"whitepoint.colortemp": 6500, |
| 2005 |
"whitepoint.colortemp.backup": 6500, |
| 2006 |
"whitepoint.colortemp.locus": "t", |
| 2007 |
"whitepoint.visual_editor.bg_v": 255, |
| 2008 |
"whitepoint.visual_editor.b": 255, |
| 2009 |
"whitepoint.visual_editor.g": 255, |
| 2010 |
"whitepoint.visual_editor.r": 255, |
| 2011 |
"whitepoint.x": 0.3127, |
| 2012 |
"whitepoint.x.backup": 0.3127, |
| 2013 |
"whitepoint.y": 0.3290, |
| 2014 |
"whitepoint.y.backup": 0.3290, |
| 2015 |
"x3dom.cache": 1, |
| 2016 |
"x3dom.embed": 0, |
| 2017 |
} |
| 2018 |
LCODE, LENC = locale.getlocale() |
| 2019 |
if LCODE: |
| 2020 |
DEFAULTS["lang"] = LCODE.split("_")[0].lower() |
| 2021 |
|
| 2022 |
TESTCHART_DEFAULTS = { |
| 2023 |
"s": {None: "auto"}, # shaper + matrix |
| 2024 |
"l": {None: "auto"}, # lut |
| 2025 |
"g": {None: "auto"}, # gamma + matrix |
| 2026 |
} |
| 2027 |
|
| 2028 |
|
| 2029 |
def _init_testcharts() -> None: |
| 2030 |
RES_FILES.extend( |
| 2031 |
os.path.join("ti1", chart) |
| 2032 |
for testcharts in list(TESTCHART_DEFAULTS.values()) |
| 2033 |
for chart in [value for value in list(testcharts.values()) if value != "auto"] |
| 2034 |
) |
| 2035 |
TESTCHART_DEFAULTS["G"] = TESTCHART_DEFAULTS["g"] |
| 2036 |
TESTCHART_DEFAULTS["S"] = TESTCHART_DEFAULTS["s"] |
| 2037 |
for key in ("X", "x"): |
| 2038 |
TESTCHART_DEFAULTS[key] = TESTCHART_DEFAULTS["l"] |
| 2039 |
|
| 2040 |
|
| 2041 |
def getcfg( |
| 2042 |
name: str, |
| 2043 |
fallback: bool = True, |
| 2044 |
raw: bool = False, |
| 2045 |
cfg: configparser.ConfigParser = CFG, |
| 2046 |
) -> Any: # noqa: ANN401 |
| 2047 |
"""Get and return an option value from the configuration. |
| 2048 |
|
| 2049 |
If fallback evaluates to True and the option is not set, return its default |
| 2050 |
value. |
| 2051 |
|
| 2052 |
Args: |
| 2053 |
name (str): The name of the option to get. |
| 2054 |
fallback (bool): Whether to return the default value if the option is |
| 2055 |
not set. |
| 2056 |
raw (bool): If True, return the raw value without type conversion. |
| 2057 |
cfg (configparser.ConfigParser): The configuration parser instance. |
| 2058 |
|
| 2059 |
Returns: |
| 2060 |
Any: The value of the option, converted to the appropriate type if |
| 2061 |
necessary, or the default value if the option is not set and |
| 2062 |
fallback is True. |
| 2063 |
""" |
| 2064 |
if name == "profile.name.expanded" and is_ccxx_testchart(): |
| 2065 |
name = "measurement.name.expanded" |
| 2066 |
value = None |
| 2067 |
has_default = name in DEFAULTS |
| 2068 |
defval = DEFAULTS.get(name) |
| 2069 |
value = get_config_value(name, raw, cfg) |
| 2070 |
if value is None: |
| 2071 |
if has_default and fallback: |
| 2072 |
value = defval |
| 2073 |
if defval is not None: |
| 2074 |
debug_print(name, "- falling back to", value) |
| 2075 |
elif DEBUG and not has_default: |
| 2076 |
print("Warning - unknown option:", name) |
| 2077 |
if raw: |
| 2078 |
return value |
| 2079 |
if ( |
| 2080 |
value |
| 2081 |
and isinstance(value, str) |
| 2082 |
and name.endswith("file") |
| 2083 |
and name != "colorimeter_correction_matrix_file" |
| 2084 |
and (name != "testchart.file" or value != "auto") |
| 2085 |
and (not os.path.isabs(value) or not os.path.exists(value)) |
| 2086 |
): |
| 2087 |
value = get_corrected_colorimeter_path(name, value) |
| 2088 |
elif name in ("displays", "instruments"): |
| 2089 |
if not value: |
| 2090 |
return [] |
| 2091 |
value = [ |
| 2092 |
strtr( |
| 2093 |
v, |
| 2094 |
[ |
| 2095 |
(f"%{hex(ord(os.pathsep))[2:].upper()}", os.pathsep), |
| 2096 |
("%25", "%"), |
| 2097 |
], |
| 2098 |
) |
| 2099 |
for v in value.split(os.pathsep) |
| 2100 |
] |
| 2101 |
return value |
| 2102 |
|
| 2103 |
|
| 2104 |
def get_config_value( |
| 2105 |
name: str, |
| 2106 |
raw: bool, |
| 2107 |
cfg: configparser.ConfigParser, |
| 2108 |
) -> Any: # noqa: ANN401 |
| 2109 |
"""Helper function to get the configuration value. |
| 2110 |
|
| 2111 |
Args: |
| 2112 |
name (str): The name of the configuration option. |
| 2113 |
raw (bool): If True, return the raw value without type conversion. |
| 2114 |
cfg (configparser.ConfigParser): The configuration parser instance. |
| 2115 |
defval: The default value for the option. |
| 2116 |
deftype: The type of the default value. |
| 2117 |
|
| 2118 |
Returns: |
| 2119 |
Any: The value of the configuration option, or None if not found. |
| 2120 |
""" |
| 2121 |
if not cfg.has_option(configparser.DEFAULTSECT, name): |
| 2122 |
return None |
| 2123 |
|
| 2124 |
try: |
| 2125 |
value = cfg.get(configparser.DEFAULTSECT, name) |
| 2126 |
except UnicodeDecodeError: |
| 2127 |
pass |
| 2128 |
else: |
| 2129 |
if not raw: |
| 2130 |
value = validate_value_type(name, value) |
| 2131 |
return value |
| 2132 |
|
| 2133 |
|
| 2134 |
def get_corrected_colorimeter_path( |
| 2135 |
name: str = "colorimeter_correction_matrix_file", |
| 2136 |
value: str | None = None, |
| 2137 |
) -> str: |
| 2138 |
"""Get the corrected path for a colorimeter correction matrix file. |
| 2139 |
|
| 2140 |
This function checks if the provided path exists and normalizes it. |
| 2141 |
If the path does not exist, it attempts to find a fallback path based on |
| 2142 |
the application's data directories or returns a default value if specified. |
| 2143 |
|
| 2144 |
Args: |
| 2145 |
name (str): The name of the configuration option. |
| 2146 |
value (str | None): The path to check. If None, the function will not |
| 2147 |
attempt to normalize or check the path. |
| 2148 |
|
| 2149 |
Returns: |
| 2150 |
str: The corrected path if it exists, or a default value if specified. |
| 2151 |
""" |
| 2152 |
has_default = name in DEFAULTS |
| 2153 |
defval = DEFAULTS.get(name) |
| 2154 |
# colorimeter_correction_matrix_file is special |
| 2155 |
# because it's not (only) a path |
| 2156 |
debug_print(f"{name} does not exist: {value}", end=" ") |
| 2157 |
# Normalize path (important, this turns altsep into sep under Windows) |
| 2158 |
value = os.path.normpath(value) |
| 2159 |
# Check if this is a relative path covered by data_dirs |
| 2160 |
splits = value.split(os.path.sep) |
| 2161 |
if (splits[-3:-2] == [APPNAME] or not os.path.isabs(value)) and ( |
| 2162 |
splits[-2:-1] == ["presets"] |
| 2163 |
or splits[-2:-1] == ["ref"] |
| 2164 |
or splits[-2:-1] == ["ti1"] |
| 2165 |
): |
| 2166 |
value = os.path.join(*splits[-2:]) |
| 2167 |
value = get_data_path(value) |
| 2168 |
elif has_default: |
| 2169 |
value = None |
| 2170 |
if not value and has_default: |
| 2171 |
value = defval |
| 2172 |
if DEBUG > 1: |
| 2173 |
print(name, "- falling back to", value) |
| 2174 |
|
| 2175 |
return value |
| 2176 |
|
| 2177 |
|
| 2178 |
def hascfg( |
| 2179 |
name: str, |
| 2180 |
fallback: bool = True, |
| 2181 |
cfg: configparser.ConfigParser = CFG, |
| 2182 |
) -> bool: |
| 2183 |
"""Check if an option name exists in the configuration. |
| 2184 |
|
| 2185 |
Returns a boolean value. |
| 2186 |
If fallback evaluates to True and the name does not exist, check defaults |
| 2187 |
also. |
| 2188 |
|
| 2189 |
Args: |
| 2190 |
name (str): The name of the configuration option. |
| 2191 |
fallback (bool, optional): If True, check the DEFAULTS dictionary if |
| 2192 |
the option is not found in the configuration. Defaults to True. |
| 2193 |
cfg (configparser.ConfigParser, optional): The configuration object to |
| 2194 |
check. Defaults to CFG. |
| 2195 |
|
| 2196 |
Returns: |
| 2197 |
bool: True if the option exists in the configuration, False otherwise. |
| 2198 |
""" |
| 2199 |
if cfg.has_option(configparser.DEFAULTSECT, name): |
| 2200 |
return True |
| 2201 |
if fallback: |
| 2202 |
return name in DEFAULTS |
| 2203 |
return False |
| 2204 |
|
| 2205 |
|
| 2206 |
def get_ccxx_testchart() -> str: |
| 2207 |
"""Get the path to the default chart for CCMX/CCSS creation. |
| 2208 |
|
| 2209 |
Returns: |
| 2210 |
str: The path to the default test chart file. |
| 2211 |
""" |
| 2212 |
return get_data_path( |
| 2213 |
os.path.join("ti1", DEFAULTS["colorimeter_correction.testchart"]) |
| 2214 |
) |
| 2215 |
|
| 2216 |
|
| 2217 |
def get_current_profile(include_display_profile: bool = False) -> None | ICCProfile: |
| 2218 |
"""Get the currently selected profile (if any). |
| 2219 |
|
| 2220 |
Args: |
| 2221 |
include_display_profile (bool, optional): If True, also return the display |
| 2222 |
profile if no calibration file is set. Defaults to False. |
| 2223 |
|
| 2224 |
Returns: |
| 2225 |
None | ICCProfile: The ICC profile if available, otherwise None. |
| 2226 |
""" |
| 2227 |
path = getcfg("calibration.file", False) |
| 2228 |
if path: |
| 2229 |
from DisplayCAL.icc_profile import ICCProfile, ICCProfileInvalidError |
| 2230 |
|
| 2231 |
try: |
| 2232 |
profile = ICCProfile(path, use_cache=True) |
| 2233 |
except (OSError, ICCProfileInvalidError): |
| 2234 |
return None |
| 2235 |
return profile |
| 2236 |
if include_display_profile: |
| 2237 |
return get_display_profile() |
| 2238 |
return None |
| 2239 |
|
| 2240 |
|
| 2241 |
def get_display_profile(display_no: None | int = None) -> None | ICCProfile: |
| 2242 |
"""Get the display profile for the specified display number. |
| 2243 |
|
| 2244 |
Args: |
| 2245 |
display_no (int, optional): The display number. If None, use the |
| 2246 |
configured display number. Defaults to None. |
| 2247 |
|
| 2248 |
Returns: |
| 2249 |
None | ICCProfile: The display profile if available, otherwise None. |
| 2250 |
""" |
| 2251 |
if display_no is None: |
| 2252 |
display_no = max(getcfg("display.number") - 1, 0) |
| 2253 |
if is_virtual_display(display_no): |
| 2254 |
return None |
| 2255 |
from DisplayCAL.icc_profile import get_display_profile |
| 2256 |
|
| 2257 |
try: |
| 2258 |
return get_display_profile(display_no) |
| 2259 |
except Exception: |
| 2260 |
from DisplayCAL.log import LOG |
| 2261 |
|
| 2262 |
print(f"DisplayCAL.icc_profile.get_display_profile({display_no}):", file=LOG) |
| 2263 |
|
| 2264 |
|
| 2265 |
STANDARD_PROFILES = [] |
| 2266 |
|
| 2267 |
|
| 2268 |
def get_standard_profiles(paths_only: bool = False) -> list: |
| 2269 |
"""Get a list of standard ICC profiles. |
| 2270 |
|
| 2271 |
Args: |
| 2272 |
paths_only (bool, optional): If True, return only the file paths of the |
| 2273 |
profiles. Defaults to False. |
| 2274 |
|
| 2275 |
Returns: |
| 2276 |
list: A list of standard ICC profiles or their file paths. |
| 2277 |
""" |
| 2278 |
if not STANDARD_PROFILES: |
| 2279 |
from DisplayCAL.icc_profile import ICCProfile |
| 2280 |
|
| 2281 |
# Reference profiles (Argyll + DisplayCAL) |
| 2282 |
ref_icc = get_data_path("ref", r"\.ic[cm]$") or [] |
| 2283 |
# Other profiles installed on the system |
| 2284 |
other_icc = [] |
| 2285 |
regex = re.compile(r"\.ic[cm]$", re.IGNORECASE) |
| 2286 |
for icc_dir in set(ICCPROFILES + ICCPROFILES_HOME): |
| 2287 |
for dirpath, _dirnames, basenames in os.walk(icc_dir): |
| 2288 |
for basename in filter(regex.search, basenames): |
| 2289 |
filename, ext = os.path.splitext(basename.lower()) |
| 2290 |
if ( |
| 2291 |
filename.endswith(("_bas", "_eci", "adobergb1998")) |
| 2292 |
or filename.startswith( |
| 2293 |
( |
| 2294 |
"eci-rgb", |
| 2295 |
"ecirgb", |
| 2296 |
"ekta space", |
| 2297 |
"ektaspace", |
| 2298 |
"fogra", |
| 2299 |
"gracol", |
| 2300 |
"iso", |
| 2301 |
"lstar-", |
| 2302 |
"pso", |
| 2303 |
"prophoto", |
| 2304 |
"psr_", |
| 2305 |
"psrgravure", |
| 2306 |
"snap", |
| 2307 |
"srgb", |
| 2308 |
"swop", |
| 2309 |
) |
| 2310 |
) |
| 2311 |
or filename |
| 2312 |
in ( |
| 2313 |
"applergb", |
| 2314 |
"bestrgb", |
| 2315 |
"betargb", |
| 2316 |
"brucergb", |
| 2317 |
"ciergb", |
| 2318 |
"cie-rgb", |
| 2319 |
"colormatchrgb", |
| 2320 |
"donrgb", |
| 2321 |
"widegamutrgb", |
| 2322 |
) |
| 2323 |
): |
| 2324 |
other_icc.append(os.path.join(dirpath, basename)) |
| 2325 |
|
| 2326 |
# Ensure ref_icc is a list |
| 2327 |
ref_icc = ref_icc if isinstance(ref_icc, list) else [ref_icc] |
| 2328 |
|
| 2329 |
for path in ref_icc + other_icc: |
| 2330 |
try: |
| 2331 |
profile = ICCProfile(path, load=False, use_cache=True) |
| 2332 |
except OSError: |
| 2333 |
pass |
| 2334 |
except Exception as exception: |
| 2335 |
print(exception) |
| 2336 |
else: |
| 2337 |
if ( |
| 2338 |
profile.version < 4 |
| 2339 |
and profile.profileClass != b"nmcl" |
| 2340 |
and profile.colorSpace != b"GRAY" |
| 2341 |
and profile.connectionColorSpace in (b"Lab", b"XYZ") |
| 2342 |
): |
| 2343 |
STANDARD_PROFILES.append(profile) |
| 2344 |
if paths_only: |
| 2345 |
return [profile.filename for profile in STANDARD_PROFILES] |
| 2346 |
return STANDARD_PROFILES |
| 2347 |
|
| 2348 |
|
| 2349 |
def get_total_patches( |
| 2350 |
white_patches: None | int = None, |
| 2351 |
black_patches: None | int = None, |
| 2352 |
single_channel_patches: None | int = None, |
| 2353 |
gray_patches: None | int = None, |
| 2354 |
multi_steps: None | int = None, |
| 2355 |
multi_bcc_steps: None | int = None, |
| 2356 |
fullspread_patches: None | int = None, |
| 2357 |
) -> int: |
| 2358 |
"""Calculate the total number of patches in a test chart. |
| 2359 |
|
| 2360 |
Args: |
| 2361 |
white_patches (int, optional): Number of white patches. Defaults to None. |
| 2362 |
black_patches (int, optional): Number of black patches. Defaults to None. |
| 2363 |
single_channel_patches (int, optional): Number of single channel patches. |
| 2364 |
Defaults to None. |
| 2365 |
gray_patches (int, optional): Number of gray patches. Defaults to None. |
| 2366 |
multi_steps (int, optional): Number of multi steps. Defaults to None. |
| 2367 |
multi_bcc_steps (int, optional): Number of multi BCC steps. Defaults to |
| 2368 |
None. |
| 2369 |
fullspread_patches (int, optional): Number of full spread patches. |
| 2370 |
Defaults to None. |
| 2371 |
|
| 2372 |
Returns: |
| 2373 |
int: Total number of patches. |
| 2374 |
""" |
| 2375 |
white_patches = ( |
| 2376 |
getcfg("tc_white_patches") if white_patches is None else white_patches |
| 2377 |
) |
| 2378 |
black_patches = ( |
| 2379 |
getcfg("tc_black_patches") |
| 2380 |
if (black_patches is None and getcfg("argyll.version") >= "1.6") |
| 2381 |
else black_patches |
| 2382 |
) |
| 2383 |
single_channel_patches = ( |
| 2384 |
getcfg("tc_single_channel_patches") |
| 2385 |
if single_channel_patches is None |
| 2386 |
else single_channel_patches |
| 2387 |
) |
| 2388 |
single_channel_patches_total = single_channel_patches * 3 |
| 2389 |
gray_patches = getcfg("tc_gray_patches") if gray_patches is None else gray_patches |
| 2390 |
gray_patches = ( |
| 2391 |
2 |
| 2392 |
if (gray_patches == 0 and single_channel_patches > 0 and white_patches > 0) |
| 2393 |
else gray_patches |
| 2394 |
) |
| 2395 |
multi_steps = getcfg("tc_multi_steps") if multi_steps is None else multi_steps |
| 2396 |
multi_bcc_steps = ( |
| 2397 |
getcfg("tc_multi_bcc_steps") |
| 2398 |
if (multi_bcc_steps is None and getcfg("argyll.version") >= "1.6") |
| 2399 |
else multi_bcc_steps |
| 2400 |
) |
| 2401 |
fullspread_patches = ( |
| 2402 |
getcfg("tc_fullspread_patches") |
| 2403 |
if fullspread_patches is None |
| 2404 |
else fullspread_patches |
| 2405 |
) |
| 2406 |
total_patches = 0 |
| 2407 |
if multi_steps > 1: |
| 2408 |
( |
| 2409 |
gray_patches, |
| 2410 |
white_patches, |
| 2411 |
single_channel_patches_total, |
| 2412 |
total_patches, |
| 2413 |
) = adjust_gray_patches_count( |
| 2414 |
single_channel_patches, |
| 2415 |
single_channel_patches_total, |
| 2416 |
gray_patches, |
| 2417 |
white_patches, |
| 2418 |
total_patches, |
| 2419 |
multi_steps, |
| 2420 |
multi_bcc_steps, |
| 2421 |
) |
| 2422 |
elif gray_patches > 1: |
| 2423 |
white_patches -= 1 # white always in gray patches |
| 2424 |
single_channel_patches_total -= 3 # black always in gray patches |
| 2425 |
elif single_channel_patches_total: |
| 2426 |
# black always only once in single channel patches |
| 2427 |
single_channel_patches_total -= 2 |
| 2428 |
total_patches += ( |
| 2429 |
max(0, white_patches) |
| 2430 |
+ max(0, single_channel_patches_total) |
| 2431 |
+ max(0, gray_patches) |
| 2432 |
+ fullspread_patches |
| 2433 |
) |
| 2434 |
if black_patches: |
| 2435 |
if gray_patches > 1 or single_channel_patches_total or multi_steps: |
| 2436 |
black_patches -= 1 # black always in other patches |
| 2437 |
total_patches += black_patches |
| 2438 |
return total_patches |
| 2439 |
|
| 2440 |
|
| 2441 |
def adjust_gray_patches_count( |
| 2442 |
single_channel_patches: int, |
| 2443 |
single_channel_patches_total: int, |
| 2444 |
gray_patches: int, |
| 2445 |
white_patches: int, |
| 2446 |
total_patches: int, |
| 2447 |
multi_steps: int, |
| 2448 |
multi_bcc_steps: int, |
| 2449 |
) -> tuple[int, int]: |
| 2450 |
"""Adjust gray patches count based on multi steps and single channel patches. |
| 2451 |
|
| 2452 |
Args: |
| 2453 |
single_channel_patches (int): Number of single channel patches. |
| 2454 |
single_channel_patches_total (int): Total number of single channel |
| 2455 |
patches. |
| 2456 |
white_patches (int): Number of white patches. |
| 2457 |
gray_patches (int): Number of gray patches. |
| 2458 |
total_patches (int): Total number of patches. |
| 2459 |
multi_steps (int): Number of multi steps. |
| 2460 |
multi_bcc_steps (int): Number of multi BCC steps. |
| 2461 |
|
| 2462 |
Returns: |
| 2463 |
tupel[int, int, int, int]: A tuple containing the adjusted number of |
| 2464 |
gray patches, the white patches, the total number of single channel |
| 2465 |
patches and the total number of patches. |
| 2466 |
""" |
| 2467 |
multi_patches = int(math.pow(multi_steps, 3)) |
| 2468 |
if multi_bcc_steps > 1: |
| 2469 |
multi_patches += int(math.pow(multi_bcc_steps - 1, 3)) |
| 2470 |
total_patches += multi_patches |
| 2471 |
white_patches -= 1 # white always in multi channel patches |
| 2472 |
|
| 2473 |
multi_step = 255.0 / (multi_steps - 1) |
| 2474 |
multi_values = [] |
| 2475 |
multi_bcc_values = [] |
| 2476 |
if multi_bcc_steps > 1: |
| 2477 |
multi_bcc_step = multi_step |
| 2478 |
multi_values.extend(str(multi_bcc_step * i) for i in range(multi_bcc_steps)) |
| 2479 |
multi_bcc_values.extend( |
| 2480 |
str(multi_bcc_step / 2.0 * i) for i in range(multi_bcc_steps * 2 - 1) |
| 2481 |
) |
| 2482 |
else: |
| 2483 |
multi_values.extend(str(multi_step * i) for i in range(multi_steps)) |
| 2484 |
if single_channel_patches > 1: |
| 2485 |
single_channel_step = 255.0 / (single_channel_patches - 1) |
| 2486 |
for i in range(single_channel_patches): |
| 2487 |
if str(single_channel_step * i) in multi_values: |
| 2488 |
single_channel_patches_total -= 3 |
| 2489 |
if gray_patches > 1: |
| 2490 |
gray_step = 255.0 / (gray_patches - 1) |
| 2491 |
for i in range(gray_patches): |
| 2492 |
if ( |
| 2493 |
str(gray_step * i) in multi_values |
| 2494 |
or str(gray_step * i) in multi_bcc_values |
| 2495 |
): |
| 2496 |
gray_patches -= 1 |
| 2497 |
return ( |
| 2498 |
gray_patches, |
| 2499 |
white_patches, |
| 2500 |
single_channel_patches_total, |
| 2501 |
total_patches, |
| 2502 |
) |
| 2503 |
|
| 2504 |
|
| 2505 |
def get_verified_path(cfg_item_name: str, path: None | str = None) -> tuple[str, str]: |
| 2506 |
"""Verify and return directory and filename for a user cfg path or given path. |
| 2507 |
|
| 2508 |
Args: |
| 2509 |
cfg_item_name (str): Config item name to retrieve the path. |
| 2510 |
path (str, optional): Path to verify. Defaults to None. |
| 2511 |
|
| 2512 |
Returns: |
| 2513 |
tuple[str, str]: A tuple containing the directory and filename. |
| 2514 |
""" |
| 2515 |
default_path = path or getcfg(cfg_item_name) |
| 2516 |
default_dir = expanduseru("~") |
| 2517 |
default_file = "" |
| 2518 |
if default_path: |
| 2519 |
if os.path.exists(default_path): |
| 2520 |
default_dir, default_file = ( |
| 2521 |
os.path.dirname(default_path), |
| 2522 |
os.path.basename(default_path), |
| 2523 |
) |
| 2524 |
elif DEFAULTS.get(cfg_item_name) and os.path.exists(DEFAULTS[cfg_item_name]): |
| 2525 |
default_dir, default_file = ( |
| 2526 |
os.path.dirname(DEFAULTS[cfg_item_name]), |
| 2527 |
os.path.basename(DEFAULTS[cfg_item_name]), |
| 2528 |
) |
| 2529 |
elif os.path.exists(os.path.dirname(default_path)): |
| 2530 |
default_dir = os.path.dirname(default_path) |
| 2531 |
return default_dir, default_file |
| 2532 |
|
| 2533 |
|
| 2534 |
def is_ccxx_testchart(testchart: None | str = None) -> bool: |
| 2535 |
"""Check whether the testchart is the default chart for CCMX/CCSS creation. |
| 2536 |
|
| 2537 |
Args: |
| 2538 |
testchart (None | str): The testchart to check. |
| 2539 |
If not provided, the default testchart will be used. |
| 2540 |
|
| 2541 |
Returns: |
| 2542 |
bool: True if the testchart is the default chart for CCMX/CCSS creation, |
| 2543 |
False otherwise. |
| 2544 |
""" |
| 2545 |
testchart = testchart or getcfg("testchart.file") |
| 2546 |
return testchart == get_ccxx_testchart() |
| 2547 |
|
| 2548 |
|
| 2549 |
def is_profile( |
| 2550 |
filename: None | str = None, include_display_profile: bool = False |
| 2551 |
) -> bool: |
| 2552 |
"""Check if the given filename is a valid ICC profile. |
| 2553 |
|
| 2554 |
Args: |
| 2555 |
filename (None | str): The filename to check. |
| 2556 |
If not provided, the default calibration file will be used. |
| 2557 |
include_display_profile (bool): Whether to include the display profile |
| 2558 |
in the check. Defaults to False. |
| 2559 |
|
| 2560 |
Returns: |
| 2561 |
bool: True if the filename is a valid ICC profile, |
| 2562 |
False otherwise. |
| 2563 |
""" |
| 2564 |
filename = filename or getcfg("calibration.file", False) |
| 2565 |
if filename: |
| 2566 |
if os.path.exists(filename): |
| 2567 |
from DisplayCAL.icc_profile import ICCProfile, ICCProfileInvalidError |
| 2568 |
|
| 2569 |
try: |
| 2570 |
ICCProfile(filename, use_cache=True) |
| 2571 |
except (OSError, ICCProfileInvalidError): |
| 2572 |
pass |
| 2573 |
else: |
| 2574 |
return True |
| 2575 |
elif include_display_profile: |
| 2576 |
return bool(get_display_profile()) |
| 2577 |
return False |
| 2578 |
|
| 2579 |
|
| 2580 |
def makecfgdir(which: None | str = None, worker: None | Worker = None) -> bool: |
| 2581 |
"""Create the configuration directory. |
| 2582 |
|
| 2583 |
Args: |
| 2584 |
which (None | str): The type of configuration directory to create. |
| 2585 |
Can be "user" or "system". Defaults to "user". |
| 2586 |
worker (None | Worker): The worker instance to use for executing |
| 2587 |
commands. Defaults to None. |
| 2588 |
|
| 2589 |
Returns: |
| 2590 |
bool: True if the configuration directory was created successfully, |
| 2591 |
False otherwise. |
| 2592 |
""" |
| 2593 |
if which is None: |
| 2594 |
which = "user" |
| 2595 |
|
| 2596 |
if which == "user": |
| 2597 |
if not os.path.exists(CONFIG_HOME): |
| 2598 |
try: |
| 2599 |
os.makedirs(CONFIG_HOME) |
| 2600 |
except Exception as exception: |
| 2601 |
print( |
| 2602 |
"Warning - could not create configuration directory " |
| 2603 |
f"'{CONFIG_HOME}': {exception}" |
| 2604 |
) |
| 2605 |
return False |
| 2606 |
elif not os.path.exists(CONFIG_SYS): |
| 2607 |
try: |
| 2608 |
if sys.platform == "win32": |
| 2609 |
os.makedirs(CONFIG_SYS) |
| 2610 |
else: |
| 2611 |
result = worker.exec_cmd( |
| 2612 |
"mkdir", |
| 2613 |
["-p", CONFIG_SYS], |
| 2614 |
capture_output=True, |
| 2615 |
low_contrast=False, |
| 2616 |
skip_scripts=True, |
| 2617 |
silent=True, |
| 2618 |
asroot=True, |
| 2619 |
) |
| 2620 |
if isinstance(result, Exception): |
| 2621 |
raise result |
| 2622 |
except Exception as exception: |
| 2623 |
print( |
| 2624 |
"Warning - could not create configuration directory " |
| 2625 |
f"'{CONFIG_SYS}': {exception}" |
| 2626 |
) |
| 2627 |
return False |
| 2628 |
return True |
| 2629 |
|
| 2630 |
|
| 2631 |
CFGINITED = {} |
| 2632 |
|
| 2633 |
# A legitimate config file is a few KB at most. Anything past this is |
| 2634 |
# treated as corrupted rather than risking an out-of-memory parse (issue |
| 2635 |
# #828). |
| 2636 |
MAX_CFG_FILE_SIZE = 10 * 1024 * 1024 |
| 2637 |
|
| 2638 |
|
| 2639 |
def initcfg( |
| 2640 |
module: None | str = None, |
| 2641 |
cfg: configparser.ConfigParser = CFG, |
| 2642 |
force_load: bool = False, |
| 2643 |
) -> None: |
| 2644 |
"""Initialize the configuration. |
| 2645 |
|
| 2646 |
Read in settings if the configuration file exists, else create the |
| 2647 |
settings directory if nonexistent. |
| 2648 |
|
| 2649 |
Args: |
| 2650 |
module (None | str): The module name to use for the configuration. |
| 2651 |
If None, use the default application name. |
| 2652 |
Defaults to None. |
| 2653 |
cfg (configparser.ConfigParser): The configuration parser instance. |
| 2654 |
Defaults to the global CFG instance. |
| 2655 |
force_load (bool): If True, force reloading the configuration files. |
| 2656 |
Defaults to False. |
| 2657 |
""" |
| 2658 |
cfgbasename = f"{APPBASENAME}-{module}" if module else APPBASENAME |
| 2659 |
makecfgdir() |
| 2660 |
cfg_full_path = os.path.join(CONFIG_HOME, f"{cfgbasename}.ini") |
| 2661 |
if os.path.exists(CONFIG_HOME) and not os.path.exists(cfg_full_path): |
| 2662 |
if not cfg.has_section(configparser.DEFAULTSECT): |
| 2663 |
# No Default section, add it... |
| 2664 |
cfg.add_section(configparser.DEFAULTSECT) |
| 2665 |
# Set default preset |
| 2666 |
setcfg("calibration.file", DEFAULTS["calibration.file"], cfg=cfg) |
| 2667 |
|
| 2668 |
# Read cfg |
| 2669 |
cfgnames = ( |
| 2670 |
[APPBASENAME, cfgbasename] |
| 2671 |
if module |
| 2672 |
else [APPBASENAME, f"{APPBASENAME}-testchart-editor"] |
| 2673 |
) |
| 2674 |
cfgroots = ( |
| 2675 |
[CONFIG_HOME] if module == "apply-profiles" else [CONFIG_HOME, CONFIG_SYS] |
| 2676 |
) |
| 2677 |
cfgfiles = fetch_config_files(cfgnames, cfgroots, force_load) |
| 2678 |
if not cfgfiles: |
| 2679 |
return |
| 2680 |
if not module: |
| 2681 |
# Make most recent file take precedence |
| 2682 |
cfgfiles.sort(key=lambda cfgfile: CFGINITED.get(cfgfile)) |
| 2683 |
try: |
| 2684 |
# writecfg() always writes UTF-8 (str.encode() defaults to it |
| 2685 |
# regardless of locale). Without an explicit encoding here, read() |
| 2686 |
# falls back to the OS locale's preferred encoding, which on |
| 2687 |
# Windows without the "Beta: UTF-8" system-locale option is the |
| 2688 |
# legacy ANSI codepage (e.g. cp1252). That mismatch mis-decodes |
| 2689 |
# any non-ASCII option value on every read, and since writecfg() |
| 2690 |
# then re-encodes the already-garbled string as UTF-8, the mojibake |
| 2691 |
# compounds on every read/write cycle (issue #828). |
| 2692 |
cfg.read(cfgfiles, encoding="utf-8") |
| 2693 |
# This won't raise an exception if the file does not exist, |
| 2694 |
# only if it can't be parsed |
| 2695 |
except Exception: |
| 2696 |
print( |
| 2697 |
"Warning - could not parse configuration files:\n{}".format( |
| 2698 |
"\n".join(cfgfiles) |
| 2699 |
) |
| 2700 |
) |
| 2701 |
# Fix Python 2.7 ConfigParser option values being lists instead of |
| 2702 |
# strings in case of a ParsingError. http://bugs.python.org/issue24142 |
| 2703 |
all_sections = [configparser.DEFAULTSECT] |
| 2704 |
all_sections.extend(cfg.sections()) |
| 2705 |
for section in all_sections: |
| 2706 |
for name, val in cfg.items(section): |
| 2707 |
if isinstance(val, list): |
| 2708 |
cfg.set(section, name, "\n".join(val)) |
| 2709 |
finally: |
| 2710 |
if not module: |
| 2711 |
if getcfg("lang", fallback=False, cfg=cfg) is None: |
| 2712 |
setcfg("lang", DEFAULTS["lang"], cfg=cfg) |
| 2713 |
if getcfg("calibration.ambient_viewcond_adjust", fallback=False, cfg=cfg) is None: |
| 2714 |
setcfg( |
| 2715 |
"calibration.ambient_viewcond_adjust", |
| 2716 |
DEFAULTS["calibration.ambient_viewcond_adjust"], |
| 2717 |
cfg=cfg, |
| 2718 |
) |
| 2719 |
if not getcfg("calibration.ambient_viewcond_adjust", cfg=cfg): |
| 2720 |
# Reset to default |
| 2721 |
setcfg("calibration.ambient_viewcond_adjust.lux", None, cfg=cfg) |
| 2722 |
if getcfg("profile.save_path", fallback=False, cfg=cfg) is None: |
| 2723 |
setcfg("profile.save_path", STORAGE, cfg=cfg) |
| 2724 |
|
| 2725 |
|
| 2726 |
def fetch_config_files( |
| 2727 |
cfgnames: list[str], |
| 2728 |
cfgroots: list[str], |
| 2729 |
force_load: bool = False, |
| 2730 |
) -> list[str]: |
| 2731 |
"""Fetch configuration files based on the provided names and roots. |
| 2732 |
|
| 2733 |
Args: |
| 2734 |
cfgnames (list): List of configuration names to look for. |
| 2735 |
cfgroots (list): List of directories to search for configuration files. |
| 2736 |
force_load (bool): Whether to force reloading the configuration files. |
| 2737 |
|
| 2738 |
Returns: |
| 2739 |
list[str]: A list of configuration file paths that were found and |
| 2740 |
successfully loaded. |
| 2741 |
""" |
| 2742 |
cfgfiles = [] |
| 2743 |
for cfgname in cfgnames: |
| 2744 |
for cfgroot in cfgroots: |
| 2745 |
cfgfile = os.path.join(cfgroot, f"{cfgname}.ini") |
| 2746 |
if not os.path.isfile(cfgfile): |
| 2747 |
continue |
| 2748 |
try: |
| 2749 |
stat = os.stat(cfgfile) |
| 2750 |
mtime = stat.st_mtime |
| 2751 |
except OSError as exception: |
| 2752 |
print(f"Warning - os.stat('{cfgfile}') failed: {exception}") |
| 2753 |
break |
| 2754 |
if stat.st_size > MAX_CFG_FILE_SIZE: |
| 2755 |
# A config file this large can only be the result of |
| 2756 |
# corruption -- some option value grew unbounded, e.g. by |
| 2757 |
# repeated appends of mis-decoded text (issue #828). |
| 2758 |
# Parsing it would blow up memory and likely crash, so |
| 2759 |
# quarantine it instead of loading it. |
| 2760 |
quarantined = f"{cfgfile}.corrupt-{int(time.time())}" |
| 2761 |
print( |
| 2762 |
f"Warning - '{cfgfile}' is {stat.st_size} bytes, " |
| 2763 |
f"which looks corrupted. Moving it to '{quarantined}' " |
| 2764 |
"and falling back to defaults." |
| 2765 |
) |
| 2766 |
with contextlib.suppress(OSError): |
| 2767 |
os.replace(cfgfile, quarantined) |
| 2768 |
break |
| 2769 |
last_checked = CFGINITED.get(cfgfile) |
| 2770 |
if force_load or mtime != last_checked: |
| 2771 |
CFGINITED[cfgfile] = mtime |
| 2772 |
cfgfiles.append(cfgfile) |
| 2773 |
msg = ( |
| 2774 |
"Force loading" |
| 2775 |
if force_load |
| 2776 |
else "Reloading" |
| 2777 |
if last_checked |
| 2778 |
else "Loading" |
| 2779 |
) |
| 2780 |
print(msg, cfgfile) |
| 2781 |
# Make user config take precedence |
| 2782 |
break |
| 2783 |
return cfgfiles |
| 2784 |
|
| 2785 |
|
| 2786 |
def validate_value_type( |
| 2787 |
name: str, |
| 2788 |
value: Any, # noqa: ANN401 |
| 2789 |
) -> Any: # noqa: ANN401 |
| 2790 |
"""Check for invalid types and return default if wrong type. |
| 2791 |
|
| 2792 |
Args: |
| 2793 |
name (str): The name of the configuration option. |
| 2794 |
value (Any): The value of the configuration option. |
| 2795 |
|
| 2796 |
Returns: |
| 2797 |
Any: The value of the configuration option, or the default value if the |
| 2798 |
option is not set or has an invalid type. |
| 2799 |
""" |
| 2800 |
if (name != "trc" or value not in VALID_VALUES["trc"]) and isinstance( |
| 2801 |
DEFAULTS.get(name), (int, float, Decimal) |
| 2802 |
): |
| 2803 |
value = validate_numeric_value(name, value) |
| 2804 |
elif name.startswith("dimensions.measureframe"): |
| 2805 |
value = validate_measureframe_dimensions_value(name, value) |
| 2806 |
elif name == "profile.quality" and getcfg("profile.type") in ("g", "G"): |
| 2807 |
# default to high quality for gamma + matrix |
| 2808 |
value = "h" |
| 2809 |
elif name == "trc.type" and getcfg("trc") in VALID_VALUES["trc"]: |
| 2810 |
value = "g" |
| 2811 |
elif name in VALID_VALUES and value not in VALID_VALUES[name]: |
| 2812 |
debug_print(f"Invalid config value for {name}: {value}", end=" ") |
| 2813 |
value = None |
| 2814 |
elif name == "copyright": |
| 2815 |
value = validate_copyright_value(name, value) |
| 2816 |
elif name == "measurement_mode": |
| 2817 |
value = validate_measurement_mode_value(name, value) |
| 2818 |
|
| 2819 |
return value |
| 2820 |
|
| 2821 |
|
| 2822 |
def validate_numeric_value( |
| 2823 |
name: str, |
| 2824 |
value: int | float | Decimal, # noqa: PYI041 |
| 2825 |
) -> int | float | Decimal: |
| 2826 |
"""Validate a numeric value against its default and valid ranges. |
| 2827 |
|
| 2828 |
Args: |
| 2829 |
name (str): The name of the configuration option. |
| 2830 |
value (int | float | Decimal): The numeric value to validate. |
| 2831 |
|
| 2832 |
Returns: |
| 2833 |
int | float | Decimal: The validated value, or the default value if |
| 2834 |
validation fails. |
| 2835 |
""" |
| 2836 |
defval = DEFAULTS.get(name) |
| 2837 |
deftype = type(defval) |
| 2838 |
try: |
| 2839 |
value = deftype(value) |
| 2840 |
except (ValueError, TypeError): |
| 2841 |
value = defval |
| 2842 |
else: |
| 2843 |
valid_range = VALID_RANGES.get(name) |
| 2844 |
if valid_range: |
| 2845 |
value = min(max(valid_range[0], value), valid_range[1]) |
| 2846 |
elif name in VALID_VALUES and value not in VALID_VALUES[name]: |
| 2847 |
value = defval |
| 2848 |
return value |
| 2849 |
|
| 2850 |
|
| 2851 |
def validate_measureframe_dimensions_value(name: str, value: str) -> str: |
| 2852 |
"""Validate the measure frame dimensions value. |
| 2853 |
|
| 2854 |
Args: |
| 2855 |
name (str): The name of the configuration option. |
| 2856 |
value (str): The value of the configuration option. |
| 2857 |
|
| 2858 |
Returns: |
| 2859 |
str: The validated measure frame dimensions value. |
| 2860 |
""" |
| 2861 |
try: |
| 2862 |
value = [max(0, float(n)) for n in value.split(",")] |
| 2863 |
if len(value) != 3: |
| 2864 |
raise ValueError |
| 2865 |
except ValueError: |
| 2866 |
value = DEFAULTS[name] |
| 2867 |
else: |
| 2868 |
value[0] = min(value[0], 1) |
| 2869 |
value[1] = min(value[1], 1) |
| 2870 |
value[2] = min(value[2], 50) |
| 2871 |
value = ",".join([str(n) for n in value]) |
| 2872 |
|
| 2873 |
return value |
| 2874 |
|
| 2875 |
|
| 2876 |
def validate_copyright_value(name: str, value: str) -> str: |
| 2877 |
"""Validate the copyright value. |
| 2878 |
|
| 2879 |
Args: |
| 2880 |
name (str): The name of the configuration option. |
| 2881 |
value (str): The value of the configuration option. |
| 2882 |
|
| 2883 |
Returns: |
| 2884 |
str: The validated copyright value. |
| 2885 |
""" |
| 2886 |
if name != "copyright": |
| 2887 |
return value |
| 2888 |
|
| 2889 |
# Make sure DisplayCAL and Argyll version are up-to-date |
| 2890 |
defval = DEFAULTS.get(name) |
| 2891 |
pattern = re.compile(rf"({APPNAME}(?:\s*v(?:ersion|\.)?)?\s*)\d+(?:\.\d+)*", re.I) |
| 2892 |
repl = create_replace_function("\\1%s", VERSION_STRING) |
| 2893 |
value = re.sub(pattern, repl, value) |
| 2894 |
if APPBASENAME != APPNAME: |
| 2895 |
pattern = re.compile( |
| 2896 |
rf"({APPBASENAME}(?:\s*v(?:ersion|\.)?)?\s*)\d+(?:\.\d+)*", |
| 2897 |
re.I, |
| 2898 |
) |
| 2899 |
repl = create_replace_function("\\1%s", VERSION_STRING) |
| 2900 |
value = re.sub(pattern, repl, value) |
| 2901 |
pattern = re.compile( |
| 2902 |
r"(Argyll(?:\s*CMS)?)((?:\s*v(?:ersion|\.)?)?\s*)\d+(?:\.\d+)*", |
| 2903 |
re.I, |
| 2904 |
) |
| 2905 |
repl = ( |
| 2906 |
create_replace_function("\\1\\2%s", defval.split()[-1]) |
| 2907 |
if defval.split()[-1] != "CMS" |
| 2908 |
else "\\1" |
| 2909 |
) |
| 2910 |
return re.sub(pattern, repl, value) |
| 2911 |
|
| 2912 |
|
| 2913 |
def validate_measurement_mode_value(name: str, value: str) -> str: |
| 2914 |
"""Validate the measurement mode value. |
| 2915 |
|
| 2916 |
Args: |
| 2917 |
name (str): The name of the configuration option. |
| 2918 |
value (str): The value of the configuration option. |
| 2919 |
|
| 2920 |
Returns: |
| 2921 |
str: The validated measurement mode value. |
| 2922 |
""" |
| 2923 |
if name == "measurement_mode": |
| 2924 |
# Map n and r measurement modes to canonical l and c |
| 2925 |
# the inverse mapping happens per-instrument in |
| 2926 |
# Worker.add_measurement_features(). |
| 2927 |
# That way we can have compatibility with old and current |
| 2928 |
# Argyll CMS |
| 2929 |
value = {"n": "l", "r": "c"}.get(value, value) |
| 2930 |
return value |
| 2931 |
|
| 2932 |
|
| 2933 |
def set_default_app_dpi() -> None: |
| 2934 |
"""Set application DPI.""" |
| 2935 |
# Only call this after creating the wx.App object! |
| 2936 |
global DPISET |
| 2937 |
if DPISET or getcfg("app.dpi", False): |
| 2938 |
DPISET = True |
| 2939 |
return |
| 2940 |
|
| 2941 |
# HighDPI support |
| 2942 |
from DisplayCAL.wx_addons import wx |
| 2943 |
|
| 2944 |
DPISET = True |
| 2945 |
if sys.platform in ("darwin", "win32"): |
| 2946 |
# Determine screen DPI |
| 2947 |
dpi = wx.ScreenDC().GetPPI()[0] |
| 2948 |
else: |
| 2949 |
# Linux |
| 2950 |
from DisplayCAL.util_os import which |
| 2951 |
|
| 2952 |
txt_scale = None |
| 2953 |
# XDG_CURRENT_DESKTOP delimiter is colon (':') |
| 2954 |
desktop = os.getenv("XDG_CURRENT_DESKTOP", "").split(":") |
| 2955 |
if "gtk2" in wx.PlatformInfo: |
| 2956 |
txt_scale = get_hidpi_scaling_factor() |
| 2957 |
elif desktop[0] == "KDE": |
| 2958 |
pass |
| 2959 |
# Nothing to do |
| 2960 |
elif which("gsettings"): |
| 2961 |
import subprocess as sp |
| 2962 |
|
| 2963 |
p = sp.Popen( |
| 2964 |
[ # noqa: S607 |
| 2965 |
"gsettings", |
| 2966 |
"get", |
| 2967 |
"org.gnome.desktop.interface", |
| 2968 |
"text-scaling-factor", |
| 2969 |
], |
| 2970 |
stdin=sp.PIPE, |
| 2971 |
stdout=sp.PIPE, |
| 2972 |
stderr=sp.PIPE, |
| 2973 |
) |
| 2974 |
factor, stderr = p.communicate() |
| 2975 |
with contextlib.suppress(ValueError): |
| 2976 |
txt_scale = float(factor) |
| 2977 |
dpi = get_default_dpi() |
| 2978 |
if txt_scale: |
| 2979 |
dpi = round(dpi * txt_scale) |
| 2980 |
DEFAULTS["app.dpi"] = dpi |
| 2981 |
DPISET = True |
| 2982 |
|
| 2983 |
|
| 2984 |
def get_hidpi_scaling_factor() -> float: |
| 2985 |
"""Get the scaling factor for high DPI displays. |
| 2986 |
|
| 2987 |
Returns: |
| 2988 |
float: The scaling factor for high DPI displays. |
| 2989 |
""" |
| 2990 |
if sys.platform in ("darwin", "win32"): |
| 2991 |
return 1.0 # Handled via app DPI |
| 2992 |
|
| 2993 |
# Linux |
| 2994 |
from DisplayCAL.util_os import which |
| 2995 |
|
| 2996 |
dpi = get_hidpi_scaling_factor_from_xrdb() |
| 2997 |
if dpi is not None: |
| 2998 |
return dpi |
| 2999 |
|
| 3000 |
factor = None |
| 3001 |
|
| 3002 |
# XDG_CURRENT_DESKTOP delimiter is colon (':') |
| 3003 |
desktop = os.getenv("XDG_CURRENT_DESKTOP", "").split(":") |
| 3004 |
if desktop[0] == "KDE": |
| 3005 |
factor = get_hidpi_scaling_factor_from_kde() |
| 3006 |
|
| 3007 |
if not factor and which("gsettings"): |
| 3008 |
factor = get_hidpi_scaling_factor_from_gnome() |
| 3009 |
|
| 3010 |
if factor is not None: |
| 3011 |
try: |
| 3012 |
factor = float(factor) |
| 3013 |
except ValueError: |
| 3014 |
factor = None |
| 3015 |
return factor |
| 3016 |
|
| 3017 |
|
| 3018 |
def get_hidpi_scaling_factor_from_xrdb() -> float: |
| 3019 |
"""Get the scaling factor for high DPI displays from xrdb. |
| 3020 |
|
| 3021 |
Returns: |
| 3022 |
float: The scaling factor for high DPI displays. |
| 3023 |
""" |
| 3024 |
from DisplayCAL.util_os import which |
| 3025 |
|
| 3026 |
if not which("xrdb"): |
| 3027 |
return None |
| 3028 |
import subprocess as sp |
| 3029 |
|
| 3030 |
p = sp.Popen( |
| 3031 |
["xrdb", "-query"], # noqa: S607 |
| 3032 |
stdin=sp.PIPE, |
| 3033 |
stdout=sp.PIPE, |
| 3034 |
stderr=sp.PIPE, |
| 3035 |
) |
| 3036 |
# Format: 'Xft.dpi: 192' |
| 3037 |
stdout, _ = p.communicate() |
| 3038 |
for line in stdout.splitlines(): |
| 3039 |
line = line.decode() |
| 3040 |
if line.startswith("Xft.dpi:"): |
| 3041 |
split = line.split() |
| 3042 |
dpi = split[-1] |
| 3043 |
try: |
| 3044 |
return float(dpi) / get_default_dpi() |
| 3045 |
except ValueError: |
| 3046 |
pass |
| 3047 |
|
| 3048 |
return None |
| 3049 |
|
| 3050 |
|
| 3051 |
def get_hidpi_scaling_factor_from_kde() -> None | str: |
| 3052 |
"""Get the scaling factor for high DPI displays from KDE settings. |
| 3053 |
|
| 3054 |
Returns: |
| 3055 |
None | str: The scaling factor for high DPI displays as a string if |
| 3056 |
found, otherwise None. |
| 3057 |
""" |
| 3058 |
# Two env-vars exist: QT_SCALE_FACTOR and QT_SCREEN_SCALE_FACTORS. |
| 3059 |
# According to documentation[1], the latter is 'mainly useful for debugging' |
| 3060 |
# that's not how it is used by KDE though. |
| 3061 |
# Changing display scaling via KDE settings GUI only sets |
| 3062 |
# QT_SCREEN_SCALE_FACTORS. We are thus currently ignoring QT_SCALE_FACTOR. |
| 3063 |
# [1] https://doc.qt.io/qt-5/highdpi.html |
| 3064 |
# QT_SCREEN_SCALE_FACTORS delimiter is semicolon (';') |
| 3065 |
# Format: Mapping of XrandR display names to scale factor |
| 3066 |
# e.g. 'VGA-1=1.5;VGA-2=2.0;' |
| 3067 |
# or just list of scale factors e.g. '1.5;2.0;' |
| 3068 |
screen_scale_factors = os.getenv("QT_SCREEN_SCALE_FACTORS", "").split(";") |
| 3069 |
if not screen_scale_factors: |
| 3070 |
return None |
| 3071 |
|
| 3072 |
from DisplayCAL.wx_addons import wx |
| 3073 |
|
| 3074 |
factor = None |
| 3075 |
match = False |
| 3076 |
app = wx.GetApp() |
| 3077 |
if not app: |
| 3078 |
# Use first one |
| 3079 |
return screen_scale_factors[0].split("=")[-1] |
| 3080 |
|
| 3081 |
from DisplayCAL import real_display_size_mm |
| 3082 |
|
| 3083 |
if not real_display_size_mm._displays: |
| 3084 |
real_display_size_mm.enumerate_displays() |
| 3085 |
top = app.TopWindow |
| 3086 |
if top: |
| 3087 |
tmp = False |
| 3088 |
else: |
| 3089 |
# Create temp frame if no topwindow |
| 3090 |
top = wx.Frame(None) |
| 3091 |
# Move to main window location (and thus screen) |
| 3092 |
x, y = ( |
| 3093 |
getcfg("position.x", False), |
| 3094 |
getcfg("position.y", False), |
| 3095 |
) |
| 3096 |
if None not in (x, y): |
| 3097 |
top.SetSaneGeometry(x, y) |
| 3098 |
tmp = True |
| 3099 |
# Get wx display |
| 3100 |
wx_display = top.GetDisplay() |
| 3101 |
if tmp: |
| 3102 |
# No longer need our temp frame |
| 3103 |
top.Destroy() |
| 3104 |
|
| 3105 |
# Search for matching display based on geometry |
| 3106 |
pos = wx_display.Geometry[:2] |
| 3107 |
size = wx_display.Geometry[2:] |
| 3108 |
for item in screen_scale_factors: |
| 3109 |
if not item: |
| 3110 |
break |
| 3111 |
name, factor = item.split("=", 1) if "=" in item else (None, item) |
| 3112 |
for display in real_display_size_mm._displays: |
| 3113 |
if (display.get("pos") != pos or display.get("size") != size) or ( |
| 3114 |
name and display.get("xrandr_name") != name |
| 3115 |
): |
| 3116 |
# No match |
| 3117 |
continue |
| 3118 |
# Match found |
| 3119 |
match = True |
| 3120 |
break |
| 3121 |
|
| 3122 |
if match: |
| 3123 |
break |
| 3124 |
|
| 3125 |
# Use first one |
| 3126 |
return screen_scale_factors[0].split("=")[-1] if not match else factor |
| 3127 |
|
| 3128 |
|
| 3129 |
def get_hidpi_scaling_factor_from_gnome() -> None | str: |
| 3130 |
"""Get the scaling factor for high DPI displays from gsettings. |
| 3131 |
|
| 3132 |
Returns: |
| 3133 |
None | str: The scaling factor for high DPI displays as a string. |
| 3134 |
""" |
| 3135 |
# GNOME |
| 3136 |
import subprocess as sp |
| 3137 |
|
| 3138 |
factor = None |
| 3139 |
|
| 3140 |
p = sp.Popen( |
| 3141 |
["gsettings", "get", "org.gnome.desktop.interface", "scaling-factor"], # noqa: S607 |
| 3142 |
stdin=sp.PIPE, |
| 3143 |
stdout=sp.PIPE, |
| 3144 |
stderr=sp.PIPE, |
| 3145 |
) |
| 3146 |
# Format: 'unint32 1' |
| 3147 |
stdout, _ = p.communicate() |
| 3148 |
split = stdout.split() |
| 3149 |
if split: |
| 3150 |
factor = split[-1] |
| 3151 |
|
| 3152 |
return factor |
| 3153 |
|
| 3154 |
|
| 3155 |
def setcfg(name: str, value: Any, cfg: configparser.ConfigParser = CFG) -> None: # noqa: ANN401 |
| 3156 |
"""Set an option value in the configuration. |
| 3157 |
|
| 3158 |
Args: |
| 3159 |
name (str): Configuration option name. |
| 3160 |
value (Any): Value to set for the configuration option. |
| 3161 |
cfg (configparser.ConfigParser): Configuration instance. |
| 3162 |
""" |
| 3163 |
if value is None: |
| 3164 |
cfg.remove_option(configparser.DEFAULTSECT, name) |
| 3165 |
else: |
| 3166 |
if name in ("displays", "instruments") and isinstance(value, (list, tuple)): |
| 3167 |
value = os.pathsep.join( |
| 3168 |
strtr( |
| 3169 |
v, |
| 3170 |
[ |
| 3171 |
("%", "%25"), |
| 3172 |
(os.pathsep, f"%{hex(ord(os.pathsep))[2:].upper()}"), |
| 3173 |
], |
| 3174 |
) |
| 3175 |
for v in value |
| 3176 |
) |
| 3177 |
cfg.set(configparser.DEFAULTSECT, name, value) |
| 3178 |
|
| 3179 |
|
| 3180 |
def setcfg_cond( |
| 3181 |
condition: bool, |
| 3182 |
name: str, |
| 3183 |
value: Any, # noqa: ANN401 |
| 3184 |
set_if_backup_exists: bool = False, |
| 3185 |
restore: bool = True, |
| 3186 |
) -> bool: |
| 3187 |
"""Set configuration conditionally. |
| 3188 |
|
| 3189 |
If <condition>, backup configuration option <name> if not yet backed up |
| 3190 |
and set option to <value> if backup did not previously exist or |
| 3191 |
set_if_backup_exists evaluates to True. |
| 3192 |
|
| 3193 |
If not <condition> and backed up option <name>, restore option <name> to |
| 3194 |
backed up value and discard backup if <restore> evaluates to True |
| 3195 |
|
| 3196 |
Return whether or not configuration was changed |
| 3197 |
|
| 3198 |
Args: |
| 3199 |
condition (bool): Condition to check. |
| 3200 |
name (str): Configuration option name. |
| 3201 |
value (Any): Value to set if condition is True. |
| 3202 |
set_if_backup_exists (bool): If True, set the value even if a backup exists |
| 3203 |
and the condition is True. |
| 3204 |
restore (bool): If True, restore the value from the backup if the condition |
| 3205 |
is False and a backup exists. |
| 3206 |
|
| 3207 |
Returns: |
| 3208 |
bool: True if the configuration was changed, False otherwise. |
| 3209 |
""" |
| 3210 |
changed = False |
| 3211 |
backup = getcfg(f"{name}.backup", False) |
| 3212 |
if condition: |
| 3213 |
if backup is None: |
| 3214 |
setcfg(f"{name}.backup", getcfg(name)) |
| 3215 |
if backup is None or set_if_backup_exists: |
| 3216 |
setcfg(name, value) |
| 3217 |
changed = True |
| 3218 |
elif backup is not None and restore: |
| 3219 |
setcfg(name, getcfg(f"{name}.backup")) |
| 3220 |
setcfg(f"{name}.backup", None) |
| 3221 |
changed = True |
| 3222 |
return changed |
| 3223 |
|
| 3224 |
|
| 3225 |
def writecfg( |
| 3226 |
which: str = "user", |
| 3227 |
worker: None | Worker = None, |
| 3228 |
module: None | str = None, |
| 3229 |
options: tuple[str] = (), |
| 3230 |
cfg: configparser.ConfigParser = CFG, |
| 3231 |
) -> bool: |
| 3232 |
"""Write configuration file. |
| 3233 |
|
| 3234 |
Args: |
| 3235 |
which (str): 'user' or 'system' |
| 3236 |
worker (DisplayCAL.worker.Worker): worker instance if ``which == 'system'`` |
| 3237 |
module (None | str): module name. |
| 3238 |
options (tuple[str]): options to write. |
| 3239 |
cfg (configparser.ConfigParser): configuration instance. |
| 3240 |
|
| 3241 |
Returns: |
| 3242 |
bool: True if successful, False otherwise. |
| 3243 |
""" |
| 3244 |
cfgbasename = f"{APPBASENAME}-{module}" if module else APPBASENAME |
| 3245 |
# Remove unknown options |
| 3246 |
for name, _val in cfg.items(configparser.DEFAULTSECT): |
| 3247 |
if name not in DEFAULTS: |
| 3248 |
print("Removing unknown option:", name) |
| 3249 |
setcfg(name, None) |
| 3250 |
if which == "user": |
| 3251 |
# user config - stores everything and overrides system-wide config |
| 3252 |
cfgfilename = os.path.join(CONFIG_HOME, f"{cfgbasename}.ini") |
| 3253 |
lockfilename = cfgfilename + ".lock" |
| 3254 |
try: |
| 3255 |
io = StringIO() |
| 3256 |
cfg.write(io) |
| 3257 |
io.seek(0) |
| 3258 |
lines = io.read().strip("\n").split("\n") |
| 3259 |
if options: |
| 3260 |
optionlines = [ |
| 3261 |
optionline |
| 3262 |
for optionline in lines[1:] |
| 3263 |
for option in options |
| 3264 |
if optionline.startswith(option) |
| 3265 |
] |
| 3266 |
else: |
| 3267 |
optionlines = lines[1:] |
| 3268 |
# Sorting works as long as config has only one section |
| 3269 |
lines = lines[:1] + sorted(optionlines) |
| 3270 |
data = (os.linesep.join(lines) + os.linesep).encode() |
| 3271 |
# Take an exclusive lock and write to a temp file, then |
| 3272 |
# atomically replace the real config file. Without this, two |
| 3273 |
# processes writing the config at the same time (e.g. the |
| 3274 |
# profile loader and the main app running concurrently) could |
| 3275 |
# interleave their writes and corrupt the file. |
| 3276 |
with open(lockfilename, "a+b") as lockfile: |
| 3277 |
with FileLock(lockfile, exclusive=True, blocking=True): |
| 3278 |
fd, tmpfilename = tempfile.mkstemp( |
| 3279 |
dir=CONFIG_HOME, prefix=f"{cfgbasename}.", suffix=".tmp" |
| 3280 |
) |
| 3281 |
with os.fdopen(fd, "wb") as cfgfile: |
| 3282 |
cfgfile.write(data) |
| 3283 |
os.replace(tmpfilename, cfgfilename) |
| 3284 |
except Exception as exception: |
| 3285 |
print( |
| 3286 |
"Warning - could not write user configuration file " |
| 3287 |
f"'{cfgfilename}': {exception}" |
| 3288 |
) |
| 3289 |
return False |
| 3290 |
else: |
| 3291 |
# system-wide config - only stores essentials ie. Argyll directory |
| 3292 |
cfgfilename1 = os.path.join(CONFIG_HOME, f"{cfgbasename}.local.ini") |
| 3293 |
cfgfilename2 = os.path.join(CONFIG_SYS, f"{cfgbasename}.ini") |
| 3294 |
if sys.platform == "win32": |
| 3295 |
cfgfilename = cfgfilename2 |
| 3296 |
else: |
| 3297 |
cfgfilename = cfgfilename1 |
| 3298 |
try: |
| 3299 |
if getcfg("argyll.dir"): |
| 3300 |
with open(cfgfilename, "wb") as cfgfile: |
| 3301 |
cfgfile.write( |
| 3302 |
( |
| 3303 |
"{}{}".format( |
| 3304 |
os.linesep.join( |
| 3305 |
[ |
| 3306 |
"[Default]", |
| 3307 |
f"argyll.dir = {getcfg('argyll.dir')}", |
| 3308 |
] |
| 3309 |
), |
| 3310 |
os.linesep, |
| 3311 |
) |
| 3312 |
).encode() |
| 3313 |
) |
| 3314 |
if sys.platform != "win32": |
| 3315 |
# on Linux and OS X, we write the file to the user's config dir |
| 3316 |
# then 'su mv' it to the system-wide config dir |
| 3317 |
result = worker.exec_cmd( |
| 3318 |
"mv", |
| 3319 |
["-f", cfgfilename1, cfgfilename2], |
| 3320 |
capture_output=True, |
| 3321 |
low_contrast=False, |
| 3322 |
skip_scripts=True, |
| 3323 |
silent=True, |
| 3324 |
asroot=True, |
| 3325 |
) |
| 3326 |
if isinstance(result, Exception): |
| 3327 |
raise result |
| 3328 |
except Exception as exception: |
| 3329 |
print( |
| 3330 |
"Warning - could not write system-wide configuration file " |
| 3331 |
f"'{cfgfilename2}': {exception}" |
| 3332 |
) |
| 3333 |
return False |
| 3334 |
return True |
| 3335 |
|
| 3336 |
|
| 3337 |
_init_testcharts() |
| 3338 |
RUNTYPE = runtimeconfig(PYFILE) |
| 3339 |
|
| 3340 |
|
| 3341 |
if sys.platform in ("darwin", "win32") and not os.getenv("SSL_CERT_FILE"): |
| 3342 |
try: |
| 3343 |
import certifi |
| 3344 |
except ImportError: |
| 3345 |
CAFILE = None |
| 3346 |
else: |
| 3347 |
CAFILE = certifi.where() |
| 3348 |
if CAFILE and not os.path.isfile(CAFILE): |
| 3349 |
CAFILE = None |
| 3350 |
if not CAFILE: |
| 3351 |
# Use our bundled CA file |
| 3352 |
CAFILE = get_data_path("cacert.pem") |
| 3353 |
if CAFILE and isinstance(CAFILE, str): |
| 3354 |
os.environ["SSL_CERT_FILE"] = CAFILE |