Beispiel #1
0
    def remove_callback(self, event_name='', callback_tag=''):
        """
        Remove callback based on specified keyword argument.
        If both keyword specified, it will performed both action.

        :key event_name: Maya event name callback which want to removed.
        :type event_name: str
        :key callback_tag: Callback tag which want to removed.
        :type callback_tag: str
        """
        callback_collection = self._group_registered_callbacks()

        cb_id_array = om.MCallbackIdArray()
        cb_fn_name_list = []
        if event_name:
            cb_fn_name_list.extend(callback_collection['events'].get(
                event_name, []))
        if callback_tag:
            cb_fn_name_list.extend(callback_collection['tags'].get(
                callback_tag, []))

        for cb_fn_name in cb_fn_name_list:
            cb_id_array.append(
                self._registered_callback[cb_fn_name]['callback_id'])

        if cb_id_array:
            om.MMessage.removeCallbacks(cb_id_array)
Beispiel #2
0
    def __init__(self):
        super(KeyframeNamingWindow, self).__init__()

        self.callback_ids = om.MCallbackIdArray()
        self._reregister_callback_queued = False

        self.frames_in_list = []
        self._currently_refreshing = False
        self._currently_setting_selection = False
        self._listening_to_singleton = None
        self._listening_to_anim_curve = None

        self.time_change_listener = maya_helpers.TimeChangeListener(self._time_changed)

        from .qt_generated import keyframe_naming
        reload(keyframe_naming)

        self._ui = keyframe_naming.Ui_keyframe_naming()
        self._ui.setupUi(self)

        self._ui.removeFrame.clicked.connect(self.delete_selected_frame)
        self._ui.renameFrame.clicked.connect(self.rename_selected_frame)
        self._ui.addFrame.clicked.connect(self.add_new_frame)
        self._ui.frameList.itemDelegate().commitData.connect(self.frame_name_edited)
        self._ui.frameList.itemDelegate().closeEditor.connect(self.name_editor_closed)
        self._ui.frameList.itemSelectionChanged.connect(self.selected_frame_changed)
        self._ui.frameList.itemClicked.connect(self.selected_frame_changed)
        self._ui.frameList.setContextMenuPolicy(Qt.Qt.CustomContextMenu)

        def context_menu(pos):
            # Activate the context menu for the selected item.
            item = self._ui.frameList.itemAt(pos)
            if item is None:
                return

            keyframe_context_menu = self._create_keyframe_context_menu(item)
            action = keyframe_context_menu.exec_(self._ui.frameList.mapToGlobal(pos))
            
        self._ui.frameList.customContextMenuRequested.connect(context_menu)

        # Create the menu.  Why can't this be done in the designer?
        menu_bar = Qt.QMenuBar()
        self.layout().setMenuBar(menu_bar)

        edit_menu = menu_bar.addMenu('Edit')
        menu_select_naming_node = Qt.QAction('Select zKeyframeNaming node', self)
        menu_select_naming_node.setStatusTip('Select the zKeyframeNaming node, to edit keyframes in the graph editor')
        menu_select_naming_node.triggered.connect(select_naming_node)
        edit_menu.addAction(menu_select_naming_node)
        
        add_arnold_attribute = Qt.QAction('Add Arnold attribute', self)
        add_arnold_attribute.setStatusTip('Add a custom Arnold attribute to export the current frame name to rendered EXR files')
        add_arnold_attribute.triggered.connect(connect_to_arnold)
        edit_menu.addAction(add_arnold_attribute)

        self.installEventFilter(self)
        self._ui.frameList.installEventFilter(self)
Beispiel #3
0
    def __init__(self):

        self.logger = logging_util.SporeLogger(__name__)

        self.wdg_tree = collections.defaultdict(list)

        self.ui = manager_ui.ManagerWindow()
        self.io = message_utils.IOHandler()
        self.callbacks = om.MCallbackIdArray()

        self.initialize_ui()
        self.connect_signals()
Beispiel #4
0
    def add_callbacks(self):
        """ add scene callbacks to reset the global tracking dir when a new
        scene is opened """

        self.logger.debug('Add global scene callbacks...')
        callbacks = om.MCallbackIdArray()
        callbacks.append(
            om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeOpen,
                                         self.set_tracking_dir))
        callbacks.append(
            om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeNew,
                                         self.set_tracking_dir))
        return callbacks
