from __future__ import annotations
from typing import Literal
from ._client import DazClient
from ._result import ExecutionResult
from ._script_builder import ScriptBuilder
# Instance attribute set on the client while a group is open (read via
# vars() so a MagicMock client doesn't auto-create it).
_ACTIVE = "_dazpy_undo_group"
[docs]
class UndoGroup:
"""Context manager that groups DAZ Studio operations into a single undo step.
DAZ Studio 4 drops an undo group that is still open when a script ends,
so the group cannot be opened and closed in separate requests. Instead,
every :meth:`DazClient.execute` call made inside the block is queued
rather than sent. When the block ends, the queued scripts go to Studio as
one request, wrapped in ``UndoStack.beginHold()`` …
``UndoStack.accept(label)``. (Studio 6's global ``beginUndo()`` /
``acceptUndo()`` record nothing when run through the server, so
``UndoStack`` is called directly.)
What this means for code inside the block:
* ``execute()`` returns an :class:`~dazpy.ExecutionResult` whose
``value`` is ``None`` until the block ends. It is filled in after the
combined request returns, so read values *after* the block, or do reads
that later code depends on *before* entering it. Helpers that act on a
returned value straight away (for example, raising when a lookup comes
back empty) do not work inside a group.
* Only ``execute()`` is queued. Other client calls (``execute_file()``,
async submission, renders) run straight away, outside the group.
* If a queued script throws, ``UndoStack.cancel()`` runs, which reverts
the changes made by the earlier scripts in the group, and the error is
raised from the ``with`` statement.
* If the block raises, the queued scripts are discarded and never sent.
* A group opened inside another group joins the outer one and uses the
outer label.
Obtain via :meth:`DazScene.undo` rather than constructing directly::
arm = skel.find_bone("r_forearm") # look up before the block
with scene.undo("Rotate arm"):
arm.set_local_rotation(0, 0, 45)
Args:
client: The :class:`~dazpy.DazClient` to use.
label: The label shown in DAZ Studio's Edit > Undo menu.
"""
def __init__(self, client: DazClient, label: str):
self._client = client
self._label = label
self._queue: list[tuple[str, object, ExecutionResult]] = []
self._timeout: float | None = None
self._retry_on_busy = False
self._nested = False
def _defer(self, script: str, args: object = None, *, retry_on_busy: bool = False,
max_wait: float = 30.0, timeout: float | None = None) -> ExecutionResult:
placeholder = ExecutionResult(value=None)
self._queue.append((script, args, placeholder))
self._retry_on_busy = self._retry_on_busy or retry_on_busy
if timeout is not None:
self._timeout = timeout if self._timeout is None else max(self._timeout, timeout)
return placeholder
def _build_script(self) -> str:
lines = ["var __dazpy_undo = [];", "UndoStack.beginHold();", "try {"]
for script, args, _ in self._queue:
shim = ""
if args is not None:
shim = f"function getArguments(){{ return [{ScriptBuilder.to_js(args)}]; }} "
lines.append(
f"__dazpy_undo.push((function(){{ {shim}"
f"return eval({ScriptBuilder.escape_string(script)}); }})());")
lines += [
"} catch (e) { UndoStack.cancel(); throw e; }",
f"UndoStack.accept({ScriptBuilder.to_js(self._label)});",
"return __dazpy_undo;",
]
return ScriptBuilder.iife("\n".join(lines))
def __enter__(self) -> UndoGroup:
if vars(self._client).get(_ACTIVE) is not None:
self._nested = True # execute() already queues into the outer group
return self
vars(self._client)[_ACTIVE] = self
self._had_own_execute = "execute" in vars(self._client)
self._original_execute = self._client.execute
self._client.execute = self._defer # type: ignore[method-assign]
return self
def _restore_execute(self) -> None:
client = self._client
if not self._had_own_execute:
vars(client).pop("execute", None)
# Bound methods compare equal (not identical) per access; a mock's
# child mock lives outside vars() and must be put back explicitly.
if getattr(client, "execute", None) != self._original_execute:
client.execute = self._original_execute # type: ignore[method-assign]
def __exit__(self, exc_type, exc_val, exc_tb) -> Literal[False]:
if self._nested:
return False
self._restore_execute()
del vars(self._client)[_ACTIVE]
if exc_type is not None or not self._queue:
return False
result = self._client.execute(
self._build_script(), retry_on_busy=self._retry_on_busy, timeout=self._timeout)
values = result.value if isinstance(result.value, list) else []
for i, (_, _, placeholder) in enumerate(self._queue):
placeholder.value = values[i] if i < len(values) else None
placeholder.output = result.output
placeholder.request_id = result.request_id
placeholder.duration_ms = result.duration_ms
return False