Files
Mujoco_WASM/python/mujoco/experimental/studio/handler_registry.py
T
Matija Kecman 0dfa4b509a Refactor Studio customization and message dispatch to use decorator-based handlers
This change replaces fixed callback protocols (e.g., ViewerGuiHook, ViewerUpdateHook, SimEventHandler) with a general-purpose, priority-based message and event handling mechanism.

Key changes:
- Handler decorator and registry: Introduced the `@messages.handler(priority=...)` decorator and `HandlerRegistry` (`handler_registry.py`). Methods marked as handlers are automatically discovered and dispatched by priority (CRITICAL, USER, LIBRARY, INTERNAL) or method resolution order.
- Local lifecycle events: Added `ViewerAppInitEvent`, `BuildGuiEvent`, and `UpdateEvent` to `messages.py`. Custom GUI rendering and per-frame update logic can now be implemented as standard event handlers without needing separate interface protocols.
- Streamlined launch and app APIs: Replaced individual hook and handler arguments in `launch_passive`, `ViewerApp`, and `ViewerHandle` with unified `viewer_handlers` and `sim_handlers` lists.
- Module restructuring: Extracted simulation-side message handling and `ViewerHandle` from `sim_app.py` into a dedicated `viewer_handle.py` module, removing `sim_app.py`.
- Sample updates: Migrated existing examples (such as `implot.py`) to use the new handler pattern and lifecycle events.

PiperOrigin-RevId: 941729322
Change-Id: I93e7c0edf0a13a8dc854f9e2083451f7c25a1825
2026-07-02 09:14:41 -07:00

63 lines
2.4 KiB
Python

# Copyright 2026 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Internal handler registration, metadata stamping, and runtime dispatching."""
import collections
from typing import Any, Callable
from mujoco.experimental.studio import messages
def _discover_handlers(
handler_obj: Any,
) -> list[tuple[messages._HandlerInfo, Callable[..., Any]]]:
"""Scan an object for methods marked with handler decorators."""
handlers = []
for name in dir(type(handler_obj)):
unbound = getattr(type(handler_obj), name, None)
if unbound is None:
continue
info = getattr(unbound, messages._HANDLER_INFO_ATTR, None) # pylint: disable=protected-access
if info is None:
continue
bound = getattr(handler_obj, name)
handlers.append((info, bound))
return handlers
class HandlerRegistry:
"""Runtime registry of discovered handlers from handler instances."""
def __init__(self, handlers: list[Any] | None = None) -> None:
self.handlers: dict[
type[messages.Message], list[tuple[int, Callable[..., Any]]]
] = collections.defaultdict(list)
for obj in handlers or []:
for info, bound_method in _discover_handlers(obj):
self.handlers[info.message_type].append((info.priority, bound_method))
def dispatch(self, message: Any) -> None:
"""Dispatches a message to registered handlers in priority order."""
# Collect all matching handlers for the given message class and all its
# ancestors/superclasses.
message_handlers = []
for message_type in type(message).__mro__:
message_handlers.extend(self.handlers.get(message_type, []))
# Sort by priority; higher values execute first.
message_handlers.sort(key=lambda item: item[0], reverse=True)
for _, handler in message_handlers:
if handler(message):
# Handler returned True to consume the message; stop dispatching.
return