| 1 |
"""Interface to the colord service for managing color profiles and devices on Linux. |
| 2 |
|
| 3 |
It supports querying, managing, and installing color profiles for display |
| 4 |
devices, leveraging both the D-Bus API and the `colormgr` command-line utility. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import contextlib |
| 10 |
import os |
| 11 |
import subprocess as sp |
| 12 |
import sys |
| 13 |
import warnings |
| 14 |
from binascii import hexlify |
| 15 |
from time import sleep |
| 16 |
from typing import Callable |
| 17 |
|
| 18 |
from DisplayCAL.options import USE_COLORD_GI |
| 19 |
|
| 20 |
try: |
| 21 |
# XXX D-Bus API is more complete currently |
| 22 |
if not USE_COLORD_GI: |
| 23 |
raise ImportError("") |
| 24 |
from gi.repository import Colord, Gio |
| 25 |
except ImportError: |
| 26 |
Colord = None |
| 27 |
Gio = None |
| 28 |
else: |
| 29 |
cancellable = Gio.Cancellable.new() |
| 30 |
|
| 31 |
from DisplayCAL import localization as lang |
| 32 |
from DisplayCAL.util_dbus import BUSTYPE_SYSTEM, DBusException, DBusObject |
| 33 |
from DisplayCAL.util_os import which |
| 34 |
from DisplayCAL.util_str import safe_str |
| 35 |
|
| 36 |
if sys.platform not in ("darwin", "win32"): |
| 37 |
from DisplayCAL.defaultpaths import XDG_DATA_HOME |
| 38 |
|
| 39 |
if not Colord: |
| 40 |
try: |
| 41 |
Colord = DBusObject( |
| 42 |
BUSTYPE_SYSTEM, |
| 43 |
"org.freedesktop.ColorManager", |
| 44 |
"/org/freedesktop/ColorManager", |
| 45 |
) |
| 46 |
except DBusException as exception: |
| 47 |
warnings.warn(safe_str(exception), Warning, stacklevel=2) |
| 48 |
|
| 49 |
|
| 50 |
# See colord/cd-client.c |
| 51 |
CD_CLIENT_IMPORT_DAEMON_TIMEOUT = 5000 # ms |
| 52 |
|
| 53 |
|
| 54 |
if ( |
| 55 |
not Colord |
| 56 |
or isinstance(Colord, DBusObject) |
| 57 |
or not hasattr(Colord, "quirk_vendor_name") |
| 58 |
): |
| 59 |
# from DisplayCAL.config import get_data_path |
| 60 |
|
| 61 |
# From colord/lib/colord/cd_quirk.c, cd_quirk_vendor_name |
| 62 |
quirk_cache = { |
| 63 |
"suffixes": [ |
| 64 |
"Co.", |
| 65 |
"Co", |
| 66 |
"Inc.", |
| 67 |
"Inc", |
| 68 |
"Ltd.", |
| 69 |
"Ltd", |
| 70 |
"Corporation", |
| 71 |
"Incorporated", |
| 72 |
"Limited", |
| 73 |
"GmbH", |
| 74 |
"corp.", |
| 75 |
], |
| 76 |
"vendor_names": { |
| 77 |
"Acer, inc.": "Acer", |
| 78 |
"Acer Technologies": "Acer", |
| 79 |
"AOC Intl": "AOC", |
| 80 |
"Apple Computer Inc": "Apple", |
| 81 |
"Arnos Insturments & Computer Systems": "Arnos", |
| 82 |
"ASUSTeK Computer Inc.": "ASUSTeK", |
| 83 |
"ASUSTeK Computer INC": "ASUSTeK", |
| 84 |
"ASUSTeK COMPUTER INC.": "ASUSTeK", |
| 85 |
"BTC Korea Co., Ltd": "BTC", |
| 86 |
"CASIO COMPUTER CO.,LTD": "Casio", |
| 87 |
"CLEVO": "Clevo", |
| 88 |
"Delta Electronics": "Delta", |
| 89 |
"Eizo Nanao Corporation": "Eizo", |
| 90 |
"Envision Peripherals,": "Envision", |
| 91 |
"FUJITSU": "Fujitsu", |
| 92 |
"Fujitsu Siemens Computers GmbH": "Fujitsu Siemens", |
| 93 |
"Funai Electric Co., Ltd.": "Funai", |
| 94 |
"Gigabyte Technology Co., Ltd.": "Gigabyte", |
| 95 |
"Goldstar Company Ltd": "LG", |
| 96 |
"LG Electronics": "LG", |
| 97 |
"GOOGLE": "Google", |
| 98 |
"Hewlett-Packard": "Hewlett Packard", |
| 99 |
"Hitachi America Ltd": "Hitachi", |
| 100 |
"HP": "Hewlett Packard", |
| 101 |
"HWP": "Hewlett Packard", |
| 102 |
"IBM France": "IBM", |
| 103 |
"Lenovo Group Limited": "Lenovo", |
| 104 |
"LENOVO": "Lenovo", |
| 105 |
"Iiyama North America": "Iiyama", |
| 106 |
"MARANTZ JAPAN, INC.": "Marantz", |
| 107 |
"Mitsubishi Electric Corporation": "Mitsubishi", |
| 108 |
"Nexgen Mediatech Inc.,": "Nexgen Mediatech", |
| 109 |
"NIKON": "Nikon", |
| 110 |
"Panasonic Industry Company": "Panasonic", |
| 111 |
"Philips Consumer Electronics Company": "Philips", |
| 112 |
"RGB Systems, Inc. dba Extron Electronics": "Extron", |
| 113 |
"SAM": "Samsung", |
| 114 |
"Samsung Electric Company": "Samsung", |
| 115 |
"Samsung Electronics America": "Samsung", |
| 116 |
"samsung": "Samsung", |
| 117 |
"SAMSUNG": "Samsung", |
| 118 |
"Sanyo Electric Co.,Ltd.": "Sanyo", |
| 119 |
"Sonix Technology Co.": "Sonix", |
| 120 |
"System manufacturer": "Unknown", |
| 121 |
"To Be Filled By O.E.M.": "Unknown", |
| 122 |
"Toshiba America Info Systems Inc": "Toshiba", |
| 123 |
"Toshiba Matsushita Display Technology Co.,": "Toshiba", |
| 124 |
"TOSHIBA": "Toshiba", |
| 125 |
"Unknown vendor": "Unknown", |
| 126 |
"Westinghouse Digital Electronics": "Westinghouse Digital", |
| 127 |
"Zalman Tech Co., Ltd.": "Zalman", |
| 128 |
}, |
| 129 |
} |
| 130 |
|
| 131 |
|
| 132 |
prefix = "/org/freedesktop/ColorManager/" |
| 133 |
device_ids = {} |
| 134 |
|
| 135 |
|
| 136 |
def client_connect() -> Colord.Client: |
| 137 |
"""Connect to colord. |
| 138 |
|
| 139 |
Raises: |
| 140 |
CDError: If there is an error connecting to colord. |
| 141 |
|
| 142 |
Returns: |
| 143 |
Colord.Client: Colord client instance. |
| 144 |
""" |
| 145 |
client = Colord.Client.new() |
| 146 |
|
| 147 |
# Connect to colord |
| 148 |
if not client.connect_sync(cancellable): |
| 149 |
raise CDError("Couldn't connect to colord") |
| 150 |
return client |
| 151 |
|
| 152 |
|
| 153 |
def device_connect(client: Colord.Client, device_id: bytes | str) -> Device: |
| 154 |
"""Connect to device. |
| 155 |
|
| 156 |
Args: |
| 157 |
client (Colord.Client): Colord client instance. |
| 158 |
device_id (bytes | str): Device ID to connect to. |
| 159 |
|
| 160 |
Raises: |
| 161 |
CDError: If there is an error connecting to the device or if the device |
| 162 |
could not be found. |
| 163 |
|
| 164 |
Returns: |
| 165 |
Device: Connected device object. |
| 166 |
""" |
| 167 |
if isinstance(device_id, str): |
| 168 |
device_id = device_id.encode("UTF-8") |
| 169 |
try: |
| 170 |
device = client.find_device_sync(device_id, cancellable) |
| 171 |
except Exception as exception: |
| 172 |
raise CDError(exception.args[0]) from exception |
| 173 |
|
| 174 |
# Connect to device |
| 175 |
if not device.connect_sync(cancellable): |
| 176 |
raise CDError(f"Couldn't connect to device with ID {device_id!r}") |
| 177 |
return device |
| 178 |
|
| 179 |
|
| 180 |
def device_id_from_edid( |
| 181 |
edid: dict, |
| 182 |
quirk: bool = False, |
| 183 |
use_serial_32: bool = True, |
| 184 |
truncate_edid_strings: bool = False, |
| 185 |
omit_manufacturer: bool = False, |
| 186 |
query: bool = False, |
| 187 |
) -> None | str: |
| 188 |
"""Assemble device key from EDID. |
| 189 |
|
| 190 |
Args: |
| 191 |
edid (dict): EDID data containing keys like 'manufacturer', |
| 192 |
'monitor_name', 'serial_ascii', and optionally 'hash'. |
| 193 |
quirk (bool): Whether to apply manufacturer name quirks. |
| 194 |
use_serial_32 (bool): Whether to include the 32-bit serial number. |
| 195 |
truncate_edid_strings (bool): Whether to truncate EDID strings to 12 characters. |
| 196 |
omit_manufacturer (bool): Whether to omit the manufacturer from the device ID. |
| 197 |
query (bool): Whether to query colord for the device ID. |
| 198 |
|
| 199 |
Returns: |
| 200 |
None | str: Assembled device ID string or None if no valid ID could be |
| 201 |
constructed. |
| 202 |
""" |
| 203 |
# https://github.com/hughsie/colord/blob/master/doc/device-and-profile-naming-spec.txt |
| 204 |
# Should match device ID returned by gcm_session_get_output_id in |
| 205 |
# gnome-settings-daemon/plugins/color/gsd-color-state.c |
| 206 |
# and Edid::deviceId in colord-kde/colord-kded/Edid.cpp respectively |
| 207 |
if device_id := device_id_from_edid_hash(edid=edid, query=query): |
| 208 |
return device_id |
| 209 |
return generate_device_id( |
| 210 |
edid, quirk, use_serial_32, truncate_edid_strings, omit_manufacturer |
| 211 |
) |
| 212 |
|
| 213 |
|
| 214 |
def generate_device_id( |
| 215 |
edid: dict, |
| 216 |
quirk: bool = False, |
| 217 |
use_serial_32: bool = True, |
| 218 |
truncate_edid_strings: bool = False, |
| 219 |
omit_manufacturer: bool = False, |
| 220 |
) -> None | str: |
| 221 |
"""Generate a device ID from EDID data. |
| 222 |
|
| 223 |
Args: |
| 224 |
edid (dict): EDID data containing keys like 'manufacturer', |
| 225 |
'monitor_name', 'serial_ascii', and optionally 'hash'. |
| 226 |
quirk (bool): Whether to apply manufacturer name quirks. |
| 227 |
use_serial_32 (bool): Whether to include the 32-bit serial number. |
| 228 |
truncate_edid_strings (bool): Whether to truncate EDID strings to 12 characters. |
| 229 |
omit_manufacturer (bool): Whether to omit the manufacturer from the device ID. |
| 230 |
|
| 231 |
Returns: |
| 232 |
str: A string representing the device ID based on the EDID data. |
| 233 |
""" |
| 234 |
parts = ["xrandr"] |
| 235 |
edid_keys = ["monitor_name", "serial_ascii"] |
| 236 |
if not omit_manufacturer: |
| 237 |
edid_keys.insert(0, "manufacturer") |
| 238 |
if use_serial_32: |
| 239 |
edid_keys.append("serial_32") |
| 240 |
for name in edid_keys: |
| 241 |
if not (value := edid.get(name)): |
| 242 |
continue |
| 243 |
if name == "serial_32" and "serial_ascii" in edid: |
| 244 |
# Only add numeric serial if no ascii serial |
| 245 |
continue |
| 246 |
if name == "manufacturer": |
| 247 |
value = quirk_manufacturer(value) if quirk else value |
| 248 |
elif isinstance(value, str) and truncate_edid_strings: |
| 249 |
# Older versions of colord used only the first 12 bytes |
| 250 |
value = value[:12] |
| 251 |
parts.append(str(value)) |
| 252 |
return "-".join(parts) if len(parts) > 1 else None |
| 253 |
|
| 254 |
|
| 255 |
def device_id_from_edid_hash(edid: dict, query: bool = False) -> None | str: |
| 256 |
"""Generate a device ID from EDID hash. |
| 257 |
|
| 258 |
Args: |
| 259 |
edid (dict): EDID data containing 'hash' key. |
| 260 |
query (bool): Whether to query colord for the device ID. |
| 261 |
|
| 262 |
Returns: |
| 263 |
None | str: A string representing the device ID based on the EDID hash. |
| 264 |
""" |
| 265 |
if "hash" not in edid: |
| 266 |
return None |
| 267 |
|
| 268 |
# Placeholder implementation, replace with actual logic as needed |
| 269 |
if device_id := device_ids.get(edid["hash"]): |
| 270 |
return device_id |
| 271 |
if ( |
| 272 |
sys.platform not in ("darwin", "win32") |
| 273 |
and query |
| 274 |
and isinstance(Colord, DBusObject) |
| 275 |
): |
| 276 |
try: |
| 277 |
device = Device(find("device-by-property", ["OutputEdidMd5", edid["hash"]])) |
| 278 |
device_id = device.properties.get("DeviceId") |
| 279 |
except CDError as exception: |
| 280 |
warnings.warn(safe_str(exception), Warning, stacklevel=2) |
| 281 |
else: |
| 282 |
if device_id: |
| 283 |
device_ids[edid["hash"]] = device_id |
| 284 |
return device_id |
| 285 |
return None |
| 286 |
|
| 287 |
|
| 288 |
def find(what: str, search: str | list) -> str: |
| 289 |
"""Find device or profile and return object path. |
| 290 |
|
| 291 |
Args: |
| 292 |
what (str): Type of object to search for, e.g., "profile-by-id" or |
| 293 |
"device-by-property". |
| 294 |
search (list or str): Search criteria, e.g., profile ID or device ID. |
| 295 |
|
| 296 |
Raises: |
| 297 |
CDError: If colord API is not available or if there is an error |
| 298 |
querying the object. |
| 299 |
CDObjectNotFoundError: If the object could not be found. |
| 300 |
CDObjectQueryError: If there is an error querying the object. |
| 301 |
|
| 302 |
Returns: |
| 303 |
str: Object path of the found object. |
| 304 |
""" |
| 305 |
if not isinstance(Colord, DBusObject): |
| 306 |
raise CDError("colord API not available") |
| 307 |
if not isinstance(search, list): |
| 308 |
search = [search] |
| 309 |
method_name = "_".join(part for part in what.split("-")) |
| 310 |
try: |
| 311 |
return getattr(Colord, "find_" + method_name)(*search) |
| 312 |
except Exception as exception: |
| 313 |
if hasattr(exception, "get_dbus_name"): |
| 314 |
if exception.get_dbus_name() == "org.freedesktop.ColorManager.NotFound": |
| 315 |
raise CDObjectNotFoundError(safe_str(exception)) from exception |
| 316 |
raise CDObjectQueryError(safe_str(exception)) from exception |
| 317 |
raise CDError(safe_str(exception)) from exception |
| 318 |
|
| 319 |
|
| 320 |
def get_default_profile(device_id: str) -> str: |
| 321 |
"""Get default profile for device. |
| 322 |
|
| 323 |
Args: |
| 324 |
device_id (str): Device ID to search for. |
| 325 |
|
| 326 |
Returns: |
| 327 |
str: Default profile ID for the device. |
| 328 |
""" |
| 329 |
# Find device object path |
| 330 |
device = Device(get_object_path(device_id, "device")) |
| 331 |
|
| 332 |
# Get default profile |
| 333 |
try: |
| 334 |
properties = device.properties |
| 335 |
except Exception as exception: |
| 336 |
raise CDError(safe_str(exception)) from exception |
| 337 |
else: |
| 338 |
if properties.get("ProfilingInhibitors"): |
| 339 |
return None |
| 340 |
profiles = properties.get("Profiles") |
| 341 |
if profiles: |
| 342 |
return profiles[0] |
| 343 |
raise CDError(f"Couldn't get default profile for device ID {device_id!r}") |
| 344 |
|
| 345 |
|
| 346 |
def get_devices_by_kind(kind: str) -> list: |
| 347 |
"""Get devices by kind. |
| 348 |
|
| 349 |
Args: |
| 350 |
kind (str): Kind of device to search for. |
| 351 |
|
| 352 |
Returns: |
| 353 |
list: List of devices of the specified kind. |
| 354 |
""" |
| 355 |
if not isinstance(Colord, DBusObject): |
| 356 |
return [] |
| 357 |
return [ |
| 358 |
Device(str(object_path)) for object_path in Colord.get_devices_by_kind(kind) |
| 359 |
] |
| 360 |
|
| 361 |
|
| 362 |
def get_display_devices() -> list: |
| 363 |
"""Get display devices. |
| 364 |
|
| 365 |
Returns: |
| 366 |
list: List of display devices. |
| 367 |
""" |
| 368 |
return get_devices_by_kind("display") |
| 369 |
|
| 370 |
|
| 371 |
def get_display_device_ids() -> list: |
| 372 |
"""Get display device IDs. |
| 373 |
|
| 374 |
Returns: |
| 375 |
list: List of display device IDs. |
| 376 |
""" |
| 377 |
return [ |
| 378 |
_f |
| 379 |
for _f in ( |
| 380 |
display.properties.get("DeviceId") for display in get_display_devices() |
| 381 |
) |
| 382 |
if _f |
| 383 |
] |
| 384 |
|
| 385 |
|
| 386 |
def get_object_path(search: str, object_type: str) -> str: |
| 387 |
"""Get object path for profile or device ID. |
| 388 |
|
| 389 |
Args: |
| 390 |
search (str): Profile or device ID to search for. |
| 391 |
object_type (str): Type of object to search for, e.g., "profile" or |
| 392 |
"device". |
| 393 |
|
| 394 |
Raises: |
| 395 |
CDObjectNotFoundError: If the object path could not be found. |
| 396 |
|
| 397 |
Returns: |
| 398 |
str: Object path for the specified profile or device ID. |
| 399 |
""" |
| 400 |
result = find(f"{object_type}-by-id", search) |
| 401 |
if not result: |
| 402 |
raise CDObjectNotFoundError(f"Could not find object path for {search}") |
| 403 |
return result |
| 404 |
|
| 405 |
|
| 406 |
def install_profile( |
| 407 |
device_id: str, |
| 408 |
profile: Profile, |
| 409 |
timeout: float = CD_CLIENT_IMPORT_DAEMON_TIMEOUT / 1000.0, |
| 410 |
logfn: None | Callable = None, |
| 411 |
) -> None: |
| 412 |
"""Install profile for device. |
| 413 |
|
| 414 |
Args: |
| 415 |
device_id (str): Device ID to install the profile for. |
| 416 |
profile (Profile): Profile object to install. |
| 417 |
timeout (float): Time to allow for colord to pick up new profiles (recommended |
| 418 |
not below 2 secs). |
| 419 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 420 |
""" |
| 421 |
if Colord and not isinstance(Colord, DBusObject): |
| 422 |
install_profile_with_colord(device_id, profile, timeout=timeout, logfn=logfn) |
| 423 |
else: |
| 424 |
install_profile_with_dbus(device_id, profile, timeout=timeout, logfn=logfn) |
| 425 |
|
| 426 |
|
| 427 |
def get_profile_install_parameters( |
| 428 |
profile: Profile, logfn: None | Callable = None |
| 429 |
) -> tuple[str, bool, str]: |
| 430 |
"""Get parameters for profile installation. |
| 431 |
|
| 432 |
Args: |
| 433 |
profile (Profile): Profile object to install. |
| 434 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 435 |
|
| 436 |
Returns: |
| 437 |
tuple: A tuple containing the profile installation name, whether the |
| 438 |
profile already exists, and the profile ID. |
| 439 |
""" |
| 440 |
profile_install_name = os.path.join( |
| 441 |
XDG_DATA_HOME, "icc", os.path.basename(profile.filename) |
| 442 |
) |
| 443 |
|
| 444 |
profile_exists = os.path.isfile(profile_install_name) |
| 445 |
if profile.filename != profile_install_name and profile_exists: |
| 446 |
if logfn: |
| 447 |
logfn("About to overwrite existing", profile_install_name) |
| 448 |
profile.filename = None |
| 449 |
|
| 450 |
if profile.ID == "\0" * 16: |
| 451 |
profile.calculate_id() |
| 452 |
profile.filename = None |
| 453 |
profile_id = "icc-" + hexlify(profile.ID).decode() |
| 454 |
return profile_install_name, profile_exists, profile_id |
| 455 |
|
| 456 |
|
| 457 |
def write_profile_to_destination( |
| 458 |
profile: Profile, |
| 459 |
profile_install_name: str, |
| 460 |
profile_exists: bool, |
| 461 |
logfn: None | Callable = None, |
| 462 |
) -> None: |
| 463 |
"""Write profile to destination. |
| 464 |
|
| 465 |
Args: |
| 466 |
profile (Profile): Profile object to write. |
| 467 |
profile_install_name (str): Path where the profile should be installed. |
| 468 |
profile_exists (bool): Whether the profile already exists at the |
| 469 |
destination. |
| 470 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 471 |
""" |
| 472 |
profile_install_dir = os.path.dirname(profile_install_name) |
| 473 |
if not os.path.isdir(profile_install_dir): |
| 474 |
os.makedirs(profile_install_dir) |
| 475 |
# colormgr seems to have a bug where the first attempt at importing a |
| 476 |
# specific profile can time out. This seems to be work-aroundable by |
| 477 |
# writing the profile ourself first, and then importing. |
| 478 |
if not profile.filename or not profile_exists: |
| 479 |
if logfn: |
| 480 |
logfn("Writing", profile_install_name) |
| 481 |
profile.filename = profile_install_name |
| 482 |
profile.write() |
| 483 |
|
| 484 |
|
| 485 |
def install_profile_with_colord( |
| 486 |
device_id: str, |
| 487 |
profile: Profile, |
| 488 |
timeout: float = CD_CLIENT_IMPORT_DAEMON_TIMEOUT / 1000.0, |
| 489 |
logfn: None | Callable = None, |
| 490 |
) -> None: |
| 491 |
"""Install profile for device. |
| 492 |
|
| 493 |
Args: |
| 494 |
device_id (str): Device ID to install the profile for. |
| 495 |
profile (Profile): Profile object to install. |
| 496 |
timeout (float): Time to allow for colord to pick up new profiles (recommended |
| 497 |
not below 2 secs). |
| 498 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 499 |
|
| 500 |
Raises: |
| 501 |
CDError: If there is an error connecting to colord or if the profile |
| 502 |
could not be made default for the device. |
| 503 |
CDTimeoutError: If querying for the profile takes too long. |
| 504 |
""" |
| 505 |
profile_install_name, profile_exists, profile_id = get_profile_install_parameters( |
| 506 |
profile, logfn |
| 507 |
) |
| 508 |
write_profile_to_destination(profile, profile_install_name, profile_exists, logfn) |
| 509 |
|
| 510 |
client = client_connect() |
| 511 |
cdprofile = query_colord_for_newly_added_profile(profile_id, timeout=timeout) |
| 512 |
|
| 513 |
# Connect to profile |
| 514 |
if not cdprofile.connect_sync(cancellable): |
| 515 |
raise CDError("Could not connect to profile") |
| 516 |
|
| 517 |
# Connect to existing device |
| 518 |
device = device_connect(client, device_id) |
| 519 |
|
| 520 |
# Add profile to device |
| 521 |
try: |
| 522 |
device.add_profile_sync(Colord.DeviceRelation.HARD, cdprofile, cancellable) |
| 523 |
except Exception as exception: |
| 524 |
# Profile may already have been added |
| 525 |
warnings.warn(safe_str(exception), Warning, stacklevel=2) |
| 526 |
|
| 527 |
# Make profile default for device |
| 528 |
if not device.make_profile_default_sync(cdprofile, cancellable): |
| 529 |
raise CDError( |
| 530 |
f"Could not make profile {profile_id} default for device {device_id}" |
| 531 |
) |
| 532 |
|
| 533 |
|
| 534 |
def install_profile_with_dbus( |
| 535 |
device_id: str, |
| 536 |
profile: Profile, |
| 537 |
timeout: float = CD_CLIENT_IMPORT_DAEMON_TIMEOUT / 1000.0, |
| 538 |
logfn: None | Callable = None, |
| 539 |
) -> None: |
| 540 |
"""Install profile for device with DBusObject. |
| 541 |
|
| 542 |
Args: |
| 543 |
device_id (str): Device ID to install the profile for. |
| 544 |
profile (Profile): Profile object to install. |
| 545 |
timeout (float): Time to allow for colord to pick up new profiles (recommended |
| 546 |
not below 2 secs). |
| 547 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 548 |
""" |
| 549 |
if not logfn: |
| 550 |
# let's reduce complexity a bit |
| 551 |
def logfn(*args, **kwargs) -> None: |
| 552 |
"""Dummy log function that does nothing.""" |
| 553 |
|
| 554 |
profile_install_name, profile_exists, profile_id = get_profile_install_parameters( |
| 555 |
profile, logfn |
| 556 |
) |
| 557 |
write_profile_to_destination(profile, profile_install_name, profile_exists, logfn) |
| 558 |
|
| 559 |
cdprofile = None |
| 560 |
|
| 561 |
# Query colord for profile |
| 562 |
with contextlib.suppress(CDObjectQueryError): |
| 563 |
cdprofile = get_object_path(profile_id, "profile") |
| 564 |
# If profile not found, it will raise a CDObjectQueryError |
| 565 |
|
| 566 |
if not (colormgr := which("colormgr")): |
| 567 |
raise CDError("'colormgr' helper program not found!") |
| 568 |
|
| 569 |
cmd = str(colormgr) |
| 570 |
if not cdprofile: |
| 571 |
cdprofile = import_profile( |
| 572 |
cmd, profile, profile_install_name, profile_id, timeout=timeout, logfn=logfn |
| 573 |
) |
| 574 |
|
| 575 |
# Find device object path |
| 576 |
device = get_object_path(device_id, "device") |
| 577 |
|
| 578 |
add_profile_to_device(cmd, device, cdprofile, logfn) |
| 579 |
make_profile_default_for_device( |
| 580 |
cmd, profile_id, device_id, device, cdprofile, logfn=logfn |
| 581 |
) |
| 582 |
|
| 583 |
|
| 584 |
def import_profile( |
| 585 |
cmd: str, |
| 586 |
profile: Profile, |
| 587 |
profile_install_name: str, |
| 588 |
profile_id: str, |
| 589 |
timeout: float = CD_CLIENT_IMPORT_DAEMON_TIMEOUT / 1000.0, |
| 590 |
logfn: None | Callable = None, |
| 591 |
) -> None | str: |
| 592 |
"""Import profile using colormgr. |
| 593 |
|
| 594 |
Args: |
| 595 |
cmd (str): Command to run, e.g., "colormgr". |
| 596 |
profile (Profile): Profile object to import. |
| 597 |
profile_install_name (str): Path where the profile should be installed. |
| 598 |
profile_id (str): ID of the profile. |
| 599 |
timeout (float): Time to allow for colord to pick up new profiles |
| 600 |
(recommended not below 2 secs). |
| 601 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 602 |
|
| 603 |
Raises: |
| 604 |
CDError: If there is an error running the command or if the command |
| 605 |
fails. |
| 606 |
CDTimeoutError: If querying for the profile takes too long. |
| 607 |
|
| 608 |
Returns: |
| 609 |
None | str: Object path of the imported profile. |
| 610 |
""" |
| 611 |
# Import profile |
| 612 |
if not logfn: |
| 613 |
# let's reduce complexity a bit |
| 614 |
def logfn(*args, **kwargs) -> None: |
| 615 |
"""Dummy log function that does nothing.""" |
| 616 |
|
| 617 |
logfn("-" * 80) |
| 618 |
logfn(lang.getstr("commandline")) |
| 619 |
args = [cmd, "import-profile", safe_str(profile.filename)] |
| 620 |
|
| 621 |
from DisplayCAL.worker import printcmdline |
| 622 |
|
| 623 |
printcmdline(args[0], args[1:], fn=logfn) |
| 624 |
logfn("") |
| 625 |
maxtries = 3 |
| 626 |
for n in range(1, maxtries + 1): |
| 627 |
logfn(f"Trying to import profile, attempt {n}...") |
| 628 |
try: |
| 629 |
process = sp.Popen(args, stdout=sp.PIPE, stderr=sp.STDOUT) |
| 630 |
stdout, _ = process.communicate() |
| 631 |
except Exception as exception: |
| 632 |
raise CDError(safe_str(exception)) from exception |
| 633 |
if stdout.strip(): |
| 634 |
logfn(stdout.strip()) |
| 635 |
if process.returncode == 0 or os.path.isfile(profile_install_name): |
| 636 |
logfn("...ok") |
| 637 |
break |
| 638 |
logfn("...failed!") |
| 639 |
|
| 640 |
if process.returncode != 0 and not os.path.isfile(profile_install_name): |
| 641 |
raise CDTimeoutError( |
| 642 |
f"Trying to import profile '{profile.filename}' failed after {n} tries." |
| 643 |
) |
| 644 |
|
| 645 |
return query_colord_for_newly_added_profile(profile_id, timeout=timeout) |
| 646 |
|
| 647 |
|
| 648 |
def query_colord_for_newly_added_profile( |
| 649 |
profile_id: str, timeout: float = CD_CLIENT_IMPORT_DAEMON_TIMEOUT / 1000.0 |
| 650 |
) -> str: |
| 651 |
"""Query colord for newly added profile. |
| 652 |
|
| 653 |
Args: |
| 654 |
profile_id (str): ID of the profile to query for. |
| 655 |
timeout (float): Time to allow for colord to pick up new profiles |
| 656 |
(recommended not below 2 secs). |
| 657 |
|
| 658 |
Raises: |
| 659 |
CDTimeoutError: If querying for the profile takes too long. |
| 660 |
|
| 661 |
Returns: |
| 662 |
str: Object path of the queried profile. |
| 663 |
""" |
| 664 |
cdprofile = None |
| 665 |
for _ in range(int(timeout / 1.0)): |
| 666 |
# Profile might not be found so suppress the error |
| 667 |
with contextlib.suppress(CDObjectQueryError): |
| 668 |
cdprofile = get_object_path(profile_id, "profile") |
| 669 |
if cdprofile: |
| 670 |
break |
| 671 |
# Give colord time to pick up the profile |
| 672 |
sleep(1) |
| 673 |
|
| 674 |
if not cdprofile: |
| 675 |
raise CDTimeoutError( |
| 676 |
f"Querying for profile {profile_id!r} returned no result for {timeout} secs" |
| 677 |
) |
| 678 |
|
| 679 |
return cdprofile |
| 680 |
|
| 681 |
|
| 682 |
def add_profile_to_device( |
| 683 |
cmd: str, device: str, cdprofile: str, logfn: None | Callable = None |
| 684 |
) -> None: |
| 685 |
"""Add profile to device. |
| 686 |
|
| 687 |
Ignore returncode as profile may already have been added. |
| 688 |
|
| 689 |
Args: |
| 690 |
cmd (str): Command to run, e.g., "colormgr". |
| 691 |
device (str): Device object path. |
| 692 |
cdprofile (str): Profile object path. |
| 693 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 694 |
|
| 695 |
Raises: |
| 696 |
CDError: If there is an error running the command or if the command |
| 697 |
fails. |
| 698 |
""" |
| 699 |
from DisplayCAL.worker import printcmdline |
| 700 |
|
| 701 |
logfn("-" * 80) |
| 702 |
logfn(lang.getstr("commandline")) |
| 703 |
|
| 704 |
args = [cmd, "device-add-profile", device, cdprofile] |
| 705 |
|
| 706 |
printcmdline(args[0], args[1:], fn=logfn) |
| 707 |
logfn("") |
| 708 |
try: |
| 709 |
p = sp.Popen(args, stdout=sp.PIPE, stderr=sp.STDOUT) |
| 710 |
stdout, _ = p.communicate() |
| 711 |
except Exception as exception: |
| 712 |
raise CDError(safe_str(exception)) from exception |
| 713 |
|
| 714 |
if stdout.strip(): |
| 715 |
logfn(stdout.strip()) |
| 716 |
|
| 717 |
|
| 718 |
def make_profile_default_for_device( |
| 719 |
cmd: str, |
| 720 |
profile_id: str, |
| 721 |
device_id: str, |
| 722 |
device: str, |
| 723 |
cdprofile: str, |
| 724 |
logfn: None | Callable = None, |
| 725 |
) -> None: |
| 726 |
"""Make profile default for device. |
| 727 |
|
| 728 |
Args: |
| 729 |
cmd (str): Command to run, e.g., "colormgr". |
| 730 |
profile_id (str): ID of the profile to make default. |
| 731 |
device_id (str): ID of the device to make the profile default for. |
| 732 |
device (str): Device object path. |
| 733 |
cdprofile (str): Profile object path. |
| 734 |
logfn (callable, optional): Function to log messages. Defaults to None. |
| 735 |
|
| 736 |
Raises: |
| 737 |
CDError: If there is an error running the command or if the command |
| 738 |
fails. |
| 739 |
""" |
| 740 |
from DisplayCAL.worker import printcmdline |
| 741 |
|
| 742 |
logfn("") |
| 743 |
logfn(lang.getstr("commandline")) |
| 744 |
|
| 745 |
# Make profile default for device |
| 746 |
args = [cmd, "device-make-profile-default", device, cdprofile] |
| 747 |
printcmdline(args[0], args[1:], fn=logfn) |
| 748 |
logfn("") |
| 749 |
try: |
| 750 |
p = sp.Popen(args, stdout=sp.PIPE, stderr=sp.STDOUT) |
| 751 |
stdout, stderr = p.communicate() |
| 752 |
except Exception as exception: |
| 753 |
raise CDError(safe_str(exception)) from exception |
| 754 |
else: |
| 755 |
if p.returncode != 0: |
| 756 |
raise CDError( |
| 757 |
stdout.strip() |
| 758 |
or f"Could not make profile {profile_id} default for device {device_id}" |
| 759 |
) |
| 760 |
if stdout.strip(): |
| 761 |
logfn(stdout.strip()) |
| 762 |
|
| 763 |
|
| 764 |
def quirk_manufacturer(manufacturer: str) -> str: |
| 765 |
"""Correct manufacturer name for colord. |
| 766 |
|
| 767 |
Args: |
| 768 |
manufacturer (str): Manufacturer name to correct. |
| 769 |
|
| 770 |
Returns: |
| 771 |
str: Corrected manufacturer name. |
| 772 |
""" |
| 773 |
if ( |
| 774 |
Colord |
| 775 |
and not isinstance(Colord, DBusObject) |
| 776 |
and hasattr(Colord, "quirk_vendor_name") |
| 777 |
): |
| 778 |
return Colord.quirk_vendor_name(manufacturer) |
| 779 |
|
| 780 |
# Correct some company names |
| 781 |
for old, new in quirk_cache["vendor_names"].items(): |
| 782 |
if manufacturer.startswith(old): |
| 783 |
manufacturer = new |
| 784 |
break |
| 785 |
|
| 786 |
# Get rid of suffixes |
| 787 |
for suffix in quirk_cache["suffixes"]: |
| 788 |
if manufacturer.endswith(suffix): |
| 789 |
manufacturer = manufacturer[0 : len(manufacturer) - len(suffix)] |
| 790 |
|
| 791 |
return manufacturer.rstrip() |
| 792 |
|
| 793 |
|
| 794 |
class Object(DBusObject): |
| 795 |
"""Base class for colord objects. |
| 796 |
|
| 797 |
Args: |
| 798 |
object_path (str): D-Bus object path of the colord object. |
| 799 |
object_type (str): Type of the colord object, e.g., "Device" or |
| 800 |
"Profile". |
| 801 |
""" |
| 802 |
|
| 803 |
def __init__(self, object_path: str, object_type: str) -> None: |
| 804 |
try: |
| 805 |
super().__init__( |
| 806 |
BUSTYPE_SYSTEM, |
| 807 |
"org.freedesktop.ColorManager", |
| 808 |
object_path, |
| 809 |
object_type, |
| 810 |
) |
| 811 |
except DBusException as exception: |
| 812 |
raise CDError(safe_str(exception)) from exception |
| 813 |
self._object_type = object_type |
| 814 |
|
| 815 |
_properties = DBusObject.properties |
| 816 |
|
| 817 |
@property |
| 818 |
def properties(self) -> dict: |
| 819 |
"""Get properties of the object. |
| 820 |
|
| 821 |
Raises: |
| 822 |
CDError: If there is an error retrieving the properties. |
| 823 |
|
| 824 |
Returns: |
| 825 |
dict: Dictionary of properties of the object. |
| 826 |
""" |
| 827 |
try: |
| 828 |
properties = {} |
| 829 |
for key in self._properties: |
| 830 |
value = self._properties[key] |
| 831 |
if key == "Profiles": |
| 832 |
value = [Profile(object_path) for object_path in value] |
| 833 |
properties[key] = value |
| 834 |
return properties |
| 835 |
except DBusException as exception: |
| 836 |
raise CDError(safe_str(exception)) from exception |
| 837 |
|
| 838 |
|
| 839 |
class Device(Object): |
| 840 |
"""Device object. |
| 841 |
|
| 842 |
Args: |
| 843 |
object_path (str): D-Bus object path of the colord device. |
| 844 |
""" |
| 845 |
|
| 846 |
def __init__(self, object_path: str) -> None: |
| 847 |
super().__init__(object_path, "Device") |
| 848 |
|
| 849 |
|
| 850 |
class Profile(Object): |
| 851 |
"""Profile object. |
| 852 |
|
| 853 |
Args: |
| 854 |
object_path (str): D-Bus object path of the colord profile. |
| 855 |
""" |
| 856 |
|
| 857 |
def __init__(self, object_path: str) -> None: |
| 858 |
super().__init__(object_path, "Profile") |
| 859 |
|
| 860 |
|
| 861 |
class CDError(Exception): |
| 862 |
"""Base class for colord errors.""" |
| 863 |
|
| 864 |
|
| 865 |
class CDObjectQueryError(CDError): |
| 866 |
"""Object query error.""" |
| 867 |
|
| 868 |
|
| 869 |
class CDObjectNotFoundError(CDObjectQueryError): |
| 870 |
"""Object not found error.""" |
| 871 |
|
| 872 |
|
| 873 |
class CDTimeoutError(CDError): |
| 874 |
"""Timeout error.""" |
| 875 |
|
| 876 |
|
| 877 |
if __name__ == "__main__": |
| 878 |
import sys |
| 879 |
|
| 880 |
for arg in sys.argv[1:]: |
| 881 |
print(get_default_profile(arg)) |