Skip to content

solidworks_mcp.adapters.solidworks.dialog_watch

solidworks_mcp.adapters.solidworks.dialog_watch

Answer a dialog a running macro left waiting for the user (issue #97).

RunMacro2 doesn't return while a macro waits on a dialog (a MsgBox, a user form, a SolidWorks prompt), and COM calls can't move off the connect thread to time it out. :class:DialogWatch runs beside the call on its own thread and uses only Win32 window calls, never COM. When a dialog the SolidWorks process opened stays up longer than the timeout, it reads the dialog and answers it with the non-committal choice:

  • Cancel, when the dialog has that button;
  • else its only button, when it has just one (an OK acknowledgement);
  • else, with no buttons (a VBA user form), it closes the window.

A dialog with several buttons and no Cancel (Yes/No) is left for the user and logged: pressing Yes or No could change the model.

Attributes

DIALOG_CLASSES module-attribute

DIALOG_CLASSES = frozenset({'#32770', 'ThunderDFrame'})

_WM_CLOSE module-attribute

_WM_CLOSE = 16

_WM_COMMAND module-attribute

_WM_COMMAND = 273

Classes

DialogSeen dataclass

DialogSeen(title: str, text: str, buttons: tuple[str, ...], answer: str | None)

A dialog the watch found waiting, and what it did.

Attributes:

Name Type Description
title str

The dialog's title.

text str

Its message, the static texts joined.

buttons tuple[str, ...]

Its button labels, without &.

answer str | None

"Cancel", the single button's label, "closed", or None when it was left for the user.

Methods:
describe
describe() -> str

One line: the dialog, its text, and how it was answered.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def describe(self) -> str:
    """One line: the dialog, its text, and how it was answered."""
    said = f": {self.text!r}" if self.text else ""
    if self.answer is None:
        how = "left open: it has no Cancel and more than one button"
    elif self.answer == "closed":
        how = "closed"
    else:
        how = f"answered {self.answer!r}"
    return f"{self.title!r}{said} ({how})"

DialogWatch dataclass

DialogWatch(pid: int, timeout: float, windows: Windows = Win32Windows(), poll: float = 0.5, clock: Callable[[], float] = time.monotonic, seen: list[DialogSeen] = list())

Watch process pid for a dialog left waiting, while a call runs.

Use it as a context manager around the blocking call. Dialogs already open when it starts are ignored.

Attributes:

Name Type Description
pid int

The SolidWorks process ID.

timeout float

Seconds a dialog may stay open before it is answered.

windows Windows

The window calls; the real Win32 ones by default.

poll float

Seconds between looks.

clock Callable[[], float]

The time source, in seconds.

seen list[DialogSeen]

Every dialog answered or left, in the order found.

Methods:
__enter__
__enter__() -> DialogWatch

Note the dialogs already open and start watching.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def __enter__(self) -> DialogWatch:
    """Note the dialogs already open and start watching."""
    self._before = set(self.windows.dialogs(self.pid))
    self._thread = threading.Thread(
        target=self._run, name="macro-dialog-watch", daemon=True
    )
    self._thread.start()
    return self
__exit__
__exit__(exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None

Stop watching.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def __exit__(
    self,
    exc_type: type[BaseException] | None,
    exc: BaseException | None,
    tb: TracebackType | None,
) -> None:
    """Stop watching."""
    self._stop.set()
    if self._thread is not None:
        self._thread.join(timeout=5)
__post_init__
__post_init__() -> None

Set up the thread state.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def __post_init__(self) -> None:
    """Set up the thread state."""
    self._stop = threading.Event()
    self._thread: threading.Thread | None = None
    self._before: set[int] = set()
    self._first: dict[int, float] = {}
    self._handled: set[int] = set()
check
check() -> None

Answer any new dialog that has been open longer than the timeout.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def check(self) -> None:
    """Answer any new dialog that has been open longer than the timeout."""
    now = self.clock()
    for hwnd in self.windows.dialogs(self.pid):
        if hwnd in self._before or hwnd in self._handled:
            continue
        opened = self._first.setdefault(hwnd, now)
        if now - opened >= self.timeout:
            self._handled.add(hwnd)
            self._answer(hwnd)

Win32Windows

Win32Windows(gui: Any = None, process: Any = None)

:class:Windows over win32gui and win32process.

Parameters:

Name Type Description Default
gui Any

The win32gui module; imported when None.

None
process Any

The win32process module; imported when None.

None

Keep the two modules.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def __init__(self, gui: Any = None, process: Any = None) -> None:
    """Keep the two modules."""
    if gui is None or process is None:
        import win32gui
        import win32process

        gui, process = gui or win32gui, process or win32process
    self._gui = gui
    self._process = process
Methods:
children
children(hwnd: int) -> list[tuple[int, str, str]]

A window's children as (hwnd, class name, text).

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def children(self, hwnd: int) -> list[tuple[int, str, str]]:
    """A window's children as ``(hwnd, class name, text)``."""
    kids: list[tuple[int, str, str]] = []

    def _visit(child: int, _extra: Any) -> bool:
        kids.append(
            (child, self._gui.GetClassName(child), self._gui.GetWindowText(child))
        )
        return True

    self._gui.EnumChildWindows(hwnd, _visit, None)
    return kids
control_id
control_id(hwnd: int) -> int

A child control's ID.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def control_id(self, hwnd: int) -> int:
    """A child control's ID."""
    return int(self._gui.GetDlgCtrlID(hwnd))
dialogs
dialogs(pid: int) -> list[int]

Visible top-level dialog windows of process pid.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def dialogs(self, pid: int) -> list[int]:
    """Visible top-level dialog windows of process ``pid``."""
    found: list[int] = []

    def _visit(hwnd: int, _extra: Any) -> bool:
        if (
            self._gui.IsWindowVisible(hwnd)
            and self._gui.GetClassName(hwnd) in DIALOG_CLASSES
            and self._process.GetWindowThreadProcessId(hwnd)[1] == pid
        ):
            found.append(hwnd)
        return True

    self._gui.EnumWindows(_visit, None)
    return found
post
post(hwnd: int, message: int, wparam: int, lparam: int) -> None

Post a message to a window without waiting for it.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def post(self, hwnd: int, message: int, wparam: int, lparam: int) -> None:
    """Post a message to a window without waiting for it."""
    self._gui.PostMessage(hwnd, message, wparam, lparam)
title
title(hwnd: int) -> str

A window's title.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def title(self, hwnd: int) -> str:
    """A window's title."""
    return str(self._gui.GetWindowText(hwnd))

Windows

Bases: Protocol

The Win32 window calls the watch makes.

Methods:
children
children(hwnd: int) -> list[tuple[int, str, str]]

A window's children as (hwnd, class name, text).

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def children(self, hwnd: int) -> list[tuple[int, str, str]]:
    """A window's children as ``(hwnd, class name, text)``."""
control_id
control_id(hwnd: int) -> int

A child control's ID.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def control_id(self, hwnd: int) -> int:
    """A child control's ID."""
dialogs
dialogs(pid: int) -> list[int]

Visible top-level dialog windows of process pid.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def dialogs(self, pid: int) -> list[int]:
    """Visible top-level dialog windows of process ``pid``."""
post
post(hwnd: int, message: int, wparam: int, lparam: int) -> None

Post a message to a window without waiting for it.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def post(self, hwnd: int, message: int, wparam: int, lparam: int) -> None:
    """Post a message to a window without waiting for it."""
title
title(hwnd: int) -> str

A window's title.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def title(self, hwnd: int) -> str:
    """A window's title."""

Functions:

waited_message

waited_message(seen: list[DialogSeen], timeout: float) -> str

The error for a macro that waited on dialogs.

Parameters:

Name Type Description Default
seen list[DialogSeen]

The dialogs the watch found.

required
timeout float

The timeout that was used, in seconds.

required

Returns:

Name Type Description
str str

What happened, and that macros here must not wait for the user.

Source code in src/solidworks_mcp/adapters/solidworks/dialog_watch.py
def waited_message(seen: list[DialogSeen], timeout: float) -> str:
    """The error for a macro that waited on dialogs.

    Args:
        seen: The dialogs the watch found.
        timeout: The timeout that was used, in seconds.

    Returns:
        str: What happened, and that macros here must not wait for the user.
    """
    dialogs = "; ".join(d.describe() for d in seen)
    return (
        f"The macro waited for the user: after {timeout:g} s a dialog was still "
        f"open, {dialogs}. It may have done part of its work before that. "
        "Macros run by execute_macro must not wait for the user: remove the "
        "MsgBox, form or prompt, or raise dialog_timeout."
    )