Beispiel #5
0
    def postConstructor(self):
        """ called after node has been constructed. used to set things up """

        self._state = None
        self.geo_cache = geo_cache.GeoCache()

        obj_handle = om.MObjectHandle(self.thisMObject())
        sys._global_spore_tracking_dir[obj_handle.hashCode()] = self

        self.callbacks = om.MCallbackIdArray()
        self.callbacks.append(
            om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeSave,
                                         self.write_points))
        self.callbacks.append(
            om.MNodeMessage.addNodePreRemovalCallback(self.thisMObject(),
                                                      self.pre_destructor))
    def __init__(self):
        super(KeyingWindow, self).__init__()

        self.weight_node = None
        self.shown = False
        self.callback_ids = om.MCallbackIdArray()

        self._currently_refreshing = False

        self.time_change_listener = maya_helpers.TimeChangeListener(
            self._time_changed, pause_during_playback=False)

        from zMayaTools.qt_widgets import draggable_progress_bar
        reload(draggable_progress_bar)

        from zMayaTools.qt_generated import zMouthController
        reload(zMouthController)

        self.ui = zMouthController.Ui_zMouthController()
        self.ui.setupUi(self)

        self.ui.selectionBar.setMinimum(0)
        self.ui.selectionBar.setMaximum(1000)
        self.ui.mainWeightBar.setMinimum(0)
        self.ui.mainWeightBar.setMaximum(1000)

        self.ui.selectNodeButton.clicked.connect(self.select_current_node)
        self.ui.shapeSelection1.currentIndexChanged.connect(self.shape1Changed)
        self.ui.shapeSelection2.currentIndexChanged.connect(self.shape2Changed)
        self.ui.selectedNodeDropdown.currentIndexChanged.connect(
            self.selectedNodeChanged)
        self.ui.setKeyShape1.clicked.connect(self.clicked_key_shape_1)
        self.ui.setKeyShape2.clicked.connect(self.clicked_key_shape_2)
        self.ui.keySelection.clicked.connect(self.clicked_key_selection)
        self.ui.keyMainWeight.clicked.connect(self.clicked_key_main_weight)
        self.ui.soloShape1.clicked.connect(self.solo_shape1)
        self.ui.soloShape2.clicked.connect(self.solo_shape2)
        self.ui.selectionBar.mouse_movement.connect(
            self.set_selection_bar_value)
        self.ui.mainWeightBar.mouse_movement.connect(self.set_main_weight)

        self.ui.selectionBar.set_undo_chunk_around_dragging(
            'Dragging selection')
        self.ui.mainWeightBar.set_undo_chunk_around_dragging('Dragging weight')

        # This will call selectedNodeChanged, and trigger the rest of the refresh.
        self.refresh_weight_node_list()
Beispiel #7
0
    def __init__(self, node):
        super(AEsporeNodeTemplate, self).__init__(node)

        log_lvl = sys._global_spore_dispatcher.spore_globals['LOG_LEVEL']
        self.logger = logging_util.SporeLogger(__name__, log_lvl)

        self._node = node
        self.callbacks = om.MCallbackIdArray()
        self.jobs = []
        self.io = message_utils.IOHandler()
        self.navigator = None
        self.context = None

        self.beginScrollLayout()
        self.build_ui() # build bui
        pm.mel.AElocatorInclude(node) # add defaul controls
        self.addExtraControls('Extra Attributes') # add extra attributes
        self.endScrollLayout()

        self.add_script_job()
        self.add_callbacks()
Beispiel #8
0
#========================================
# author: changlong.zang
#   mail: [email protected]
#   date: Fri, 01 Jul 2016, 17:46:16
#========================================
import uuid, itertools
import maya.OpenMaya as OpenMaya
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
NODE_UUID_ATTR_NAME    = 'uuid'

DEFAULT_UUID           = '00000000000000000000000000000000'

MESSAGE_CALLBACK_ARRAY = OpenMaya.MCallbackIdArray()

#==================================================
# UUID Util ( Getting nodes and Informations )
#==================================================

def create_uuid():
    '''
    Create a string uuid hex code...
    '''
    uuid_code = uuid.uuid4()
    return uuid_code.get_hex()





