| 1 |
"""DisplayCAL main module.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import atexit |
| 6 |
import errno |
| 7 |
import getpass |
| 8 |
import glob |
| 9 |
import os |
| 10 |
import platform |
| 11 |
import socket |
| 12 |
import subprocess as sp |
| 13 |
import sys |
| 14 |
import threading |
| 15 |
from time import sleep |
| 16 |
from typing import TYPE_CHECKING, Any |
| 17 |
|
| 18 |
# Python version check |
| 19 |
from DisplayCAL.meta import PY_MAXVERSION, PY_MINVERSION |
| 20 |
|
| 21 |
PYVER = sys.version_info[:2] |
| 22 |
if PYVER < PY_MINVERSION or PYVER > PY_MAXVERSION: |
| 23 |
raise RuntimeError( |
| 24 |
"Need Python version >= {} <= {}, got {}".format( |
| 25 |
".".join(str(n) for n in PY_MINVERSION), |
| 26 |
".".join(str(n) for n in PY_MAXVERSION), |
| 27 |
sys.version.split()[0], |
| 28 |
) |
| 29 |
) |
| 30 |
|
| 31 |
if sys.platform not in ("win32", "darwin"): |
| 32 |
import distro |
| 33 |
|
| 34 |
from DisplayCAL import localization as lang |
| 35 |
from DisplayCAL.config import ( |
| 36 |
APPBASENAME, |
| 37 |
CONFIG_HOME, |
| 38 |
DATA_HOME, |
| 39 |
ENC, |
| 40 |
EXE_EXT, |
| 41 |
EXENAME, |
| 42 |
FS_ENC, |
| 43 |
LOGDIR, |
| 44 |
PYNAME, |
| 45 |
RES_FILES, |
| 46 |
RUNTYPE, |
| 47 |
get_data_path, |
| 48 |
getcfg, |
| 49 |
initcfg, |
| 50 |
) |
| 51 |
from DisplayCAL.debughelpers import ResourceError, handle_error |
| 52 |
from DisplayCAL.log import LOG |
| 53 |
from DisplayCAL.meta import VERSION_STRING |
| 54 |
from DisplayCAL.meta import ( |
| 55 |
NAME as APPNAME, |
| 56 |
) |
| 57 |
from DisplayCAL.multiprocess import mp |
| 58 |
from DisplayCAL.options import VERBOSE |
| 59 |
from DisplayCAL.util_os import FileLock, LockingError, UnlockingError |
| 60 |
|
| 61 |
if sys.platform == "win32": |
| 62 |
from DisplayCAL.util_win import win_ver |
| 63 |
elif sys.platform == "darwin": |
| 64 |
from platform import mac_ver |
| 65 |
|
| 66 |
if TYPE_CHECKING: |
| 67 |
from collections.abc import Iterator |
| 68 |
from types import TracebackType |
| 69 |
if sys.version_info >= (3, 11): |
| 70 |
from typing import Self |
| 71 |
else: |
| 72 |
from typing_extensions import Self |
| 73 |
|
| 74 |
|
| 75 |
def _excepthook( |
| 76 |
etype: None | type[BaseException], |
| 77 |
value: None | BaseException, |
| 78 |
tb: None | TracebackType, |
| 79 |
) -> None: |
| 80 |
"""Global exception handler. |
| 81 |
|
| 82 |
Args: |
| 83 |
etype (type[BaseException]): Exception type. |
| 84 |
value (BaseException): Exception instance. |
| 85 |
tb (TracebackType): Traceback object. |
| 86 |
""" |
| 87 |
# Suppress a known wxWidgets/macOS bug: when a wx.FileDialog is dismissed |
| 88 |
# on macOS, the re-activation of the parent window causes wxWidgets to |
| 89 |
# access wxArrayString with an invalid index inside the ActivateEvent |
| 90 |
# dispatch. The Python ActivateEvent wrapper is returned successfully but |
| 91 |
# with a pending exception, which CPython promotes to SystemError. The |
| 92 |
# underlying file operation completes normally; this error is purely |
| 93 |
# cosmetic and confusing to the user. |
| 94 |
if ( |
| 95 |
etype is SystemError |
| 96 |
and "ActivateEvent" in str(value) |
| 97 |
and type(getattr(value, "__cause__", None)).__name__ == "wxAssertionError" |
| 98 |
): |
| 99 |
return |
| 100 |
handle_error((etype, value, tb)) |
| 101 |
|
| 102 |
|
| 103 |
sys.excepthook = _excepthook |
| 104 |
|
| 105 |
MULTI_INSTANCE_APP_NAMES = ( |
| 106 |
"curve-viewer", |
| 107 |
"profile-info", |
| 108 |
"scripting-client", |
| 109 |
"synthprofile", |
| 110 |
"testchart-editor", |
| 111 |
) |
| 112 |
"""Allow multiple instances only for curve viewer, profile info, |
| 113 |
scripting client, synthetic profile creator and testchart editor.""" |
| 114 |
|
| 115 |
|
| 116 |
def _main( |
| 117 |
module: str, name: str, app_lock_file_name: str, probe_ports: bool = True |
| 118 |
) -> None: |
| 119 |
"""Main function. |
| 120 |
|
| 121 |
Args: |
| 122 |
module (str): Module name. |
| 123 |
name (str): Application name. |
| 124 |
app_lock_file_name (str): Lock file name. |
| 125 |
probe_ports (bool, optional): Whether to probe ports of other |
| 126 |
instances. Default is True. |
| 127 |
""" |
| 128 |
with AppLock( |
| 129 |
app_lock_file_name, "a+", False, module in MULTI_INSTANCE_APP_NAMES |
| 130 |
) as lock: |
| 131 |
print(f"Acquired lock file: {lock}") |
| 132 |
LOG("=" * 80) |
| 133 |
|
| 134 |
print_system_version_information() |
| 135 |
initialize_fault_handler() |
| 136 |
initialize_wx_module() |
| 137 |
set_high_dpi_awareness() |
| 138 |
initcfg(module) |
| 139 |
lock_to_pids_and_ports = {} |
| 140 |
if probe_ports and not probe_used_ports( |
| 141 |
module, name, app_lock_file_name, lock, lock_to_pids_and_ports |
| 142 |
): |
| 143 |
return |
| 144 |
|
| 145 |
if not lock: |
| 146 |
# If a race condition occurs, do not start another instance |
| 147 |
print("Not starting another instance.") |
| 148 |
return |
| 149 |
|
| 150 |
initialize_app(module, app_lock_file_name, lock_to_pids_and_ports) |
| 151 |
run_app(module) |
| 152 |
|
| 153 |
|
| 154 |
def print_application_version() -> None: |
| 155 |
"""Print application version.""" |
| 156 |
if VERBOSE >= 1: |
| 157 |
version = VERSION_STRING |
| 158 |
print(PYNAME + RUNTYPE, version, "") |
| 159 |
|
| 160 |
|
| 161 |
def print_os_version() -> None: |
| 162 |
"""Print OS version.""" |
| 163 |
if sys.platform == "darwin": |
| 164 |
# Python's platform.platform output is useless under Mac OS X |
| 165 |
# (e.g. 'Darwin-15.0.0-x86_64-i386-64bit' for Mac OS X 10.11 El Capitan) |
| 166 |
print(f"Mac OS X {mac_ver()[0]} {mac_ver()[-1]}") |
| 167 |
elif sys.platform == "win32": |
| 168 |
machine = platform.machine() |
| 169 |
print( |
| 170 |
*[v for v in win_ver() if v] |
| 171 |
+ [ |
| 172 |
{"AMD64": "x86_64"}.get(machine, machine), |
| 173 |
] |
| 174 |
) |
| 175 |
else: |
| 176 |
# Linux |
| 177 |
print( |
| 178 |
f"{distro.id()} {distro.version()} {distro.codename()}", |
| 179 |
platform.machine(), |
| 180 |
) |
| 181 |
|
| 182 |
|
| 183 |
def print_python_version() -> None: |
| 184 |
"""Print Python version.""" |
| 185 |
print(f"Python {sys.version}") |
| 186 |
|
| 187 |
|
| 188 |
def print_cafile_details() -> None: |
| 189 |
"""Print CA file details.""" |
| 190 |
cafile = os.getenv("SSL_CERT_FILE") |
| 191 |
if cafile: |
| 192 |
print("CA file", cafile) |
| 193 |
|
| 194 |
|
| 195 |
def print_system_version_information() -> None: |
| 196 |
"""Print system version information.""" |
| 197 |
print_application_version() |
| 198 |
print_os_version() |
| 199 |
print_python_version() |
| 200 |
print_cafile_details() |
| 201 |
|
| 202 |
|
| 203 |
def initialize_fault_handler() -> None: |
| 204 |
"""Initialize faulthandler to log crashes.""" |
| 205 |
# Enable faulthandler |
| 206 |
try: |
| 207 |
import faulthandler |
| 208 |
except Exception as exception: |
| 209 |
print(exception) |
| 210 |
else: |
| 211 |
try: |
| 212 |
faulthandler.enable(open(os.path.join(LOGDIR, f"{PYNAME}-fault.log"), "w")) # noqa: SIM115 |
| 213 |
except Exception as exception: |
| 214 |
print(exception) |
| 215 |
else: |
| 216 |
print("Faulthandler", getattr(faulthandler, "__version__", "")) |
| 217 |
|
| 218 |
|
| 219 |
def initialize_wx_module() -> None: |
| 220 |
"""Initialize wx module.""" |
| 221 |
try: |
| 222 |
from DisplayCAL.wx_addons import wx |
| 223 |
except ImportError as e: |
| 224 |
missing = str(e) |
| 225 |
msg = f"Failed to import wxPython: {missing}\n" |
| 226 |
if "libwx_gtk" in missing or ".so" in missing: |
| 227 |
msg += ( |
| 228 |
"A wxWidgets shared library could not be found. " |
| 229 |
"This usually means wxPython was compiled from source against a " |
| 230 |
"system wxWidgets that is missing optional components (e.g. the " |
| 231 |
"HTML or XRC library).\n" |
| 232 |
"Try installing the full wxWidgets development package for your " |
| 233 |
"distribution, then reinstall wxPython:\n" |
| 234 |
" Debian/Ubuntu: sudo apt install libwx-gtk3u-dev\n" |
| 235 |
" Fedora/RHEL: sudo dnf install wxGTK-devel\n" |
| 236 |
" Arch: sudo pacman -S wxwidgets-gtk3\n" |
| 237 |
" Slackware: install the wxGTK3 package with HTML support\n" |
| 238 |
"Alternatively, install a pre-built wxPython wheel if one is " |
| 239 |
"available for your platform at https://wxpython.org/pages/downloads/" |
| 240 |
) |
| 241 |
sys.exit(msg) |
| 242 |
|
| 243 |
if "phoenix" in wx.PlatformInfo: |
| 244 |
# py2exe helper so wx.xml gets picked up |
| 245 |
from wx import xml # noqa: F401 |
| 246 |
print(f"wxPython {wx.version()}") |
| 247 |
print(f"Encoding: {ENC}") |
| 248 |
print(f"File system encoding: {FS_ENC}") |
| 249 |
|
| 250 |
|
| 251 |
def set_high_dpi_awareness() -> None: |
| 252 |
"""Set high DPI awareness on Windows 8.1 and later.""" |
| 253 |
if sys.platform != "win32" or sys.getwindowsversion() < (6, 2): |
| 254 |
return |
| 255 |
|
| 256 |
# HighDPI support |
| 257 |
try: |
| 258 |
import ctypes |
| 259 |
|
| 260 |
shcore = ctypes.windll.shcore |
| 261 |
except Exception as exception: |
| 262 |
print("Warning - could not load shcore:", exception) |
| 263 |
else: |
| 264 |
if hasattr(shcore, "SetProcessDpiAwareness"): |
| 265 |
try: |
| 266 |
# 1 = System DPI aware (wxPython currently does not |
| 267 |
# support per-monitor DPI) |
| 268 |
shcore.SetProcessDpiAwareness(1) |
| 269 |
except Exception as exception: |
| 270 |
print("Warning - SetProcessDpiAwareness() failed:", exception) |
| 271 |
else: |
| 272 |
print("Warning - SetProcessDpiAwareness not found in shcore") |
| 273 |
|
| 274 |
|
| 275 |
def probe_used_ports( |
| 276 |
module: str, |
| 277 |
name: str, |
| 278 |
app_lock_file_name: str, |
| 279 |
lock: AppLock, |
| 280 |
lock_to_pids_and_ports: dict, |
| 281 |
) -> bool: |
| 282 |
"""Probe used ports to check for other instances. |
| 283 |
|
| 284 |
Args: |
| 285 |
module (str): Module name. |
| 286 |
name (str): Application name. |
| 287 |
app_lock_file_name (str): Lock file name. |
| 288 |
lock (AppLock): Lock file object. |
| 289 |
lock_to_pids_and_ports (dict): Mapping of lock files to PIDs and ports. |
| 290 |
|
| 291 |
Returns: |
| 292 |
bool: True if no other instance is running or multiple instances |
| 293 |
are allowed, False otherwise. |
| 294 |
""" |
| 295 |
check_for_currently_used_ports(app_lock_file_name, lock, lock_to_pids_and_ports) |
| 296 |
|
| 297 |
if module in MULTI_INSTANCE_APP_NAMES: |
| 298 |
return True |
| 299 |
|
| 300 |
incoming = check_lock_files_and_probe_ports( |
| 301 |
module, app_lock_file_name, lock, lock_to_pids_and_ports |
| 302 |
) |
| 303 |
|
| 304 |
if incoming is not None: |
| 305 |
# Other instance running? |
| 306 |
lang.init() |
| 307 |
if incoming == "ok": |
| 308 |
# Successfully sent our request |
| 309 |
print(lang.getstr("app.otherinstance.notified")) |
| 310 |
elif module == "apply-profiles": |
| 311 |
print("Not starting another instance.") |
| 312 |
else: |
| 313 |
# Other instance busy? |
| 314 |
handle_error(lang.getstr("app.otherinstance", name)) |
| 315 |
# Exit |
| 316 |
return False |
| 317 |
return True |
| 318 |
|
| 319 |
|
| 320 |
def check_for_currently_used_ports( |
| 321 |
app_lock_file_name: str, |
| 322 |
lock: AppLock, |
| 323 |
lock_to_pids_and_ports: dict, |
| 324 |
) -> None: |
| 325 |
"""Check for currently used ports. |
| 326 |
|
| 327 |
Args: |
| 328 |
app_lock_file_name (str): Lock file name. |
| 329 |
lock (AppLock): Lock file object. |
| 330 |
lock_to_pids_and_ports (dict): Mapping of lock files to PIDs and ports. |
| 331 |
""" |
| 332 |
lockfilenames = glob.glob(os.path.join(CONFIG_HOME, "*.lock")) |
| 333 |
for lockfilename in lockfilenames: |
| 334 |
try: |
| 335 |
if lock and lockfilename == app_lock_file_name: |
| 336 |
lockfile = lock |
| 337 |
lock.seek(0) |
| 338 |
else: |
| 339 |
lockfile = AppLock(lockfilename, "r", False, True) |
| 340 |
if lockfile: |
| 341 |
update_lock_to_pid_ports(lock_to_pids_and_ports, lockfilename, lockfile) |
| 342 |
if not lock or lockfilename != app_lock_file_name: |
| 343 |
lockfile.unlock() |
| 344 |
except OSError as exception: |
| 345 |
# This shouldn't happen |
| 346 |
print(f"Warning - could not read lockfile {lockfilename}:", exception) |
| 347 |
|
| 348 |
|
| 349 |
def update_lock_to_pid_ports( |
| 350 |
lock_to_pids_and_ports: dict, |
| 351 |
lockfilename: str, |
| 352 |
lockfile: AppLock, |
| 353 |
) -> None: |
| 354 |
"""Update mapping of lock files to PIDs and ports. |
| 355 |
|
| 356 |
Args: |
| 357 |
lock_to_pids_and_ports (dict): Mapping of lock files to PIDs and ports. |
| 358 |
lockfilename (str): Lock file name. |
| 359 |
lockfile (AppLock): Lock file object. |
| 360 |
""" |
| 361 |
if lockfilename not in lock_to_pids_and_ports: |
| 362 |
lock_to_pids_and_ports[lockfilename] = [] |
| 363 |
for ln, line in enumerate(lockfile.read().splitlines(), 1): |
| 364 |
if ":" in line: |
| 365 |
# DisplayCAL >= 3.8.8.2 with localhost blocked |
| 366 |
pid, port = line.split(":", 1) |
| 367 |
if pid: |
| 368 |
try: |
| 369 |
pid = int(pid) |
| 370 |
except ValueError: |
| 371 |
# This shouldn't happen |
| 372 |
print( |
| 373 |
"Warning - couldn't parse PID as int: " |
| 374 |
f"{pid!r} ({lockfilename} line {ln})" |
| 375 |
) |
| 376 |
pid = None |
| 377 |
else: |
| 378 |
print("Existing client using PID", pid) |
| 379 |
else: |
| 380 |
# DisplayCAL <= 3.8.8.1 or localhost ok |
| 381 |
pid = None |
| 382 |
port = line |
| 383 |
if port: |
| 384 |
try: |
| 385 |
port = int(port) |
| 386 |
except ValueError: |
| 387 |
# This shouldn't happen |
| 388 |
print( |
| 389 |
"Warning - couldn't parse port as int: " |
| 390 |
f"{port!r} ({lockfilename} line {ln})" |
| 391 |
) |
| 392 |
port = None |
| 393 |
else: |
| 394 |
print("Existing client using port", port) |
| 395 |
if pid or port: |
| 396 |
lock_to_pids_and_ports[lockfilename].append((pid, port)) |
| 397 |
|
| 398 |
|
| 399 |
def check_lock_files_and_probe_ports( |
| 400 |
module: str, |
| 401 |
app_lock_file_name: str, |
| 402 |
lock: AppLock, |
| 403 |
lock_to_pids_and_ports: dict, |
| 404 |
) -> None | str: |
| 405 |
"""Check lockfile(s) and probe port(s). |
| 406 |
|
| 407 |
Args: |
| 408 |
module (str): Module name. |
| 409 |
app_lock_file_name (str): Lock file name. |
| 410 |
lock (AppLock): Lock file object. |
| 411 |
lock_to_pids_and_ports (dict): Mapping of lock files to PIDs and ports. |
| 412 |
|
| 413 |
Returns: |
| 414 |
None | str: Incoming status. |
| 415 |
""" |
| 416 |
host = "127.0.0.1" |
| 417 |
|
| 418 |
# Check lockfile(s) and probe port(s) |
| 419 |
incoming = None |
| 420 |
for lockfilename in [app_lock_file_name]: |
| 421 |
incoming = None |
| 422 |
pids_ports = lock_to_pids_and_ports.get(lockfilename) |
| 423 |
if pids_ports: |
| 424 |
incoming = connect_and_notify_running_instance( |
| 425 |
module, lock, host, pids_ports |
| 426 |
) |
| 427 |
pid, _ = pids_ports[0] |
| 428 |
else: |
| 429 |
pid = None |
| 430 |
if not incoming: |
| 431 |
incoming = terminate_conflicting_instance( |
| 432 |
module, |
| 433 |
lockfilename, |
| 434 |
lock, |
| 435 |
pid, |
| 436 |
incoming, |
| 437 |
) |
| 438 |
|
| 439 |
if incoming == "ok": |
| 440 |
# Successfully sent our request |
| 441 |
if module == "apply-profiles": |
| 442 |
# Wait for lockfile to be removed, in which case |
| 443 |
# we know the running instance has successfully |
| 444 |
# closed. |
| 445 |
print( |
| 446 |
"Waiting for existing instance to exit and delete lockfile", |
| 447 |
lockfilename, |
| 448 |
) |
| 449 |
while os.path.isfile(lockfilename): |
| 450 |
sleep(0.05) |
| 451 |
lock.lock() |
| 452 |
print("Existing instance exited.") |
| 453 |
incoming = None |
| 454 |
lock_to_pids_and_ports.pop(lockfilename, None) |
| 455 |
break |
| 456 |
|
| 457 |
return incoming |
| 458 |
|
| 459 |
|
| 460 |
def connect_and_notify_running_instance( |
| 461 |
module: str, |
| 462 |
lock: AppLock, |
| 463 |
host: str, |
| 464 |
pids_ports: list, |
| 465 |
) -> None | str: |
| 466 |
"""Connect to running instance and notify it. |
| 467 |
|
| 468 |
Args: |
| 469 |
module (str): Module name. |
| 470 |
lock (AppLock): Lock file object. |
| 471 |
host (str): Host address. |
| 472 |
pids_ports (list): List of tuples containing PIDs and ports. |
| 473 |
|
| 474 |
Returns: |
| 475 |
None | str: Incoming status. |
| 476 |
""" |
| 477 |
_, port = pids_ports[0] |
| 478 |
incoming = None |
| 479 |
appsocket = AppSocket() |
| 480 |
if not appsocket or not port: |
| 481 |
return incoming |
| 482 |
|
| 483 |
print(f"Connecting to {port}...") |
| 484 |
if appsocket.connect(host, port): |
| 485 |
print("Connected to", port) |
| 486 |
# Other instance already running? |
| 487 |
# Get appname to check if expected app is actually |
| 488 |
# running under that port |
| 489 |
print("Getting instance name") |
| 490 |
if appsocket.send("getappname"): |
| 491 |
print("Sent scripting request, awaiting response...") |
| 492 |
data_read = appsocket.read() |
| 493 |
incoming = data_read.rstrip("\4") |
| 494 |
print(f"Got response: {incoming!r}") |
| 495 |
# translate incoming values |
| 496 |
incoming = { |
| 497 |
PYNAME: PYNAME, |
| 498 |
False: False, |
| 499 |
None: False, |
| 500 |
"": False, |
| 501 |
}.get(incoming) |
| 502 |
|
| 503 |
while incoming: |
| 504 |
# Send args as UTF-8 |
| 505 |
if module == "apply-profiles": |
| 506 |
# Always try to close currently running instance |
| 507 |
print("Closing existing instance") |
| 508 |
cmd = "exit" if incoming == PYNAME else "close" |
| 509 |
data = [cmd] |
| 510 |
lock.unlock() |
| 511 |
else: |
| 512 |
# Send module/appname to notify running app |
| 513 |
print("Notifying existing instance") |
| 514 |
data = [module or APPNAME] |
| 515 |
if module != "3DLUT-maker": |
| 516 |
for arg in sys.argv[1:]: |
| 517 |
data.append(str(arg)) |
| 518 |
data = sp.list2cmdline(data) |
| 519 |
if appsocket.send(data): |
| 520 |
print("Sent scripting request, awaiting response...") |
| 521 |
data_read = appsocket.read() |
| 522 |
incoming = data_read.rstrip("\4") |
| 523 |
print(f"Got response: {incoming!r}") |
| 524 |
if module == "apply-profiles": |
| 525 |
if incoming == "": |
| 526 |
# Successfully sent our close request. |
| 527 |
incoming = "ok" |
| 528 |
elif incoming == "invalid" and cmd == "exit": |
| 529 |
# < 3.8.8.1 didn't have exit command |
| 530 |
continue |
| 531 |
break |
| 532 |
appsocket.close() |
| 533 |
return incoming |
| 534 |
|
| 535 |
|
| 536 |
def terminate_conflicting_instance( |
| 537 |
module: str, |
| 538 |
lockfilename: str, |
| 539 |
lock: AppLock, |
| 540 |
pid: int, |
| 541 |
incoming: None | str, |
| 542 |
) -> None | str: |
| 543 |
"""Terminate conflicting instance by PID. |
| 544 |
|
| 545 |
Args: |
| 546 |
module (str): Module name. |
| 547 |
lockfilename (str): Lock file name. |
| 548 |
lock (AppLock): Lock file object. |
| 549 |
pid (int): PID of the process to terminate. |
| 550 |
incoming (None | str): Incoming status. |
| 551 |
|
| 552 |
Returns: |
| 553 |
None | str: Updated incoming status. |
| 554 |
""" |
| 555 |
if sys.platform != "win32": |
| 556 |
return incoming |
| 557 |
|
| 558 |
import pywintypes |
| 559 |
import win32ts |
| 560 |
|
| 561 |
opid = os.getpid() |
| 562 |
|
| 563 |
try: |
| 564 |
osid = win32ts.ProcessIdToSessionId(opid) |
| 565 |
except pywintypes.error as exception: |
| 566 |
print("Enumerating processes failed:", exception) |
| 567 |
osid = None |
| 568 |
|
| 569 |
try: |
| 570 |
processes = win32ts.WTSEnumerateProcesses() |
| 571 |
except pywintypes.error as exception: |
| 572 |
print("Enumerating processes failed:", exception) |
| 573 |
else: |
| 574 |
appname_lower = APPNAME.lower() |
| 575 |
exename_lower = EXENAME.lower() |
| 576 |
pyexe_lower = ( |
| 577 |
f"{appname_lower}-{module}{EXE_EXT}" |
| 578 |
if module |
| 579 |
else f"{appname_lower}{EXE_EXT}" |
| 580 |
) |
| 581 |
incoming = None |
| 582 |
for sid, pid2, basename, _usid in processes: |
| 583 |
basename_lower = basename.lower() |
| 584 |
# Optimized condition for process matching |
| 585 |
is_pid_match = pid and pid2 == pid and basename_lower == exename_lower |
| 586 |
is_session_exe_match = ( |
| 587 |
osid is None or sid == osid |
| 588 |
) and basename_lower == pyexe_lower |
| 589 |
if not (is_pid_match or is_session_exe_match) or pid2 == opid: |
| 590 |
continue |
| 591 |
# Other instance running |
| 592 |
incoming = False |
| 593 |
if module != "apply-profiles": |
| 594 |
continue |
| 595 |
if not os.path.isfile(lockfilename): |
| 596 |
create_dummy_lockfile(lockfilename) |
| 597 |
print( |
| 598 |
"Closing existing instance with PID", |
| 599 |
pid2, |
| 600 |
) |
| 601 |
startupinfo = sp.STARTUPINFO() |
| 602 |
startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW |
| 603 |
startupinfo.wShowWindow = sp.SW_HIDE |
| 604 |
lock.unlock() |
| 605 |
incoming = terminate_running_instance(incoming, pid2, startupinfo) |
| 606 |
|
| 607 |
return incoming |
| 608 |
|
| 609 |
|
| 610 |
def create_dummy_lockfile(lockfilename: str) -> None: |
| 611 |
"""Create a dummy lockfile. |
| 612 |
|
| 613 |
Args: |
| 614 |
lockfilename (str): Lock file name. |
| 615 |
""" |
| 616 |
# Create dummy lockfile |
| 617 |
try: |
| 618 |
with open(lockfilename, "w"): |
| 619 |
pass |
| 620 |
except OSError as exception: |
| 621 |
print( |
| 622 |
f"Warning - could not create dummy lockfile {lockfilename}: {exception!r}" |
| 623 |
) |
| 624 |
else: |
| 625 |
print( |
| 626 |
"Warning - had to create dummy lockfile", |
| 627 |
lockfilename, |
| 628 |
) |
| 629 |
|
| 630 |
|
| 631 |
def terminate_running_instance( |
| 632 |
incoming: None | str, |
| 633 |
pid2: int, |
| 634 |
startupinfo: sp.STARTUPINFO, |
| 635 |
) -> None | str: |
| 636 |
"""Terminate running instance by PID. |
| 637 |
|
| 638 |
Args: |
| 639 |
incoming (None | str): Incoming status. |
| 640 |
pid2 (int): PID of the process to terminate. |
| 641 |
startupinfo (subprocess.STARTUPINFO): Startup info for subprocess. |
| 642 |
|
| 643 |
Returns: |
| 644 |
None | str: Updated incoming status. |
| 645 |
""" |
| 646 |
try: |
| 647 |
p = sp.Popen( |
| 648 |
["taskkill", "/PID", f"{pid2}"], # noqa: S607 |
| 649 |
stdin=sp.PIPE, |
| 650 |
stdout=sp.PIPE, |
| 651 |
stderr=sp.STDOUT, |
| 652 |
startupinfo=startupinfo, |
| 653 |
) |
| 654 |
stdout, stderr = p.communicate() |
| 655 |
except Exception as exception: |
| 656 |
print(exception) |
| 657 |
else: |
| 658 |
print(stdout) |
| 659 |
if not p.returncode: |
| 660 |
# Successfully sent our close request. |
| 661 |
incoming = "ok" |
| 662 |
return incoming |
| 663 |
|
| 664 |
|
| 665 |
def initialize_app( |
| 666 |
module: str, app_lock_file_name: str, lock_to_pids_and_ports: dict |
| 667 |
) -> None: |
| 668 |
"""Initialize application. |
| 669 |
|
| 670 |
Args: |
| 671 |
module (str): Module name. |
| 672 |
app_lock_file_name (str): Lock file name. |
| 673 |
lock_to_pids_and_ports (dict): Mapping of lock files to PIDs and ports. |
| 674 |
""" |
| 675 |
opid = os.getpid() |
| 676 |
defaultport = getcfg("app.port") |
| 677 |
# Use exclusive lock during app startup |
| 678 |
with AppLock(app_lock_file_name, "a+", True, True) as lock: |
| 679 |
# Create listening socket |
| 680 |
if appsocket := AppSocket(): |
| 681 |
initialize_socket(lock_to_pids_and_ports, defaultport, appsocket) |
| 682 |
port = getattr(sys, "_appsocket_port", "") |
| 683 |
update_lock_file_content(module, opid, lock, port) |
| 684 |
atexit.register(lambda: print("Ran application exit handlers")) |
| 685 |
from DisplayCAL.wx_windows import BaseApp |
| 686 |
|
| 687 |
BaseApp.register_exitfunc(_exit, app_lock_file_name, port) |
| 688 |
check_for_required_resource_files(module) |
| 689 |
create_main_data_dir() |
| 690 |
|
| 691 |
|
| 692 |
def initialize_socket( |
| 693 |
lock_to_pids_and_ports: dict, |
| 694 |
defaultport: int, |
| 695 |
appsocket: AppSocket, |
| 696 |
) -> None: |
| 697 |
"""Initialize listening socket. |
| 698 |
|
| 699 |
Args: |
| 700 |
lock_to_pids_and_ports (dict): Mapping of lock files to PIDs and ports. |
| 701 |
defaultport (int): Default port to use. |
| 702 |
appsocket (AppSocket): Socket object. |
| 703 |
""" |
| 704 |
host = "127.0.0.1" |
| 705 |
if sys.platform != "win32": |
| 706 |
# https://docs.microsoft.com/de-de/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse#using-so_reuseaddr |
| 707 |
# From the above link: "The SO_REUSEADDR socket option allows |
| 708 |
# a socket to forcibly bind to a port in use by another socket". |
| 709 |
# Note that this is different from the behavior under Linux/BSD, |
| 710 |
# where a socket can only be (re-)bound if no active listening |
| 711 |
# socket is already bound to the address. |
| 712 |
# Consequently, we don't use SO_REUSEADDR under Windows. |
| 713 |
appsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 714 |
sys._appsocket = appsocket.socket |
| 715 |
if getcfg("app.allow_network_clients"): |
| 716 |
host = "" |
| 717 |
used_ports = [ |
| 718 |
pid_port[1] |
| 719 |
for pids_ports in list(lock_to_pids_and_ports.values()) |
| 720 |
for pid_port in pids_ports |
| 721 |
] |
| 722 |
candidate_ports = [0] |
| 723 |
if defaultport not in used_ports: |
| 724 |
candidate_ports.insert(0, defaultport) |
| 725 |
|
| 726 |
for port in candidate_ports: |
| 727 |
try: |
| 728 |
sys._appsocket.bind((host, port)) |
| 729 |
except OSError as exception: |
| 730 |
if port == 0: |
| 731 |
print( |
| 732 |
f"Warning - could not bind to {host}:{port}:", |
| 733 |
exception, |
| 734 |
) |
| 735 |
del sys._appsocket |
| 736 |
break |
| 737 |
else: |
| 738 |
try: |
| 739 |
sys._appsocket.settimeout(0.2) |
| 740 |
except OSError as exception: |
| 741 |
print("Warning - could not set socket timeout:", exception) |
| 742 |
del sys._appsocket |
| 743 |
break |
| 744 |
try: |
| 745 |
print("listening") |
| 746 |
sys._appsocket.listen(1) |
| 747 |
except OSError as exception: |
| 748 |
print("Warning - could not listen on socket:", exception) |
| 749 |
del sys._appsocket |
| 750 |
break |
| 751 |
try: |
| 752 |
port = sys._appsocket.getsockname()[1] |
| 753 |
except OSError as exception: |
| 754 |
print("Warning - could not get socket address:", exception) |
| 755 |
del sys._appsocket |
| 756 |
break |
| 757 |
sys._appsocket_port = port |
| 758 |
break |
| 759 |
|
| 760 |
|
| 761 |
def update_lock_file_content(module: str, opid: int, lock: AppLock, port: int) -> None: |
| 762 |
"""Update lock file content. |
| 763 |
|
| 764 |
Args: |
| 765 |
module (str): Module name. |
| 766 |
opid (int): Our PID. |
| 767 |
lock (AppLock): Lock file object. |
| 768 |
port (int): Our listening port. |
| 769 |
""" |
| 770 |
lock.seek(0) |
| 771 |
if module not in MULTI_INSTANCE_APP_NAMES: |
| 772 |
lock.truncate(0) |
| 773 |
if not port: |
| 774 |
print(f"writing to lock file: opid: {opid} port: {port}") |
| 775 |
lock.write(f"{opid}:{port}") |
| 776 |
else: |
| 777 |
print(f"writing to lock file: port: {port}") |
| 778 |
lock.write(port) |
| 779 |
lock.flush() |
| 780 |
|
| 781 |
|
| 782 |
def check_for_required_resource_files(module: str) -> None: |
| 783 |
"""Check for required resource files. |
| 784 |
|
| 785 |
Args: |
| 786 |
module (str): Module name. |
| 787 |
""" |
| 788 |
# Check for required resource files |
| 789 |
mod2res = { |
| 790 |
"3DLUT-maker": ["xrc/3dlut.xrc"], |
| 791 |
"curve-viewer": [], |
| 792 |
"profile-info": [], |
| 793 |
"scripting-client": [], |
| 794 |
"synthprofile": ["xrc/synthicc.xrc"], |
| 795 |
"testchart-editor": [], |
| 796 |
"VRML-to-X3D-converter": [], |
| 797 |
} |
| 798 |
for filename in mod2res.get(module, RES_FILES): |
| 799 |
path = get_data_path(os.path.sep.join(filename.split("/"))) |
| 800 |
if not path or not os.path.isfile(path): |
| 801 |
lang.init() |
| 802 |
raise ResourceError( |
| 803 |
lang.getstr("resources.notfound.error") + "\n" + filename |
| 804 |
) |
| 805 |
|
| 806 |
|
| 807 |
def create_main_data_dir() -> None: |
| 808 |
"""Create main data directory if it does not exist.""" |
| 809 |
# Create main data dir if it does not exist |
| 810 |
if not os.path.exists(DATA_HOME): |
| 811 |
try: |
| 812 |
os.makedirs(DATA_HOME) |
| 813 |
except Exception: |
| 814 |
handle_error( |
| 815 |
UserWarning(f"Warning - could not create directory '{DATA_HOME}'") |
| 816 |
) |
| 817 |
elif sys.platform == "darwin": |
| 818 |
# Check & fix permissions if necessary |
| 819 |
user = getpass.getuser() |
| 820 |
script = [ |
| 821 |
f"chown -R '{user}' '{directory}'" |
| 822 |
for directory in (CONFIG_HOME, DATA_HOME, LOGDIR) |
| 823 |
if os.path.isdir(directory) and not os.access(directory, os.W_OK) |
| 824 |
] |
| 825 |
if script: |
| 826 |
sp.call( |
| 827 |
[ # noqa: S607 |
| 828 |
"osascript", |
| 829 |
"-e", |
| 830 |
'do shell script "{}" with administrator privileges'.format( |
| 831 |
";".join(script).encode(FS_ENC), |
| 832 |
), |
| 833 |
] |
| 834 |
) |
| 835 |
|
| 836 |
|
| 837 |
def run_app(module: str) -> None: |
| 838 |
"""Run the application. |
| 839 |
|
| 840 |
Args: |
| 841 |
module (str): Module name. |
| 842 |
""" |
| 843 |
# Initialize & run |
| 844 |
if module == "3DLUT-maker": |
| 845 |
from DisplayCAL.wx_lut_3d_frame import main |
| 846 |
elif module == "curve-viewer": |
| 847 |
from DisplayCAL.wx_lut_viewer import main |
| 848 |
elif module == "profile-info": |
| 849 |
from DisplayCAL.wx_profile_info import main |
| 850 |
elif module == "scripting-client": |
| 851 |
from DisplayCAL.wx_scripting_client import main |
| 852 |
elif module == "synthprofile": |
| 853 |
from DisplayCAL.wx_synth_icc_frame import main |
| 854 |
elif module == "testchart-editor": |
| 855 |
from DisplayCAL.wx_testchart_editor import main |
| 856 |
elif module == "VRML-to-X3D-converter": |
| 857 |
from DisplayCAL.wx_vrml_2_x3d import main |
| 858 |
elif module == "apply-profiles": |
| 859 |
from DisplayCAL.profile_loader import main |
| 860 |
else: |
| 861 |
from DisplayCAL.display_cal import main |
| 862 |
|
| 863 |
# Run main after releasing lock |
| 864 |
main() |
| 865 |
|
| 866 |
|
| 867 |
def main(module: None | str = None) -> None: |
| 868 |
"""Main entry point. |
| 869 |
|
| 870 |
Args: |
| 871 |
module (None | str, optional): Module name. Default is None. |
| 872 |
""" |
| 873 |
mp.freeze_support() |
| 874 |
if mp.current_process().name != "MainProcess": |
| 875 |
return |
| 876 |
name = f"{APPBASENAME}-{module}" if module else APPBASENAME |
| 877 |
app_lock_file_name = os.path.join(CONFIG_HOME, f"{name}.lock") |
| 878 |
try: |
| 879 |
_main(module, name, app_lock_file_name) |
| 880 |
except Exception as exception: |
| 881 |
if isinstance(exception, ResourceError): |
| 882 |
error = exception |
| 883 |
else: |
| 884 |
error = Error(f"Fatal error: {exception}") |
| 885 |
handle_error(error) |
| 886 |
_exit(app_lock_file_name, getattr(sys, "_appsocket_port", "")) |
| 887 |
|
| 888 |
|
| 889 |
def _exit(lockfilename: str, oport: int) -> None: |
| 890 |
"""Application exit handler. |
| 891 |
|
| 892 |
Args: |
| 893 |
lockfilename (str): Lock file name. |
| 894 |
oport (int): Our listening port. |
| 895 |
""" |
| 896 |
for process in mp.active_children(): |
| 897 |
if "Manager" not in process.name: |
| 898 |
print("Terminating zombie process", process.name) |
| 899 |
process.terminate() |
| 900 |
print(process.name, "terminated") |
| 901 |
|
| 902 |
for thread in threading.enumerate(): |
| 903 |
if ( |
| 904 |
thread.is_alive() |
| 905 |
and thread is not threading.current_thread() |
| 906 |
and not thread.daemon |
| 907 |
): |
| 908 |
print(f"Waiting for thread {thread.name} to exit") |
| 909 |
thread.join() |
| 910 |
print(thread.name, "exited") |
| 911 |
|
| 912 |
if lockfilename and os.path.isfile(lockfilename): |
| 913 |
with AppLock(lockfilename, "r+", False, True) as lock: |
| 914 |
_update_lockfile(lockfilename, oport, lock) |
| 915 |
|
| 916 |
print("Exiting", PYNAME) |
| 917 |
|
| 918 |
|
| 919 |
def _update_lockfile(lockfilename: str, oport: int, lock: AppLock) -> None: |
| 920 |
"""Update lockfile by removing our own PID & port. |
| 921 |
|
| 922 |
Args: |
| 923 |
lockfilename (str): Lock file name. |
| 924 |
oport (int): Our listening port. |
| 925 |
lock (AppLock): Lock file object. |
| 926 |
""" |
| 927 |
if not lock: |
| 928 |
return |
| 929 |
# Each lockfile may contain multiple ports of running instances |
| 930 |
try: |
| 931 |
pids_ports = lock.read().splitlines() |
| 932 |
except OSError as exception: |
| 933 |
print(f"Warning - could not read lockfile {lockfilename}: {exception!r}") |
| 934 |
# filtered_pids_ports = [] |
| 935 |
return |
| 936 |
|
| 937 |
opid = os.getpid() |
| 938 |
|
| 939 |
remove_instances_if_not_running(pids_ports, opid, oport) |
| 940 |
check_filtered_pids_ports(lockfilename, lock, pids_ports) |
| 941 |
|
| 942 |
|
| 943 |
def remove_instances_if_not_running( |
| 944 |
pids_ports: list, |
| 945 |
opid: int, |
| 946 |
oport: int, |
| 947 |
) -> None: |
| 948 |
"""Remove our own PID & port from list of PIDs & ports if not running. |
| 949 |
|
| 950 |
Args: |
| 951 |
pids_ports (list): List of PIDs & ports. |
| 952 |
opid (int): Our PID. |
| 953 |
oport (int): Our listening port. |
| 954 |
""" |
| 955 |
# Determine if instances still running. If not still running, |
| 956 |
# remove from list of ports |
| 957 |
for i in reversed(range(len(pids_ports))): |
| 958 |
pid_port = pids_ports[i] |
| 959 |
if ":" in pid_port: |
| 960 |
# DisplayCAL >= 3.8.8.2 with localhost blocked |
| 961 |
pid, port = pid_port.split(":", 1) |
| 962 |
if pid: |
| 963 |
try: |
| 964 |
pid = int(pid) |
| 965 |
except ValueError: |
| 966 |
# This shouldn't happen |
| 967 |
pid = None |
| 968 |
else: |
| 969 |
# DisplayCAL <= 3.8.8.1 or localhost ok |
| 970 |
pid = None |
| 971 |
port = pid_port |
| 972 |
if port: |
| 973 |
try: |
| 974 |
port = int(port) |
| 975 |
except ValueError: |
| 976 |
# This shouldn't happen |
| 977 |
continue |
| 978 |
if (pid and pid == opid and not port) or (port and port == oport): |
| 979 |
# Remove ourself |
| 980 |
pids_ports[i] = "" |
| 981 |
continue |
| 982 |
if not port: |
| 983 |
continue |
| 984 |
appsocket = AppSocket() |
| 985 |
if not appsocket: |
| 986 |
break |
| 987 |
if not appsocket.connect("127.0.0.1", port): |
| 988 |
# Other instance probably died |
| 989 |
pids_ports[i] = "" |
| 990 |
appsocket.close() |
| 991 |
|
| 992 |
|
| 993 |
def check_filtered_pids_ports( |
| 994 |
lockfilename: str, |
| 995 |
lock: AppLock, |
| 996 |
pids_ports: list, |
| 997 |
) -> None: |
| 998 |
"""Check filtered PIDs & ports and update or remove lockfile. |
| 999 |
|
| 1000 |
Args: |
| 1001 |
lockfilename (str): Lock file name. |
| 1002 |
lock (AppLock): Lock file object. |
| 1003 |
pids_ports (list): List of PIDs & ports. |
| 1004 |
""" |
| 1005 |
# Filtered PIDs & ports (only used for checking) |
| 1006 |
filtered_pids_ports = [pid_port for pid_port in pids_ports if pid_port] |
| 1007 |
if filtered_pids_ports: |
| 1008 |
# Write updated lockfile |
| 1009 |
try: |
| 1010 |
lock.seek(0) |
| 1011 |
lock.truncate(0) |
| 1012 |
except OSError as exception: |
| 1013 |
print(f"Warning - could not update lockfile {lockfilename}: {exception!r}") |
| 1014 |
else: |
| 1015 |
lock.write("\n".join(pids_ports)) |
| 1016 |
else: |
| 1017 |
lock.close() |
| 1018 |
try: |
| 1019 |
os.remove(lockfilename) |
| 1020 |
except OSError as exception: |
| 1021 |
print(f"Warning - could not remove lockfile {lockfilename}: {exception!r}") |
| 1022 |
|
| 1023 |
|
| 1024 |
def main_3dlut_maker() -> None: |
| 1025 |
"""Launch the 3D LUT maker.""" |
| 1026 |
main("3DLUT-maker") |
| 1027 |
|
| 1028 |
|
| 1029 |
def main_curve_viewer() -> None: |
| 1030 |
"""Launch the 3D LUT viewer.""" |
| 1031 |
main("curve-viewer") |
| 1032 |
|
| 1033 |
|
| 1034 |
def main_eecolor_to_madvr_converter() -> None: |
| 1035 |
"""Launch the eeColor to madVR 3D LUT converter (CLI tool).""" |
| 1036 |
from DisplayCAL.eecolor_to_madvr import main as eecolor_to_madvr_main |
| 1037 |
|
| 1038 |
eecolor_to_madvr_main() |
| 1039 |
|
| 1040 |
|
| 1041 |
def main_profile_info() -> None: |
| 1042 |
"""Launch the profile info editor.""" |
| 1043 |
main("profile-info") |
| 1044 |
|
| 1045 |
|
| 1046 |
def main_scripting_client() -> None: |
| 1047 |
"""Launch the scripting client.""" |
| 1048 |
main("scripting-client") |
| 1049 |
|
| 1050 |
|
| 1051 |
def main_synthprofile() -> None: |
| 1052 |
"""Launch the synthetic profile creator.""" |
| 1053 |
main("synthprofile") |
| 1054 |
|
| 1055 |
|
| 1056 |
def main_testchart_editor() -> None: |
| 1057 |
"""Launch the testchart editor.""" |
| 1058 |
main("testchart-editor") |
| 1059 |
|
| 1060 |
|
| 1061 |
def main_vrml_to_x3d_converter() -> None: |
| 1062 |
"""Launch the VRML to X3D converter. |
| 1063 |
|
| 1064 |
Uses the GUI by default; falls back to console mode for --help/--no-gui. |
| 1065 |
""" |
| 1066 |
if "--help" in sys.argv[1:] or "--no-gui" in sys.argv[1:]: |
| 1067 |
from DisplayCAL.wx_vrml_2_x3d import main as vrml_to_x3d_main |
| 1068 |
|
| 1069 |
vrml_to_x3d_main() |
| 1070 |
else: |
| 1071 |
main("VRML-to-X3D-converter") |
| 1072 |
|
| 1073 |
|
| 1074 |
def main_vrml_to_x3d_converter_console() -> None: |
| 1075 |
"""Launch the VRML to X3D converter in console-only mode (no GUI).""" |
| 1076 |
from DisplayCAL.wx_vrml_2_x3d import main as vrml_to_x3d_main |
| 1077 |
|
| 1078 |
vrml_to_x3d_main() |
| 1079 |
|
| 1080 |
|
| 1081 |
class AppLock: |
| 1082 |
"""Lock file wrapper class. |
| 1083 |
|
| 1084 |
Args: |
| 1085 |
lockfilename (str): Lock file name. |
| 1086 |
mode (str): File open mode, e.g. 'r', 'a+', etc. |
| 1087 |
exclusive (bool, optional): Whether to acquire an exclusive lock. |
| 1088 |
Default is False. |
| 1089 |
blocking (bool, optional): Whether to wait until the lock is acquired. |
| 1090 |
Default is False. |
| 1091 |
""" |
| 1092 |
|
| 1093 |
def __init__( |
| 1094 |
self, |
| 1095 |
lockfilename: str, |
| 1096 |
mode: str, |
| 1097 |
exclusive: bool = False, |
| 1098 |
blocking: bool = False, |
| 1099 |
) -> None: |
| 1100 |
self._lockfilename = lockfilename |
| 1101 |
self._mode = mode |
| 1102 |
self._lockfile = None |
| 1103 |
self._lock = None |
| 1104 |
self._exclusive = exclusive |
| 1105 |
self._blocking = blocking |
| 1106 |
self.lock() |
| 1107 |
|
| 1108 |
def __enter__(self) -> Self: |
| 1109 |
"""Context manager enter method. |
| 1110 |
|
| 1111 |
Returns: |
| 1112 |
Self: The AppLock instance. |
| 1113 |
""" |
| 1114 |
return self |
| 1115 |
|
| 1116 |
def __exit__( |
| 1117 |
self, |
| 1118 |
etype: None | type[BaseException], |
| 1119 |
value: None | BaseException, |
| 1120 |
traceback: None | TracebackType, |
| 1121 |
) -> None: |
| 1122 |
"""Release lock and close lockfile. |
| 1123 |
|
| 1124 |
Args: |
| 1125 |
etype (None | type[BaseException]): Exception type. |
| 1126 |
value (None | BaseException): Exception instance. |
| 1127 |
traceback (None | TracebackType): Traceback object. |
| 1128 |
""" |
| 1129 |
self.unlock() |
| 1130 |
|
| 1131 |
def __getattr__(self, name: str) -> Any: # noqa: ANN401 |
| 1132 |
"""Return attribute of lockfile. |
| 1133 |
|
| 1134 |
Args: |
| 1135 |
name (str): Attribute name. |
| 1136 |
|
| 1137 |
Returns: |
| 1138 |
Any: Attribute of lockfile. |
| 1139 |
""" |
| 1140 |
return getattr(self._lockfile, name) |
| 1141 |
|
| 1142 |
def __iter__(self) -> None | Iterator: |
| 1143 |
"""Return iterator for lockfile. |
| 1144 |
|
| 1145 |
Returns: |
| 1146 |
None | Iterator: Iterator for lockfile, or None if lockfile |
| 1147 |
is not available. |
| 1148 |
""" |
| 1149 |
return self._lockfile |
| 1150 |
|
| 1151 |
def __bool__(self) -> bool: |
| 1152 |
"""Return True if lockfile was successfully created and locked.""" |
| 1153 |
return bool(self._lock) |
| 1154 |
|
| 1155 |
def lock(self) -> bool: |
| 1156 |
"""Create and lock lockfile. |
| 1157 |
|
| 1158 |
Returns: |
| 1159 |
bool: True on success, False on failure. |
| 1160 |
""" |
| 1161 |
lockdir = os.path.dirname(self._lockfilename) |
| 1162 |
try: |
| 1163 |
if not os.path.isdir(lockdir): |
| 1164 |
os.makedirs(lockdir) |
| 1165 |
# Create lockfile |
| 1166 |
self._lockfile = open(self._lockfilename, self._mode) # noqa: SIM115 |
| 1167 |
except OSError as exception: |
| 1168 |
# This shouldn't happen |
| 1169 |
print(f"Error - could not open lockfile {self._lockfilename}:", exception) |
| 1170 |
else: |
| 1171 |
try: |
| 1172 |
self._lock = FileLock(self._lockfile, self._exclusive, self._blocking) |
| 1173 |
except LockingError: |
| 1174 |
pass |
| 1175 |
except OSError as exception: |
| 1176 |
# This shouldn't happen |
| 1177 |
print( |
| 1178 |
f"Error - could not lock lockfile {self._lockfile.name}:", |
| 1179 |
exception, |
| 1180 |
) |
| 1181 |
else: |
| 1182 |
return True |
| 1183 |
return False |
| 1184 |
|
| 1185 |
def unlock(self) -> None: |
| 1186 |
"""Unlock and close lockfile.""" |
| 1187 |
if self._lockfile: |
| 1188 |
try: |
| 1189 |
self._lockfile.close() |
| 1190 |
except OSError as exception: |
| 1191 |
# This shouldn't happen |
| 1192 |
print( |
| 1193 |
f"Error - could not close lockfile {self._lockfile.name}:", |
| 1194 |
exception, |
| 1195 |
) |
| 1196 |
if self._lock: |
| 1197 |
try: |
| 1198 |
self._lock.unlock() |
| 1199 |
except UnlockingError as exception: |
| 1200 |
# This shouldn't happen |
| 1201 |
print( |
| 1202 |
f"Warning - could not unlock lockfile {self._lockfile.name}:", |
| 1203 |
exception, |
| 1204 |
) |
| 1205 |
|
| 1206 |
def write(self, contents: str) -> None: |
| 1207 |
"""Write contents to lockfile. |
| 1208 |
|
| 1209 |
Args: |
| 1210 |
contents (str): Contents to write. |
| 1211 |
""" |
| 1212 |
if self._lockfile: |
| 1213 |
try: |
| 1214 |
self._lockfile.write(f"{contents}\n") |
| 1215 |
except OSError as exception: |
| 1216 |
# This shouldn't happen |
| 1217 |
print( |
| 1218 |
f"Error - could not write to lockfile {self._lockfile.name}:", |
| 1219 |
exception, |
| 1220 |
) |
| 1221 |
|
| 1222 |
|
| 1223 |
class AppSocket: |
| 1224 |
"""Socket wrapper class.""" |
| 1225 |
|
| 1226 |
def __init__(self) -> None: |
| 1227 |
try: |
| 1228 |
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1229 |
except OSError as exception: |
| 1230 |
# This shouldn't happen |
| 1231 |
print("Warning - could not create TCP socket:", exception) |
| 1232 |
|
| 1233 |
def __getattr__(self, name: str) -> Any: # noqa: ANN401 |
| 1234 |
"""Return attribute of socket. |
| 1235 |
|
| 1236 |
Args: |
| 1237 |
name (str): Attribute name. |
| 1238 |
|
| 1239 |
Returns: |
| 1240 |
Any: Attribute of socket. |
| 1241 |
""" |
| 1242 |
return getattr(self.socket, name) |
| 1243 |
|
| 1244 |
def __bool__(self) -> bool: |
| 1245 |
"""Return True if socket was successfully created. |
| 1246 |
|
| 1247 |
Returns: |
| 1248 |
bool: True if socket was successfully created, False otherwise. |
| 1249 |
""" |
| 1250 |
return hasattr(self, "socket") |
| 1251 |
|
| 1252 |
def connect(self, host: str, port: int) -> bool: |
| 1253 |
"""Connect to host:port. |
| 1254 |
|
| 1255 |
Args: |
| 1256 |
host (str): Host to connect to. |
| 1257 |
port (int): Port to connect to. |
| 1258 |
|
| 1259 |
Returns: |
| 1260 |
bool: True on success, False on failure. |
| 1261 |
""" |
| 1262 |
try: |
| 1263 |
self.socket.connect((host, port)) |
| 1264 |
except OSError as exception: |
| 1265 |
# Other instance probably died |
| 1266 |
print(f"Connection to {host}:{port} failed:", exception) |
| 1267 |
return False |
| 1268 |
return True |
| 1269 |
|
| 1270 |
def read(self) -> str: |
| 1271 |
"""Read data until EOT character (ASCII 4) is found. |
| 1272 |
|
| 1273 |
Returns: |
| 1274 |
str: Incoming data. |
| 1275 |
""" |
| 1276 |
incoming = "" |
| 1277 |
while "\4" not in incoming: |
| 1278 |
try: |
| 1279 |
data = self.socket.recv(1024).decode("utf-8") |
| 1280 |
except OSError as exception: |
| 1281 |
if exception.errno == errno.EWOULDBLOCK: |
| 1282 |
sleep(0.05) |
| 1283 |
continue |
| 1284 |
print("Warning - could not receive data:", exception) |
| 1285 |
break |
| 1286 |
if not data: |
| 1287 |
break |
| 1288 |
incoming += data |
| 1289 |
return incoming |
| 1290 |
|
| 1291 |
def send(self, data: str) -> bool: |
| 1292 |
"""Send data. |
| 1293 |
|
| 1294 |
Args: |
| 1295 |
data (str): Data to send. |
| 1296 |
|
| 1297 |
Returns: |
| 1298 |
bool: True on success, False on failure. |
| 1299 |
""" |
| 1300 |
print("AppSocket.send start") |
| 1301 |
try: |
| 1302 |
# self.socket.send(("%s\n" % data).encode()) |
| 1303 |
data_to_send = f"{data}\n".encode() |
| 1304 |
print(f"data_to_send: {data_to_send}") |
| 1305 |
self.socket.sendall(data_to_send) |
| 1306 |
except OSError as exception: |
| 1307 |
# Connection lost? |
| 1308 |
print(f"Warning - could not send data {data!r}:", exception) |
| 1309 |
return False |
| 1310 |
return True |
| 1311 |
|
| 1312 |
|
| 1313 |
class Error(Exception): |
| 1314 |
"""Generic error class.""" |
| 1315 |
|
| 1316 |
|
| 1317 |
if __name__ == "__main__": |
| 1318 |
main() |