Hive Events Examples¶
The page provides code examples for Hive events.
Each example is a real python file, docs/source/examplecode/hiveevents/, which is run by the
Hive unit tests so the examples stay working. Copy one into your own script or into a
script editor tab and call its start() function. Call stop() when you are done, a subscription
of a plain function lasts until you unsubscribe.
Listen To Everything¶
Subscribe with only a callback to hear every event of every rig.
"""Listen to every Hive event."""
from zoo.libs.hive import api
def describe(event):
"""Returns a one line description of any Hive event."""
eventName = api.EVENT_LABELS[event.eventType]
return "{}: rig={} component={}".format(eventName, event.rigName or "-", event.componentToken or "-")
def onEvent(event):
print(describe(event))
def start():
"""Subscribes for the events of every rig, the current ones and any created later."""
api.subscribe(onEvent)
def stop():
api.unsubscribe(onEvent)
Creating, renaming and deleting a rig prints:
RIG_CREATED: rig=Robot component=-
RIG_RENAMED: rig=Android component=-
RIG_DELETING: rig=Android component=-
RIG_DELETED: rig=Android component=-
Listen To One Event¶
Pass eventTypes to only be called for the events you need.
"""Only listen to the events you care about."""
from zoo.libs.hive import api
def onRigRenamed(event):
print("Rig renamed from {} to {}".format(event.oldValue, event.newValue))
def start():
api.subscribe(onRigRenamed, eventTypes=(api.HiveEventType.RIG_RENAMED,))
def stop():
api.unsubscribe(onRigRenamed)
Back Up A Rig Before It Is Deleted¶
RIG_DELETING is sent before anything is deleted, so the rig and its components can still be read. Once the
rig is deleted event.rig is None, only event.rigName is left.
"""Use the pre delete event to back up a rig before it is deleted."""
from zoo.libs.hive import api
backups = {}
def onRigDeleting(event):
# Nothing has been deleted yet, the rig and its components are fully valid.
rig = event.rig
tokens = [component.serializedTokenKey() for component in rig.iterComponents()]
print("Deleting rig {} with components {}".format(event.rigName, tokens))
backups[event.rigName] = rig.serializeFromScene()
def onRigDeleted(event):
# The rig is gone, only the name is left and event.rig is None.
print("Deleted rig {}, a backup is stored: {}".format(event.rigName, event.rigName in backups))
def start():
api.subscribe(onRigDeleting, eventTypes=(api.HiveEventType.RIG_DELETING,))
api.subscribe(onRigDeleted, eventTypes=(api.HiveEventType.RIG_DELETED,))
def stop():
api.unsubscribe(onRigDeleting)
api.unsubscribe(onRigDeleted)
Deleting a rig which has a spine component prints:
Deleting rig Robot with components ['spine:M']
Deleted rig Robot, a backup is stored: True
Track Deletes From Start To Finish¶
Every *_DELETING event ends with a *_DELETED or a *_DELETE_FAILED. This tracker knows what is being
deleted and which deletes failed.
The listener is a bound method, so Hive holds a weak reference, and the subscription ends when the tracker object is garbage collected.
"""Track deletes from start to finish, and see the ones which fail.
Every ``*_DELETING`` event is followed by exactly one ``*_DELETED`` or ``*_DELETE_FAILED`` event.
"""
from zoo.libs.hive import api
Type = api.HiveEventType
class DeleteTracker:
"""Keeps track of the rigs and components which are being deleted.
The listener is a bound method so Hive only holds a weak reference, the subscription ends when the tracker is
garbage collected. Call :meth:`stop` to end it sooner.
"""
def __init__(self):
self.pending = set()
self.failed = {}
api.subscribe(self._onEvent, eventTypes=(
Type.RIG_DELETING, Type.RIG_DELETED, Type.RIG_DELETE_FAILED,
Type.COMPONENT_DELETING, Type.COMPONENT_DELETED, Type.COMPONENT_DELETE_FAILED,
))
def stop(self):
api.unsubscribe(self._onEvent)
def _onEvent(self, event):
key = event.componentToken or event.rigName
if event.eventType in (Type.RIG_DELETING, Type.COMPONENT_DELETING):
self.pending.add(key)
return
self.pending.discard(key)
if event.eventType in (Type.RIG_DELETE_FAILED, Type.COMPONENT_DELETE_FAILED):
# The rig or component may be partly deleted, check exists() before using it.
self.failed[key] = event.error
Monitor Builds¶
BUILD_STATE_CHANGED is sent for each stage which finishes. BUILD_FAILED is sent for a stage which fails
or is cancelled, this includes builds started by the Hive Artist UI, a script or a build script.
"""Report builds and build failures, whoever started them."""
from zoo.libs.hive import api
def onBuildStateChanged(event):
stage = api.STAGE_LABELS.get(event.stage, event.stage)
print("Finished {} for rig {}".format(stage, event.rigName))
def onBuildFailed(event):
stage = api.STAGE_LABELS.get(event.stage, event.stage)
if event.cancelled:
print("The {} build of rig {} was cancelled".format(stage, event.rigName))
return
print("The {} build of rig {} failed on component {}: {}".format(
stage, event.rigName, event.componentToken, event.error))
# The build context has the log of the build up to the failure.
if event.buildContext is not None:
for entry in event.buildContext.log:
print(" {}".format(entry.message))
def start():
api.subscribe(onBuildStateChanged, eventTypes=(api.HiveEventType.BUILD_STATE_CHANGED,))
api.subscribe(onBuildFailed, eventTypes=(api.HiveEventType.BUILD_FAILED,))
def stop():
api.unsubscribe(onBuildStateChanged)
api.unsubscribe(onBuildFailed)
Building the guides prints Finished guide for rig Robot. A component which raises while building prints:
The guide build of rig Robot failed on component spine:M: Unknown build guide error
Failed to build buildGuide for component: <FkComponent>-spine:M
Watch The Configuration¶
CONFIGURATION_CHANGED is only sent for a real change. Setting the same value again sends nothing.
"""React to configuration changes."""
from zoo.libs.hive import api
def onConfigurationChanged(event):
if event.key is None:
# e.g. the saved rig configuration changed or the whole configuration was reloaded
print("The configuration of rig {} changed".format(event.rigName or "-"))
return
print("{} changed from {} to {} on rig {}".format(event.key, event.oldValue, event.newValue, event.rigName or "-"))
def start():
api.subscribe(onConfigurationChanged, eventTypes=(api.HiveEventType.CONFIGURATION_CHANGED,))
def stop():
api.unsubscribe(onConfigurationChanged)
Changing the guide scale of a rig prints guideScale changed from 1.0 to 3.0 on rig Robot.
Hold Back Events In A Script¶
The listeners of COMPONENT_ADDED hear about the components only once all of them exist.
The *_DELETING and failure events are never held back.
"""Hold back events while a script makes many changes."""
from zoo.libs.hive import api
def createComponents(rig, names):
"""Creates the components, listeners only hear about them once all of them exist."""
with api.Configuration.events().blocked():
return [rig.createComponent("fkchain", name, "M") for name in names]
Events In A Widget¶
A QObject which turns an event into a Qt signal. Pass names, not the live rig, through the signal.
"""Turn Hive events into Qt signals for a widget."""
from zoo.libs.hive import api
from zoovendor.Qt import QtCore
class RigNameWatcher(QtCore.QObject):
"""Emits :attr:`rigRenamed` whenever any rig is renamed."""
rigRenamed = QtCore.Signal(str, str)
def __init__(self, parent=None):
super().__init__(parent)
# a bound method, Hive holds it weakly so this doesn't keep the watcher alive
api.subscribe(self._onEvent, eventTypes=(api.HiveEventType.RIG_RENAMED,))
def dispose(self):
api.unsubscribe(self._onEvent)
def _onEvent(self, event):
self.rigRenamed.emit(str(event.oldValue), str(event.newValue))
Call dispose() when the widget closes. Because the subscription is a bound method it is also dropped
automatically when the watcher is garbage collected.
Test A Listener¶
An event is a plain object which you can build yourself. Keep the listener logic in a function of the event and test it without Maya or a rig.
"""Test a listener without Maya by building the event yourself."""
from zoo.libs.hive import api
def renameMessage(event):
"""The listener logic, kept in a function of the event so it can be tested on its own."""
if event.eventType != api.HiveEventType.RIG_RENAMED:
return ""
return "{} -> {}".format(event.oldValue, event.newValue)