Source code for jcmsuite.editing.editor

# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH

"""Editor integration entrypoint for `jcmsuite`."""

from __future__ import annotations

import asyncio
import os
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 ..daemon.transport import (
    DaemonTransportConnection,
    close_daemon_connection,
    send_daemon_message,
    start_daemon_service,
)
from ..exceptions import (
    BackendUnavailableError,
    InvalidConfigurationError,
    RuntimeContextError,
)
from ..logging import get_logger

_logger: Logger = get_logger(__name__)
_EDIT_STATUS_BY_CONTEXT_ID: dict[int, bool] = {}
_EDIT_CONNECTION_BY_CONTEXT_ID: dict[int, DaemonTransportConnection] = {}


@overload
def edit(
    file_name: str | Path | None = None,
    *,
    line: int = 1,
    col: int = 1,
    set_status: Literal["on", "off"] | None = None,
    hint: str = "",
    context: SolverContext | None = None,
    asynchronous: Literal[False] = False,
) -> None: ...


@overload
def edit(
    file_name: str | Path | None = None,
    *,
    line: int = 1,
    col: int = 1,
    set_status: Literal["on", "off"] | None = None,
    hint: str = "",
    context: SolverContext | None = None,
    asynchronous: Literal[True],
) -> Coroutine[object, object, None]: ...


[docs] def edit( file_name: str | Path | None = None, *, line: int = 1, col: int = 1, set_status: Literal["on", "off"] | None = None, hint: str = "", context: SolverContext | None = None, asynchronous: bool = False, ) -> None | Coroutine[object, object, None]: """Open a project file or template in `JCMedit`. Parameters ---------- file_name : str | Path | None, optional File to open. If omitted, open `JCMedit` without a selected file. line : int, optional One-based line number to select. col : int, optional One-based column number to select. set_status : {"on", "off"} | None, optional Use `"on"` to enable automatic editor windows. Use `"off"` to disable them. hint : str, optional Text to send to the editor with the selected source position. 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 `JCMedit` starts or when automatic editor windows are disabled. If `asynchronous` is `True`, returns a coroutine that performs the operation. Raises ------ InvalidConfigurationError If `file_name` does not identify an existing file. RuntimeContextError If the `JCMedit` service cannot start. RuntimeError If asynchronous code calls the function without `asynchronous=True`. ValueError If `line`, `col`, or `set_status` is not valid. """ if asynchronous: return _edit_impl( file_name=file_name, line=line, col=col, set_status=set_status, hint=hint, context=context, ) try: asyncio.get_running_loop() except RuntimeError: return asyncio.run( _edit_impl( file_name=file_name, line=line, col=col, set_status=set_status, hint=hint, context=context, ) ) raise RuntimeError( "edit() called from a running event loop; use `await edit(..., asynchronous=True)`." )
async def _edit_impl( *, file_name: str | Path | None, line: int, col: int, set_status: Literal["on", "off"] | None, hint: str, context: SolverContext | None, ) -> None: """Internal edit implementation shared by sync and async wrappers. Notes ----- Edit integration behavior: - Start one socket service via ``JCMsolve --start_edit``. - Send popup/edit messages over that socket. This avoids direct ``JCMcontrol`` CLI argument handling, which can split whitespace-containing hints in shell wrappers. """ resolved_context: SolverContext = resolve_context(context) context_id: int = id(resolved_context) message: str = "__popup__" if file_name is not None: file_path: Path = Path(file_name).expanduser().resolve() if not file_path.is_file(): raise InvalidConfigurationError(f"Cannot access file {file_path}.") resolved_line: int = int(line) resolved_col: int = int(col) if resolved_line < 1: raise ValueError(f"Invalid parameter for line: {resolved_line}.") if resolved_col < 1: raise ValueError(f"Invalid parameter for col: {resolved_col}.") # The edit backend interprets column coordinates one step higher than # the user-facing value passed through this API. # Keep external API 1-based and apply the backend offset here. backend_col: int = resolved_col + 1 message = f"{file_path}!;!{resolved_line}!;!{backend_col}!;!{hint}" if set_status is not None: if set_status not in ("on", "off"): raise ValueError('set_status must be either "on" or "off".') _EDIT_STATUS_BY_CONTEXT_ID[context_id] = set_status == "on" if set_status == "off": message = "shutdown" is_enabled: bool = _EDIT_STATUS_BY_CONTEXT_ID.get(context_id, True) if not is_enabled and set_status != "on" and message != "shutdown": _logger.warning( 'JCMedit was switched off. Use edit(set_status="on") to switch it on again.' ) return try: _send_edit_message_with_restart(context=resolved_context, message=message) except BackendUnavailableError as error: _logger.warning("Could not start JCMedit. %s", error) return if message == "shutdown": _close_edit_connection(context_id) def _send_edit_message_with_restart(*, context: SolverContext, message: str) -> None: """Send one edit message and restart socket transport once on failure.""" context_id: int = id(context) connection: DaemonTransportConnection = _get_or_start_edit_connection(context) try: _ = send_daemon_message( connection=connection, message=message, get_answer=False, ) return except Exception: _logger.debug( "Edit socket send failed; restarting edit service once.", exc_info=True, ) _close_edit_connection(context_id) restarted_connection: DaemonTransportConnection = _get_or_start_edit_connection( context ) try: _ = send_daemon_message( connection=restarted_connection, message=message, get_answer=False, ) except Exception as exception: _close_edit_connection(context_id) raise RuntimeContextError("Could not start JCMedit service.") from exception def _get_or_start_edit_connection(context: SolverContext) -> DaemonTransportConnection: """Return context-bound edit socket connection, starting it if needed.""" context_id: int = id(context) existing_connection: DaemonTransportConnection | None = ( _EDIT_CONNECTION_BY_CONTEXT_ID.get(context_id) ) if existing_connection is not None: return existing_connection solve_binary: Path | None = context.jcm_solve if solve_binary is None or not solve_binary.is_file(): raise RuntimeContextError( "JCMsolve binary is not available; cannot start JCMedit service." ) try: calling_pid: int = os.getppid() except Exception: calling_pid = 0 new_connection: DaemonTransportConnection = start_daemon_service( jcm_solve_binary=solve_binary, calling_pid=calling_pid, start_command="--start_edit", ) _EDIT_CONNECTION_BY_CONTEXT_ID[context_id] = new_connection return new_connection def _close_edit_connection(context_id: int) -> None: """Close and remove a context-bound edit socket connection.""" connection: DaemonTransportConnection | None = _EDIT_CONNECTION_BY_CONTEXT_ID.pop( context_id, None ) close_daemon_connection(connection)