# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""Viewer integration entrypoint for `jcmsuite`."""
from __future__ import annotations
import asyncio
import subprocess
from collections.abc import Coroutine
from logging import Logger
from pathlib import Path
from typing import Literal, overload
from ..context import SolverContext, resolve_context
from ..context.subprocess_tools import _spawn_detached_binary
from ..exceptions import InvalidConfigurationError, RuntimeContextError
from ..logging import get_logger
_logger: Logger = get_logger(__name__)
@overload
def view(
jcm_file: str | Path,
*,
context: SolverContext | None = None,
asynchronous: Literal[False] = False,
) -> None: ...
@overload
def view(
jcm_file: str | Path,
*,
context: SolverContext | None = None,
asynchronous: Literal[True],
) -> Coroutine[object, object, None]: ...
[docs]
def view(
jcm_file: str | Path,
*,
context: SolverContext | None = None,
asynchronous: bool = False,
) -> None | Coroutine[object, object, None]:
"""Open a JCMsuite grid or fieldbag file in `JCMview`.
Parameters
----------
jcm_file : str | Path
Path to an existing `.jcm` grid or fieldbag file.
context : SolverContext | None, optional
JCMsuite settings to use. If omitted, use the active context or the
default context.
asynchronous : bool, optional
If `True`, return a value that you must use with `await`.
Returns
-------
None | Coroutine[object, object, None]
`None` after `JCMview` starts. If `asynchronous` is `True`, returns a
coroutine that starts `JCMview`.
Raises
------
RuntimeContextError
If `JCMview` is not available.
InvalidConfigurationError
If `jcm_file` does not exist.
RuntimeError
If asynchronous code calls the function without `asynchronous=True`.
"""
if asynchronous:
return _view_impl(jcm_file=jcm_file, context=context)
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(_view_impl(jcm_file=jcm_file, context=context))
raise RuntimeError(
"view() called from a running event loop; use `await view(..., asynchronous=True)`."
)
async def _view_impl(
*,
jcm_file: str | Path,
context: SolverContext | None,
) -> None:
"""Internal view implementation shared by sync and async wrappers."""
resolved_context: SolverContext = resolve_context(context)
await resolved_context.startup()
view_binary_path: Path | None = resolved_context.jcm_view
if view_binary_path is None or not view_binary_path.is_file():
raise RuntimeContextError("JCMview binary is not available in the context.")
jcm_path: Path = Path(jcm_file).expanduser().resolve()
if not jcm_path.exists():
raise InvalidConfigurationError(
f"JCMview input file does not exist: {jcm_path}"
)
_logger.info("Viewing file %s", jcm_path)
_launch_viewer(view_binary_path, jcm_path)
def _launch_viewer(
view_binary_path: Path,
jcm_path: Path,
) -> None:
"""Spawn `JCMview` in detached mode and return immediately."""
_spawn_detached_binary(
view_binary_path,
[str(jcm_path)],
popen_factory=subprocess.Popen,
)