def set_object_uuid(mobject, update=False, newID=None):
    '''
Beispiel #9
0
# 
# Author: Autodesk Developer Network

#For this exercise, search for the TODO keywords and follow the instructions in
#comments. If you are unsure of what you need to do, feel free to ask the instructor
#or look into the solution folder.
#Each #... line is a line of code you need to write or complete.

import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import sys

kPluginNodeTypeName = "sceneMsgCmd"


IDs = OpenMaya.MCallbackIdArray()


def removeCallback(ID):

	for i in range(ID.length()):
		try:
			#- TODO: You are responsible to remove all the callbacks you have registered in your plug-in code
			#...
		except:
			sys.stderr.write( "Failed to remove callback\n" )
			raise


def sceneMsgCmd():
	#- Clean up callback id array
Beispiel #10
0
def initMEL():
    if 'PYMEL_SKIP_MEL_INIT' in os.environ or pymel_options.get('skip_mel_init', False):
        _logger.info("Skipping MEL initialization")
        return

    _logger.debug("initMEL")
    mayaVersion = versions.installName()
    prefsDir = getUserPrefsDir()
    if prefsDir is None:
        _logger.error("could not initialize user preferences: MAYA_APP_DIR not set")
    elif not os.path.isdir(prefsDir):
        _logger.error("could not initialize user preferences: %s does not exist" % prefsDir)

    # TODO : use cmds.internalVar to get paths
    # got this startup sequence from autodesk support
    startup = [
        #'defaultRunTimeCommands.mel',  # sourced automatically
        # os.path.join( prefsDir, 'userRunTimeCommands.mel'), # sourced automatically
        'createPreferencesOptVars.mel',
        'createGlobalOptVars.mel',
        os.path.join(prefsDir, 'userPrefs.mel') if prefsDir else None,
        'initialStartup.mel',
        #$HOME/Documents/maya/projects/default/workspace.mel
        'initialPlugins.mel',
        #'initialGUI.mel', #GUI
        #'initialLayout.mel', #GUI
        # os.path.join( prefsDir, 'windowPrefs.mel'), #GUI
        # os.path.join( prefsDir, 'menuSetPrefs.mel'), #GUI
        #'hotkeySetup.mel', #GUI
        'namedCommandSetup.mel',
        os.path.join(prefsDir, 'userNamedCommands.mel') if prefsDir else None,
        #'initAfter.mel', #GUI
        os.path.join(prefsDir, 'pluginPrefs.mel') if prefsDir else None
    ]
    if pymel_options.get('skip_initial_plugins', False):
        # initialPlugins.mel is not sourced when running maya -batch, but has been included
        # in the pymel startup sequence since time immemorial. see pymel.conf for more info
        _logger.info("Skipping loading Initial Plugins")
        startup.remove('initialPlugins.mel')

    import maya.mel

    callbacks = om.MCallbackIdArray()
    toDelete = []

    # initialStartup.mel will run a `file -f -new`.  This is dangerous, for
    # obvoius resons, so we disable all file news while we run these...
    def rejectNewCallback(boolPtr_retCode, clientData):
        om.MScriptUtil.setBool(boolPtr_retCode, False)

    callbacks.append(om.MSceneMessage.addCheckCallback(
        om.MSceneMessage.kBeforeNewCheck, rejectNewCallback))

    try:
        # additionally, userPrefs.mel will apparently create a bunch of ikSolver
        # nodes (apparently just to set some global ik prefs?)
        # make sure we clean those up...
        def logIkSolverCreation(nodeObj, clientData):
            toDelete.append(om.MObjectHandle(nodeObj))

        callbacks.append(om.MDGMessage.addNodeAddedCallback(
            logIkSolverCreation, "ikSolver"))

        for f in startup:
            _logger.debug("running: %s" % f)
            if f is not None:
                if os.path.isabs(f) and not os.path.exists(f):
                    _logger.warning("Maya startup file %s does not exist" % f)
                else:
                    if PY2:
                        # need to encode backslashes (used for windows paths)
                        if isinstance(f, unicode):
                            encoding = 'unicode_escape'
                        else:
                            encoding = 'string_escape'
                        f = f.encode(encoding)
                    else:
                        # encoding to unicode_escape should add escape
                        # sequences, but also make sure everything is in basic
                        # ascii - so if we decode utf-8 (or ascii), it should
                        # give us a string which is escaped
                        f = f.encode('unicode_escape').decode('utf-8')
                    maya.mel.eval('source "%s"' % f)

    except Exception as e:
        _logger.error("could not perform Maya initialization sequence: failed "
                      "on %s: %s" % (f, e))
    finally:
        om.MMessage.removeCallbacks(callbacks)

        # clean up the created ik solvers
        dgMod = om.MDGModifier()
        for objHandle in toDelete:
            if objHandle.isValid():
                dgMod.deleteNode(objHandle.object())
        dgMod.doIt()

    try:
        # make sure it exists
        res = maya.mel.eval('whatIs "userSetup.mel"')
        if res != 'Unknown':
            maya.mel.eval('source "userSetup.mel"')
    except RuntimeError:
        pass

    _logger.debug("done running mel files")
    def __init__(self):
        super(ChannelBoxColt, self).__init__()
        self.setObjectName('ChannelBoxColt')
        self.setMinimumHeight(500)
        self.setStyleSheet('#ChannelBoxColt {background: transparent};')
        self.setSizePolicy(qg.QSizePolicy.Expanding, qg.QSizePolicy.Minimum)
        self.setLayout(qg.QStackedLayout())
        self.QFont = qg.QFont('Calibri', 12)
        self.QFont.setBold(True)

        mainWin = getMainWindow(windowObject)
        self.setParent(mainWin)

        self._currentNode = None
        self._isUpdating = False
        self._allNodes = []

        #############################
        # Blank Widget from stacked layout to clear the panel
        self.blankWidget = qg.QLabel()
        self.blankWidget.setObjectName('blankpage')
        self.blankWidget.setStyleSheet('#blankpage {background: transparent};')
        self.layout().addWidget(self.blankWidget)

        ###############################
        # Channel Box cristal pannel widget
        #
        self.channelBoxHolder = CustomGroup.CustomGroupColt()
        cb_layout = qg.QVBoxLayout(self.channelBoxHolder)
        self.layout().addWidget(self.channelBoxHolder)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setAlignment(qc.Qt.AlignTop)
        cb_lyt = self.channelBoxHolder.layout()
        cb_data_lyt = qg.QVBoxLayout()
        cb_lyt.addLayout(cb_data_lyt)
        cb_data_lyt.setContentsMargins(0, 1, 0, 0)
        cb_data_lyt.setAlignment(qc.Qt.AlignTop | qc.Qt.AlignVCenter
                                 | qc.Qt.AlignRight)

        ###################################
        # Table
        self.CB_table = CustomTableView(1, 2)
        self.CB_table.setStyleSheet(tableCSS)
        self.CB_table.setHorizontalScrollBarPolicy(qc.Qt.ScrollBarAlwaysOff)
        self.CB_table.setVerticalScrollBarPolicy(qc.Qt.ScrollBarAlwaysOff)
        self.CB_table.setFrameShape(qg.QFrame.NoFrame)
        self.CB_table.setFocusPolicy(qc.Qt.NoFocus)
        self.CB_table.verticalHeader().setVisible(False)
        self.CB_table.horizontalHeader().setVisible(False)
        cb_data_lyt.addWidget(self.CB_table)
        self.CB_table.setShowGrid(False)
        editTriggers = self.CB_table.DoubleClicked | self.CB_table.SelectedClicked | self.CB_table.AnyKeyPressed
        self.CB_table.setEditTriggers(editTriggers)

        #########################
        # using a custoom Item protoptype, this will always set my custom item to the table
        self.CB_table.setItemPrototype(CustomTableItem())

        #######################################################
        ####################################
        # Connections and callbacks from maya API
        #
        self.sel_idx = om.MEventMessage.addEventCallback(
            "SelectionChanged", self.refresDisplay)
        self.callbackkill = partial(om.MMessage.removeCallback, self.sel_idx)

        self.destroy_callback = self.destroyed.connect(self.callbackkill)

        ######################################
        # Signals from QWidgets Conection Area
        #
        self.CB_table.itemChanged.connect(self.itemChanged)
        self.selectedSignal.connect(self.connectionBridgeTest)
        self.updateAllSignal.connect(self.updateAllNodes)

        self.CB_table.installEventFilter(self)
        self.layout().currentChanged.connect(self.clearCallbackFromNode)
        ##########################################################
        # Clears any maya selection before launch the UI
        #
        self.layout().setCurrentIndex(0)
        cmds.select(clear=True)
        ##########################################################
        # CALLBACKS ID TO DELETE:
        #
        self.callBacks_ids = []
        self._node_callbackID = ''

        self.ids_array = om.MCallbackIdArray()
Beispiel #12
0
import maya.OpenMaya as OpenMaya

callback_array = OpenMaya.MCallbackIdArray()


def call_back(time_s, time_e, *args):
    '''
    '''
    print time_s, time_e


callback_array.append(OpenMaya.MTimerMessage.addTimerCallback(2, call_back))

OpenMaya.MMessage.removeCallbacks(callback_array)
Beispiel #13
0
"""
a module for managing mtoa's callbacks
"""
 
import maya.cmds as cmds
import pymel.core as pm
import maya.OpenMaya as om
from collections import defaultdict
import types

global _callbackIds
_callbackIds = om.MCallbackIdArray()

global _nodeAddedCallbacks
_nodeAddedCallbacks = defaultdict(list)

global _nodeRemovedCallbacks
_nodeRemovedCallbacks = defaultdict(list)

global _attrChangedCallbacks
_attrChangedCallbacks = {}

global _nameChangedCallbacks
_nameChangedCallbacks = defaultdict(list)

CONTEXTS = [om.MNodeMessage.kConnectionMade,
            om.MNodeMessage.kConnectionBroken,
            om.MNodeMessage.kAttributeEval,
            om.MNodeMessage.kAttributeSet,
            om.MNodeMessage.kAttributeLocked,
            om.MNodeMessage.kAttributeUnlocked,
Beispiel #14
0
    def __init__(self):
        super(KeyingWindow, self).__init__()

        # How do we make our window handle global hotkeys?
        undo = Qt.QAction('Undo', self)
        undo.setShortcut(Qt.Qt.CTRL + Qt.Qt.Key_Z)
        undo.triggered.connect(lambda: pm.undo())
        self.addAction(undo)

        redo = Qt.QAction('Redo', self)
        redo.setShortcut(Qt.Qt.CTRL + Qt.Qt.Key_Y)
        redo.triggered.connect(lambda: pm.redo(redo=True))
        self.addAction(redo)

        self.weight_node = None
        self.shown = False
        self.callback_ids = om.MCallbackIdArray()

        self._currently_refreshing = False

        style = r'''
        /* Maya's checkbox style makes the checkbox invisible when it's deselected,
         * which makes it impossible to tell that there's even a checkbox there to
         * click.  Adjust the background color to fix this. */
        QTreeView::indicator:unchecked {
            background-color: #000;
        }
        '''
        self.setStyleSheet(style)

        self.time_change_listener = maya_helpers.TimeChangeListener(self._time_changed, pause_during_playback=False)

        # Make sure zMouthController has been generated.
        qt_helpers.compile_all_layouts()

        from zMayaTools.qt_widgets import draggable_progress_bar
        reload(draggable_progress_bar)

        from zMayaTools.qt_generated import zMouthController
        reload(zMouthController)

        self.ui = zMouthController.Ui_zMouthController()
        self.ui.setupUi(self)

        self.ui.selectionBar.setMinimum(0)
        self.ui.selectionBar.setMaximum(1000)
        self.ui.mainWeightBar.setMinimum(0)
        self.ui.mainWeightBar.setMaximum(1000)

        self.ui.selectNodeButton.clicked.connect(self.select_current_node)
        self.ui.shapeSelection1.currentIndexChanged.connect(self.shape1Changed)
        self.ui.shapeSelection2.currentIndexChanged.connect(self.shape2Changed)
        self.ui.selectedNodeDropdown.currentIndexChanged.connect(self.selectedNodeChanged)
        self.ui.setKeyShape1.clicked.connect(self.clicked_key_shape_1)
        self.ui.setKeyShape2.clicked.connect(self.clicked_key_shape_2)
        self.ui.keySelection.clicked.connect(self.clicked_key_selection)
        self.ui.keyMainWeight.clicked.connect(self.clicked_key_main_weight)
        self.ui.soloShape1.clicked.connect(self.solo_shape1)
        self.ui.soloShape2.clicked.connect(self.solo_shape2)
        self.ui.selectionBar.mouse_movement.connect(self.set_selection_bar_value)
        self.ui.mainWeightBar.mouse_movement.connect(self.set_main_weight)

        self.ui.selectionBar.set_undo_chunk_around_dragging('Dragging selection')
        self.ui.mainWeightBar.set_undo_chunk_around_dragging('Dragging weight')

        # This will call selectedNodeChanged, and trigger the rest of the refresh.
        self.refresh_weight_node_list()