| 1 |
"""Argyll utilities situated here. |
| 2 |
|
| 3 |
The utilities that were previously spread around are gathered here. |
| 4 |
""" |
| 5 |
|
| 6 |
# Standard Library Imports |
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import contextlib |
| 10 |
import json |
| 11 |
import os |
| 12 |
import re |
| 13 |
import string |
| 14 |
import subprocess as sp |
| 15 |
import sys |
| 16 |
import time |
| 17 |
import urllib.error |
| 18 |
import urllib.request |
| 19 |
from functools import cache |
| 20 |
from typing import TYPE_CHECKING, Callable, overload |
| 21 |
|
| 22 |
# Local Imports |
| 23 |
from DisplayCAL import config, options |
| 24 |
from DisplayCAL import localization as lang |
| 25 |
from DisplayCAL.argyll_names import ALTNAMES as ARGYLL_ALTNAMES |
| 26 |
from DisplayCAL.argyll_names import NAMES as ARGYLL_NAMES |
| 27 |
from DisplayCAL.argyll_names import OPTIONAL as ARGYLL_OPTIONAL |
| 28 |
from DisplayCAL.config import ( |
| 29 |
APPNAME, |
| 30 |
EXE_EXT, |
| 31 |
FS_ENC, |
| 32 |
get_data_path, |
| 33 |
get_icon, |
| 34 |
get_verified_path, |
| 35 |
getcfg, |
| 36 |
setcfg, |
| 37 |
writecfg, |
| 38 |
) |
| 39 |
from DisplayCAL.util_os import getenvu, safe_glob, which |
| 40 |
from DisplayCAL.util_str import make_filename_safe |
| 41 |
|
| 42 |
if TYPE_CHECKING: |
| 43 |
import wx # noqa: TC004 |
| 44 |
|
| 45 |
ARGYLL_UTILS = {} |
| 46 |
|
| 47 |
|
| 48 |
def debug_print(*args, **kwargs) -> None: |
| 49 |
"""Prints messages if DEBUG is set to 1 or higher.""" |
| 50 |
if kwargs.pop("debug_level", 1) <= options.DEBUG: |
| 51 |
print(*args, **kwargs) |
| 52 |
|
| 53 |
|
| 54 |
def verbose_print(*args, **kwargs) -> None: |
| 55 |
"""Prints messages if VERBOSE is set to 1 or higher.""" |
| 56 |
if kwargs.pop("verbose_level", 1) <= options.VERBOSE: |
| 57 |
print(*args, **kwargs) |
| 58 |
|
| 59 |
|
| 60 |
def get_path_from_env() -> list[str]: |
| 61 |
"""Parse environment paths into a list. |
| 62 |
|
| 63 |
Returns: |
| 64 |
list[str]: A list of paths. |
| 65 |
""" |
| 66 |
return getenvu("PATH", os.defpath).split(os.pathsep) |
| 67 |
|
| 68 |
|
| 69 |
def check_argyll_bin(paths: None | list[str] = None) -> bool: |
| 70 |
"""Check if the Argyll binaries can be found. |
| 71 |
|
| 72 |
Args: |
| 73 |
paths (None | list[str]): The paths to look for. |
| 74 |
|
| 75 |
Returns: |
| 76 |
bool: True if all required Argyll binaries are found, False otherwise. |
| 77 |
""" |
| 78 |
prev_dir = None |
| 79 |
cur_dir = os.curdir |
| 80 |
for name in ARGYLL_NAMES: |
| 81 |
exe = get_argyll_util(name, paths) |
| 82 |
if not exe: |
| 83 |
if name in ARGYLL_OPTIONAL: |
| 84 |
continue |
| 85 |
return False |
| 86 |
cur_dir = os.path.dirname(exe) |
| 87 |
if not prev_dir: |
| 88 |
prev_dir = cur_dir |
| 89 |
continue |
| 90 |
if cur_dir == prev_dir: |
| 91 |
continue |
| 92 |
if name in ARGYLL_OPTIONAL: |
| 93 |
verbose_print( |
| 94 |
f"Warning: Optional Argyll executable {exe} is not " |
| 95 |
"in the same directory as the main executables " |
| 96 |
f"({prev_dir})." |
| 97 |
) |
| 98 |
else: |
| 99 |
verbose_print( |
| 100 |
f"Error: Main Argyll executable {exe} is not in the " |
| 101 |
f"same directory as the other executables ({prev_dir})." |
| 102 |
) |
| 103 |
return False |
| 104 |
|
| 105 |
verbose_print("Argyll binary directory:", cur_dir, verbose_level=3) |
| 106 |
debug_print("[D] check_argyll_bin OK") |
| 107 |
if options.DEBUG >= 2: |
| 108 |
if not paths: |
| 109 |
paths = get_path_from_env() |
| 110 |
argyll_dir = (getcfg("argyll.dir") or "").rstrip(os.path.sep) |
| 111 |
if argyll_dir: |
| 112 |
if argyll_dir in paths: |
| 113 |
paths.remove(argyll_dir) |
| 114 |
paths = [argyll_dir, *paths] |
| 115 |
print("[D] Search path:\n ", "\n ".join(paths)) |
| 116 |
# Fedora doesn't ship Rec709.icm |
| 117 |
config.DEFAULTS["3dlut.input.profile"] = ( |
| 118 |
get_data_path(os.path.join("ref", "Rec709.icm")) |
| 119 |
or get_data_path(os.path.join("ref", "sRGB.icm")) |
| 120 |
or "" |
| 121 |
) |
| 122 |
config.DEFAULTS["testchart.reference"] = ( |
| 123 |
get_data_path(os.path.join("ref", "ColorChecker.cie")) or "" |
| 124 |
) |
| 125 |
config.DEFAULTS["gamap_profile"] = ( |
| 126 |
get_data_path(os.path.join("ref", "sRGB.icm")) or "" |
| 127 |
) |
| 128 |
return True |
| 129 |
|
| 130 |
|
| 131 |
def prompt_argyll_dir( |
| 132 |
parent: wx.Window = None, |
| 133 |
callafter: None | Callable = None, |
| 134 |
callafter_args: None | tuple = None, |
| 135 |
) -> str: |
| 136 |
"""Prompt the user for the Argyll CMS directory. |
| 137 |
|
| 138 |
Args: |
| 139 |
parent (wx.Window): The parent window for dialogs. |
| 140 |
callafter (callable): A function to call after setting the Argyll bin. |
| 141 |
callafter_args (None | tuple): Arguments to pass to the callafter |
| 142 |
function. |
| 143 |
|
| 144 |
Returns: |
| 145 |
str: The path to the Argyll CMS directory. |
| 146 |
""" |
| 147 |
# Check if Argyll version on PATH is newer than configured Argyll version |
| 148 |
paths = get_path_from_env() |
| 149 |
argyll_version_string = get_argyll_version_string("dispwin", True, paths) |
| 150 |
argyll_version = parse_argyll_version_string(argyll_version_string) |
| 151 |
argyll_version_string_cfg = get_argyll_version_string("dispwin", True) |
| 152 |
argyll_version_cfg = parse_argyll_version_string(argyll_version_string_cfg) |
| 153 |
# Don't prompt for 1.2.3_foo if current version is 1.2.3 |
| 154 |
# but prompt for 1.2.3 if current version is 1.2.3_foo |
| 155 |
# Also prompt for 1.2.3_beta2 if current version is 1.2.3_beta |
| 156 |
argyll_dir = None |
| 157 |
if ( |
| 158 |
argyll_version > argyll_version_cfg |
| 159 |
and ( |
| 160 |
argyll_version[:4] == argyll_version_cfg[:4] |
| 161 |
or not argyll_version_string.startswith(argyll_version_string_cfg) |
| 162 |
) |
| 163 |
) or ( |
| 164 |
argyll_version < argyll_version_cfg |
| 165 |
and argyll_version_string_cfg.startswith(argyll_version_string) |
| 166 |
and "beta" in argyll_version_string_cfg.lower() |
| 167 |
): |
| 168 |
from DisplayCAL.wx_windows import ConfirmDialog |
| 169 |
|
| 170 |
argyll_dir = os.path.dirname(get_argyll_util("dispwin", paths) or "") |
| 171 |
dlg = ConfirmDialog( |
| 172 |
parent, |
| 173 |
msg=lang.getstr( |
| 174 |
"dialog.select_argyll_version", |
| 175 |
(argyll_version_string, argyll_version_string_cfg), |
| 176 |
), |
| 177 |
ok=lang.getstr("ok"), |
| 178 |
cancel=lang.getstr("cancel"), |
| 179 |
alt=lang.getstr("browse"), |
| 180 |
bitmap=get_icon(size=32, name="dialog-question"), |
| 181 |
) |
| 182 |
dlg_result = dlg.ShowModal() |
| 183 |
dlg.Destroy() |
| 184 |
if dlg_result == wx.ID_OK: |
| 185 |
setcfg("argyll.dir", None) |
| 186 |
# Always write cfg directly after setting Argyll directory so |
| 187 |
# subprocesses that read the configuration will use the right |
| 188 |
# executables |
| 189 |
writecfg() |
| 190 |
return True |
| 191 |
if dlg_result == wx.ID_CANCEL: |
| 192 |
if callafter: |
| 193 |
callafter(*callafter_args) |
| 194 |
return False |
| 195 |
|
| 196 |
return argyll_dir |
| 197 |
|
| 198 |
|
| 199 |
def get_homebrew_argyll_bin() -> None | str: |
| 200 |
"""Return Homebrew ArgyllCMS bin directory on macOS if available.""" |
| 201 |
if sys.platform != "darwin": |
| 202 |
return None |
| 203 |
brew = which("brew") or which("brew", ["/opt/homebrew/bin", "/usr/local/bin"]) |
| 204 |
if not brew: |
| 205 |
return None |
| 206 |
for formula in ("argyll-cms", "argyllcms"): |
| 207 |
try: |
| 208 |
result = sp.run( |
| 209 |
[brew, "--prefix", formula], |
| 210 |
check=False, |
| 211 |
capture_output=True, |
| 212 |
text=True, |
| 213 |
timeout=10, |
| 214 |
) |
| 215 |
except (OSError, ValueError, sp.SubprocessError): |
| 216 |
continue |
| 217 |
if result.returncode != 0: |
| 218 |
continue |
| 219 |
prefix = (result.stdout or "").strip() |
| 220 |
if not prefix: |
| 221 |
continue |
| 222 |
bin_dir = os.path.join(prefix, "bin") |
| 223 |
if check_argyll_bin([bin_dir]): |
| 224 |
return bin_dir |
| 225 |
return None |
| 226 |
|
| 227 |
|
| 228 |
def set_argyll_bin( |
| 229 |
parent: wx.Window = None, |
| 230 |
silent: bool = False, |
| 231 |
callafter: None | Callable = None, |
| 232 |
callafter_args: None | tuple = None, |
| 233 |
) -> bool: |
| 234 |
"""Set the directory containing the Argyll CMS binary executables. |
| 235 |
|
| 236 |
Args: |
| 237 |
parent (wx.Window): The parent window for dialogs. |
| 238 |
silent (bool): If True, do not show any dialogs. |
| 239 |
callafter (callable): A function to call after setting the Argyll bin. |
| 240 |
callafter_args (None | tuple): Arguments to pass to the callafter |
| 241 |
function. |
| 242 |
|
| 243 |
Returns: |
| 244 |
bool: True if the Argyll bin was set successfully, False otherwise. |
| 245 |
""" |
| 246 |
# TODO: This function contains UI stuff, please refactor it so that it is |
| 247 |
# split into a separate function that can be called from the UI. |
| 248 |
from DisplayCAL.wx_addons import wx |
| 249 |
from DisplayCAL.wx_windows import InfoDialog |
| 250 |
|
| 251 |
# Tests fails if wx.App is not initialized... |
| 252 |
_ = wx.GetApp() or wx.App() |
| 253 |
|
| 254 |
callafter_args = () if callafter_args is None else callafter_args |
| 255 |
|
| 256 |
# do not center on parent if not visible |
| 257 |
parent = None if parent and not parent.IsShownOnScreen() else parent |
| 258 |
argyll_dir = prompt_argyll_dir(parent, callafter, callafter_args) |
| 259 |
if parent and not check_argyll_bin(): |
| 260 |
choices = [ |
| 261 |
("download", lang.getstr("download")), |
| 262 |
("browse", lang.getstr("browse")), |
| 263 |
] |
| 264 |
brew_argyll_bin = get_homebrew_argyll_bin() |
| 265 |
if brew_argyll_bin: |
| 266 |
choices.append( |
| 267 |
( |
| 268 |
"homebrew", |
| 269 |
lang.getstr( |
| 270 |
"argyll.use_homebrew", |
| 271 |
brew_argyll_bin, |
| 272 |
), |
| 273 |
) |
| 274 |
) |
| 275 |
dlg = wx.SingleChoiceDialog( |
| 276 |
parent, |
| 277 |
lang.getstr("dialog.argyll.notfound.choice"), |
| 278 |
APPNAME, |
| 279 |
[label for _, label in choices], |
| 280 |
style=wx.CHOICEDLG_STYLE, |
| 281 |
) |
| 282 |
dlg.SetSelection(0) |
| 283 |
dlg_result = dlg.ShowModal() |
| 284 |
selected = dlg.GetSelection() |
| 285 |
dlg.Destroy() |
| 286 |
if dlg_result != wx.ID_OK: |
| 287 |
if callafter: |
| 288 |
callafter(*callafter_args) |
| 289 |
return False |
| 290 |
action = choices[selected][0] if selected >= 0 else "browse" |
| 291 |
if action == "download": |
| 292 |
# Download Argyll CMS |
| 293 |
from DisplayCAL.display_cal import app_update_check |
| 294 |
|
| 295 |
try: |
| 296 |
app_update_check(parent, silent, argyll=True) |
| 297 |
except Exception as exception: |
| 298 |
InfoDialog( |
| 299 |
parent, |
| 300 |
msg=f"{lang.getstr('download.fail')}\n{exception}", |
| 301 |
ok=lang.getstr("ok"), |
| 302 |
bitmap=get_icon(size=32, name="dialog-error"), |
| 303 |
) |
| 304 |
return False |
| 305 |
if action == "homebrew" and brew_argyll_bin: |
| 306 |
verbose_print( |
| 307 |
"Using Homebrew Argyll binary directory:", |
| 308 |
brew_argyll_bin, |
| 309 |
verbose_level=3, |
| 310 |
) |
| 311 |
setcfg("argyll.dir", brew_argyll_bin) |
| 312 |
# Always write cfg directly after setting Argyll directory so |
| 313 |
# subprocesses that read the configuration will use the right |
| 314 |
# executables |
| 315 |
writecfg() |
| 316 |
return True |
| 317 |
dlg = wx.DirDialog( |
| 318 |
parent, |
| 319 |
lang.getstr("dialog.set_argyll_bin"), |
| 320 |
defaultPath=os.path.join(*get_verified_path("argyll.dir", path=argyll_dir)), |
| 321 |
style=wx.DD_DIR_MUST_EXIST, |
| 322 |
) |
| 323 |
dlg.Center(wx.BOTH) |
| 324 |
result = False |
| 325 |
while not result: |
| 326 |
result = dlg.ShowModal() == wx.ID_OK |
| 327 |
if result: |
| 328 |
path = dlg.GetPath().rstrip(os.path.sep) |
| 329 |
if os.path.basename(path) != "bin": |
| 330 |
path = os.path.join(path, "bin") |
| 331 |
result = check_argyll_bin([path]) |
| 332 |
if result: |
| 333 |
verbose_print("Setting Argyll binary directory:", path, verbose_level=3) |
| 334 |
setcfg("argyll.dir", path) |
| 335 |
# Always write cfg directly after setting Argyll directory so |
| 336 |
# subprocesses that read the configuration will use the right |
| 337 |
# executables |
| 338 |
writecfg() |
| 339 |
break |
| 340 |
not_found = [ |
| 341 |
f" {lang.getstr('or')} ".join( |
| 342 |
[ |
| 343 |
altname |
| 344 |
for altname in [ |
| 345 |
altname + EXE_EXT for altname in ARGYLL_ALTNAMES[name] |
| 346 |
] |
| 347 |
if "argyll" not in altname |
| 348 |
] |
| 349 |
) |
| 350 |
for name in ARGYLL_NAMES |
| 351 |
if not get_argyll_util(name, [path]) and name not in ARGYLL_OPTIONAL |
| 352 |
] |
| 353 |
InfoDialog( |
| 354 |
parent, |
| 355 |
msg="{}\n\n{}".format( |
| 356 |
path, lang.getstr("argyll.dir.invalid", ", ".join(not_found)) |
| 357 |
), |
| 358 |
ok=lang.getstr("ok"), |
| 359 |
bitmap=get_icon(size=32, name="dialog-error"), |
| 360 |
) |
| 361 |
else: |
| 362 |
break |
| 363 |
dlg.Destroy() |
| 364 |
if not result and callafter: |
| 365 |
callafter(*callafter_args) |
| 366 |
return result |
| 367 |
|
| 368 |
|
| 369 |
def check_set_argyll_bin(paths: None | list[str] = None) -> bool: |
| 370 |
"""Check if Argyll binaries can be found, otherwise let the user choose. |
| 371 |
|
| 372 |
Args: |
| 373 |
paths (list[str]): The paths to look for. |
| 374 |
""" |
| 375 |
if check_argyll_bin(paths): |
| 376 |
return True |
| 377 |
return set_argyll_bin() |
| 378 |
|
| 379 |
|
| 380 |
def validate_search_paths(paths: None | list[str] = None) -> list[str]: |
| 381 |
"""Validate the paths to look for Argyll utilities. |
| 382 |
|
| 383 |
Args: |
| 384 |
paths (None | list[str]): The paths to look for. |
| 385 |
|
| 386 |
Returns: |
| 387 |
list[str]: A list of paths to look for Argyll utilities. |
| 388 |
""" |
| 389 |
cfg_argyll_dir = getcfg("argyll.dir") |
| 390 |
if not paths: |
| 391 |
paths = get_path_from_env() |
| 392 |
if argyll_dir := (cfg_argyll_dir or "").rstrip(os.path.sep): |
| 393 |
with contextlib.suppress(ValueError): |
| 394 |
paths.remove(argyll_dir) |
| 395 |
paths = [argyll_dir, *paths] |
| 396 |
return paths |
| 397 |
|
| 398 |
|
| 399 |
def get_argyll_util(name: str, paths: None | list[str] = None) -> None | str: |
| 400 |
"""Find a single Argyll utility. Return the full path. |
| 401 |
|
| 402 |
Args: |
| 403 |
name (str): The name of the utility. |
| 404 |
paths (None | list[str]): The paths to look for. |
| 405 |
|
| 406 |
Returns: |
| 407 |
None | str: None if not found or the path of the utility. |
| 408 |
""" |
| 409 |
paths = validate_search_paths(paths) |
| 410 |
cache_key = os.pathsep.join(paths) |
| 411 |
if exe := ARGYLL_UTILS.get(cache_key, {}).get(name, None): |
| 412 |
return exe |
| 413 |
verbose_print( |
| 414 |
"Info: Searching for", name, "in", os.pathsep.join(paths), verbose_level=4 |
| 415 |
) |
| 416 |
for path in paths: |
| 417 |
for altname in ARGYLL_ALTNAMES.get(name, []): |
| 418 |
if exe := which(f"{altname}{EXE_EXT}", [path]): |
| 419 |
break |
| 420 |
if exe: |
| 421 |
break |
| 422 |
|
| 423 |
verbose_print( |
| 424 |
*( |
| 425 |
["Info:", name, "=", exe] |
| 426 |
if exe |
| 427 |
else [ |
| 428 |
"Info:", |
| 429 |
"|".join(ARGYLL_ALTNAMES[name]), |
| 430 |
"not found in", |
| 431 |
os.pathsep.join(paths), |
| 432 |
] |
| 433 |
), |
| 434 |
verbose_level=4, |
| 435 |
) |
| 436 |
if exe: |
| 437 |
if cache_key not in ARGYLL_UTILS: |
| 438 |
ARGYLL_UTILS[cache_key] = {} |
| 439 |
ARGYLL_UTILS[cache_key][name] = exe |
| 440 |
return exe |
| 441 |
|
| 442 |
|
| 443 |
def get_argyll_utilname(name: str, paths: None | list[str] = None) -> str: |
| 444 |
"""Find a single Argyll utility. |
| 445 |
|
| 446 |
Args: |
| 447 |
name (str): The name of the utility. |
| 448 |
paths (None | list[str]): The paths to look for. |
| 449 |
|
| 450 |
Returns: |
| 451 |
str: The basename of the utility without extension, or an empty string |
| 452 |
if not found. |
| 453 |
""" |
| 454 |
exe = get_argyll_util(name, paths) |
| 455 |
if exe: |
| 456 |
exe = os.path.basename(os.path.splitext(exe)[0]) |
| 457 |
return exe |
| 458 |
|
| 459 |
|
| 460 |
def get_argyll_version( |
| 461 |
name: str, silent: bool = False, paths: None | list[str] = None |
| 462 |
) -> str: |
| 463 |
"""Determine version of a certain Argyll utility. |
| 464 |
|
| 465 |
Args: |
| 466 |
name (str): The name of the Argyll utility. |
| 467 |
silent (bool): Silently check Argyll version. Default is False. |
| 468 |
paths (None | list[str]): Paths to look for Argyll executables. |
| 469 |
|
| 470 |
Returns: |
| 471 |
str: The Argyll utility version. |
| 472 |
""" |
| 473 |
argyll_version_string = get_argyll_version_string(name, silent, paths) |
| 474 |
return parse_argyll_version_string(argyll_version_string) |
| 475 |
|
| 476 |
|
| 477 |
def get_argyll_version_string( |
| 478 |
name: str, silent: bool = False, paths: None | str = None |
| 479 |
) -> str: |
| 480 |
"""Return the version of the requested Argyll utility. |
| 481 |
|
| 482 |
Args: |
| 483 |
name (str): The name of the Argyll utility. |
| 484 |
silent (bool): Silently check Argyll version. Default is False. |
| 485 |
paths (None | str): Paths to look for Argyll executables. |
| 486 |
|
| 487 |
Returns: |
| 488 |
str: The Argyll utility version. |
| 489 |
""" |
| 490 |
argyll_version_string = "0.0.0" |
| 491 |
if (not silent or not check_argyll_bin(paths)) and ( |
| 492 |
silent or not check_set_argyll_bin(paths) |
| 493 |
): |
| 494 |
return argyll_version_string |
| 495 |
|
| 496 |
# Try getting the version from the log.txt file first |
| 497 |
argyll_dir = getcfg("argyll.dir") |
| 498 |
if argyll_dir: |
| 499 |
log_path = os.path.join(argyll_dir, "log.txt") |
| 500 |
if os.path.isfile(log_path): |
| 501 |
try: |
| 502 |
with open(log_path, "rb") as f: |
| 503 |
log_data = f.read(150) |
| 504 |
match = re.search(rb"(?<=Version )\d+\.\d+\.\d+(_\w+)?", log_data) |
| 505 |
if match: |
| 506 |
return match.group().decode("utf-8") |
| 507 |
except Exception as e: |
| 508 |
print(f"Error reading {log_path}: {e}") |
| 509 |
else: |
| 510 |
print("Warning: Argyll directory not set in config.") |
| 511 |
|
| 512 |
# If the log.txt file is not available or doesn't contain the version, |
| 513 |
# fall back to using the utility itself |
| 514 |
# to get the version |
| 515 |
|
| 516 |
cmd = get_argyll_util(name, paths) |
| 517 |
if sys.platform == "win32": |
| 518 |
startupinfo = sp.STARTUPINFO() |
| 519 |
startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW |
| 520 |
startupinfo.wShowWindow = sp.SW_HIDE |
| 521 |
else: |
| 522 |
startupinfo = None |
| 523 |
try: |
| 524 |
p = sp.Popen( |
| 525 |
[cmd.encode(FS_ENC), "-?"], |
| 526 |
stdin=sp.PIPE, |
| 527 |
stdout=sp.PIPE, |
| 528 |
stderr=sp.STDOUT, |
| 529 |
startupinfo=startupinfo, |
| 530 |
) |
| 531 |
except Exception as exception: |
| 532 |
print(exception) |
| 533 |
return argyll_version_string |
| 534 |
|
| 535 |
for line in (p.communicate(timeout=30)[0] or b"").splitlines(): |
| 536 |
line = line.strip() |
| 537 |
if b"version" in line.lower(): |
| 538 |
argyll_version_string = line[line.lower().find(b"version") + 8 :].decode( |
| 539 |
"utf-8" |
| 540 |
) |
| 541 |
break |
| 542 |
|
| 543 |
return argyll_version_string |
| 544 |
|
| 545 |
|
| 546 |
def parse_argyll_version_string(argyll_version_string: str) -> list[int | str]: |
| 547 |
"""Parse the Argyll version string. |
| 548 |
|
| 549 |
Args: |
| 550 |
argyll_version_string (str): The version string to parse. |
| 551 |
|
| 552 |
Returns: |
| 553 |
list[int | str]: A list of version components. |
| 554 |
""" |
| 555 |
if isinstance(argyll_version_string, bytes): |
| 556 |
argyll_version_string = argyll_version_string.decode() |
| 557 |
argyll_version = re.findall(r"(\d+|[^.\d]+)", argyll_version_string) |
| 558 |
for i, v in enumerate(argyll_version): |
| 559 |
with contextlib.suppress(ValueError): |
| 560 |
argyll_version[i] = int(v) |
| 561 |
return argyll_version |
| 562 |
|
| 563 |
|
| 564 |
ARGYLLCMS_BINARIES_API_URL = ( |
| 565 |
"https://api.github.com/repos/eoyilmaz/argyllcms-binaries/releases/latest" |
| 566 |
) |
| 567 |
|
| 568 |
|
| 569 |
@cache |
| 570 |
def get_argyll_latest_version() -> str: |
| 571 |
"""Return the latest ArgyllCMS version from the argyllcms-binaries GitHub releases API. |
| 572 |
|
| 573 |
Returns: |
| 574 |
str: The latest version number. |
| 575 |
""" |
| 576 |
default_version = config.DEFAULTS.get("argyll.version") |
| 577 |
max_retries = 5 |
| 578 |
base_delay = 5 |
| 579 |
request = urllib.request.Request(ARGYLLCMS_BINARIES_API_URL) |
| 580 |
# Authenticated GitHub API requests get a 5000/hour rate limit instead of |
| 581 |
# the 60/hour applied per-IP to anonymous requests, which CI runners can |
| 582 |
# exhaust quickly since they share IP pools. GITHUB_TOKEN is provided for |
| 583 |
# free by GitHub Actions when explicitly passed through to the job env. |
| 584 |
github_token = os.environ.get("GITHUB_TOKEN") |
| 585 |
if github_token: |
| 586 |
request.add_header("Authorization", f"Bearer {github_token}") |
| 587 |
for attempt in range(max_retries): |
| 588 |
try: |
| 589 |
response = urllib.request.urlopen(request, timeout=20) # noqa: S310 |
| 590 |
data = json.loads(response.read()) |
| 591 |
break |
| 592 |
except urllib.error.HTTPError as exception: |
| 593 |
delay = base_delay * (2**attempt) |
| 594 |
if attempt < max_retries - 1: |
| 595 |
print( |
| 596 |
f"HTTP {exception.code} fetching ArgyllCMS latest version: " |
| 597 |
f"{exception}. Waiting {delay}s before retry..." |
| 598 |
) |
| 599 |
time.sleep(delay) |
| 600 |
else: |
| 601 |
print(f"Could not fetch ArgyllCMS latest version: {exception}") |
| 602 |
return default_version |
| 603 |
except (urllib.error.URLError, OSError, TimeoutError) as exception: |
| 604 |
delay = base_delay * (2**attempt) |
| 605 |
if attempt < max_retries - 1: |
| 606 |
print( |
| 607 |
f"Error fetching ArgyllCMS latest version: {exception}. " |
| 608 |
f"Waiting {delay}s before retry..." |
| 609 |
) |
| 610 |
time.sleep(delay) |
| 611 |
else: |
| 612 |
print(f"Could not fetch ArgyllCMS latest version: {exception}") |
| 613 |
return default_version |
| 614 |
else: |
| 615 |
return default_version |
| 616 |
tag_name = data.get("tag_name", "") |
| 617 |
if not re.match(r"^\d+\.\d+", tag_name): |
| 618 |
print( |
| 619 |
f"Could not parse ArgyllCMS latest version from " |
| 620 |
f"{ARGYLLCMS_BINARIES_API_URL}, falling back to {default_version}" |
| 621 |
) |
| 622 |
return default_version |
| 623 |
print(f"Latest ArgyllCMS version: {tag_name}") |
| 624 |
return tag_name |
| 625 |
|
| 626 |
|
| 627 |
@overload |
| 628 |
def make_argyll_compatible_path(path: bytes, is_name: bool = ...) -> bytes: ... |
| 629 |
|
| 630 |
|
| 631 |
@overload |
| 632 |
def make_argyll_compatible_path(path: str, is_name: bool = ...) -> str: ... |
| 633 |
|
| 634 |
|
| 635 |
def make_argyll_compatible_path(path, is_name=False): |
| 636 |
"""Make the path compatible with the Argyll utilities. |
| 637 |
|
| 638 |
This is currently only effective under Windows to make sure that any |
| 639 |
unicode 'division' slashes in the profile name are replaced with |
| 640 |
underscores. |
| 641 |
|
| 642 |
Args: |
| 643 |
path (bytes | str): The path to be made compatible. |
| 644 |
is_name (bool): If True, treat ``path`` as a single filename/profile |
| 645 |
name component instead of a real filesystem path. All invalid |
| 646 |
filename characters (including path separators such as ``/`` and |
| 647 |
``\\``) are replaced instead of being preserved as directory |
| 648 |
boundaries. Use this whenever the string is not guaranteed to be |
| 649 |
an actual, already validated path (e.g. an ICC profile |
| 650 |
description or a user-editable profile name). |
| 651 |
|
| 652 |
Returns: |
| 653 |
bytes | str: The compatible path. |
| 654 |
""" |
| 655 |
if is_name: |
| 656 |
pattern = r'[\\/:;*?"<>|]+' |
| 657 |
substitute = "_" |
| 658 |
if isinstance(path, bytes): |
| 659 |
pattern = pattern.encode("utf-8") |
| 660 |
substitute = substitute.encode("utf-8") |
| 661 |
return make_filename_safe(re.sub(pattern, substitute, path)) |
| 662 |
skip = -1 |
| 663 |
regex = r"\\\\\?\\" |
| 664 |
driver_letter_escape_char = ":" |
| 665 |
os_path_sep = os.path.sep |
| 666 |
string_ascii_uppercase = string.ascii_uppercase |
| 667 |
if isinstance(path, bytes): |
| 668 |
regex = regex.encode("utf-8") |
| 669 |
driver_letter_escape_char = driver_letter_escape_char.encode("utf-8") |
| 670 |
os_path_sep = os_path_sep.encode("utf-8") |
| 671 |
string_ascii_uppercase = string_ascii_uppercase.encode("utf-8") |
| 672 |
|
| 673 |
if re.match(regex, path, re.I): |
| 674 |
# Don't forget about UNC paths: |
| 675 |
# \\?\UNC\Server\Volume\File |
| 676 |
# \\?\C:\File |
| 677 |
skip = 2 |
| 678 |
|
| 679 |
parts = path.split(os_path_sep) |
| 680 |
if sys.platform == "win32" and len(parts) > skip + 1: |
| 681 |
driveletterpart = parts[skip + 1] |
| 682 |
if ( |
| 683 |
len(driveletterpart) == 2 |
| 684 |
and driveletterpart[0:1].upper() in string_ascii_uppercase |
| 685 |
and driveletterpart[1:2] == driver_letter_escape_char |
| 686 |
): |
| 687 |
skip += 1 |
| 688 |
|
| 689 |
for i, part in enumerate(parts): |
| 690 |
if i > skip: |
| 691 |
parts[i] = make_filename_safe(part) |
| 692 |
return os_path_sep.join(parts) |
| 693 |
|
| 694 |
|
| 695 |
def get_argyll_instrument_config(what: None | str = None) -> list[str]: |
| 696 |
"""Check for Argyll CMS udev rules/hotplug scripts. |
| 697 |
|
| 698 |
Args: |
| 699 |
what (str): The type of files to look for. Can be "installed", |
| 700 |
"expected", or None. |
| 701 |
|
| 702 |
Returns: |
| 703 |
list[str]: A list of file paths that match the criteria. |
| 704 |
""" |
| 705 |
filenames = [] |
| 706 |
if what == "installed": |
| 707 |
argyll_rule_filepaths = ( |
| 708 |
"/etc/udev/rules.d/55-Argyll.rules", |
| 709 |
"/etc/udev/rules.d/45-Argyll.rules", |
| 710 |
"/etc/hotplug/Argyll", |
| 711 |
"/etc/hotplug/Argyll.usermap", |
| 712 |
"/lib/udev/rules.d/55-Argyll.rules", |
| 713 |
"/lib/udev/rules.d/69-cd-sensors.rules", |
| 714 |
) |
| 715 |
filenames = [ |
| 716 |
filename for filename in argyll_rule_filepaths if os.path.isfile(filename) |
| 717 |
] |
| 718 |
else: |
| 719 |
if what == "expected": |
| 720 |
|
| 721 |
def fn(filename: bytes | str) -> bytes | str: |
| 722 |
"""Return the full path to the Argyll utility.""" |
| 723 |
return filename |
| 724 |
else: |
| 725 |
fn = get_data_path |
| 726 |
if os.path.isdir("/etc/udev/rules.d"): |
| 727 |
if safe_glob("/dev/bus/usb/*/*"): |
| 728 |
# USB and serial instruments using udev, where udev |
| 729 |
# already creates /dev/bus/usb/00X/00X devices |
| 730 |
filenames.append(fn("usb/55-Argyll.rules")) |
| 731 |
else: |
| 732 |
# USB using udev, where there are NOT /dev/bus/usb/00X/00X |
| 733 |
# devices |
| 734 |
filenames.append(fn("usb/45-Argyll.rules")) |
| 735 |
elif os.path.isdir("/etc/hotplug"): |
| 736 |
# USB using hotplug and Serial using udev |
| 737 |
# (older versions of Linux) |
| 738 |
filenames.extend( |
| 739 |
fn(filename) for filename in ("usb/Argyll", "usb/Argyll.usermap") |
| 740 |
) |
| 741 |
return [filename for filename in filenames if filename] |