Пример #1
0
        def create(self, verbose=False):

            if not self.keys:
                return

            for i,k in enumerate(self.keys):

                name = self.name+'.'+self.functions[i]

                if verbose:
                    hotkeyPrint = '\t'
                    if self.altModifier[i]:
                        hotkeyPrint+='[Alt]+'
                    if self.ctrlModifier[i]:
                        hotkeyPrint+='[Ctrl]+'
                    hotkeyPrint = hotkeyPrint+'['+k+'] :\t'+name
                    print hotkeyPrint

                rtc = 'ml_hk_'+self.name+'_'+self.functions[i]

                nc = rtc+'_NC'

                if not mc.runTimeCommand(rtc, exists=True):
                    rtc = mc.runTimeCommand(rtc, default=True, annotation=name+' Hotkey generated by ml_toolbox', category='User', command=self.commands[i])

                nc = mc.nameCommand(nc, default=True, annotation=name+' nameCommand generated by ml_toolbox', command=rtc)

                mc.hotkey(keyShortcut=k, alt=self.altModifier[i], ctl=self.ctrlModifier[i], name=nc, releaseName='')
Пример #2
0
def gather(key, ctl=False, alt=False):
    '''
    returns dict {name, key, code, ann, cat, alt, ctl}
    '''
    if len(key) > 1:
        key = key.title()
    nCmd = getNameCommand(key, ctl, alt)
    if not nCmd:
        return {}
    rtCmd = getRunTimeCommand(nCmd)
    if not rtCmd:
        log.error('nameCommand found: "%s" but no runTimeCommand! "%s"' % (nCmd, rtCmd))
        return {}
    try:
        code = cmds.runTimeCommand(rtCmd, q=True, command=True)
        ann = cmds.runTimeCommand(rtCmd, q=True, annotation=True)
        cat = cmds.runTimeCommand(rtCmd, q=True, category=True)
        lang = cmds.runTimeCommand(rtCmd, q=True, commandLanguage=True)
    except:
        log.error('could not query runTimeCommand for "%s"' % rtCmd)
        return {}
    
    data = {'name': rtCmd, 'key': key, 'code': code, 'text': ann,
            'cat': cat, 'lang': lang, 'nameCommand': nCmd}
    if alt:
        data['alt'] = True
    if ctl:
        data['ctl'] = True
    return data
Пример #3
0
    def setupCommand(self, command, name, sourceType, annotation):
        """Makes the nameCommand and the runtimeCommand that is linked to by the hotkey"""

        cmds.runTimeCommand(self.name,
                            ann=self.annotation,
                            cat='User',
                            c=self.command,
                            cl=self.sourceType)
 def create_runtime_cmd(self, key):
     cmds.runTimeCommand(
         key.name,
         annotation=key.name,
         command=key.cmd,
         category=self.category,
         commandLanguage=self.script_type,
         # default=True,
     )
 def clean_hotkeys(self):
     """
     Removes existing hotkey runTimeCommands and empties hotkey map
     dictionary.
     """
     for m, hotkeys in self.hotkey_map.iteritems():
         for i in hotkeys:
             if cmd_exists(i.name):
                 cmds.runTimeCommand(i.name, e=True, delete=True)
     self.hotkey_map = {}
Пример #6
0
 def _createHotkey(self):
     if cmds.runTimeCommand('%s_press' % self.ui_txt_name.text(), exists=True):
         if cmds.confirmDialog(m='name is not unique! replace?', b=['yes', 'no']) == 'no':
             return
         else:
             cmds.runTimeCommand('%s_press' % self.ui_txt_name.text(), delete=True, e=True)
             cmds.runTimeCommand('%s_release' % self.ui_txt_name.text(), delete=True, e=True)
     name = self.ui_txt_name.text()
     menu = self.ui_txt_menu.text()
     command = self.ui_txt_command.text()
     hotkey = self.ui_txt_hotkey.text().lower()
     if not hotkey:
         return
     ctrl = self.ui_chb_ctrl.isChecked()
     alt = self.ui_chb_alt.isChecked()
     shift = self.ui_chb_shift.isChecked()
     if self.SELECT == 1:    # select based
         press = "MMtoKey.press_selected(menu='%s', ctl=%s, alt=%s, sh=%s)" % (menu, ctrl, alt, shift)
         release = "MMtoKey.release_selected('%s', %i)" % (command, self.ui_cmb_language.currentIndex())
     else:   # preset based
         press = "MMtoKey.press_preset(ctl=%s, alt=%s, sh=%s)" % (ctrl, alt, shift)
         release = "MMtoKey.release_preset()"
     cmds.runTimeCommand('%s_press' % name, c=press, category='MMtoKey', cl='python')
     cmds.runTimeCommand('%s_release' % name, c=release, category='MMtoKey', cl='python')
     cmds.nameCommand('%s_PressNameCommand' % name, annotation='%s_press' % name, command='%s_press' % name)
     cmds.nameCommand('%s_ReleaseNameCommand' % name, annotation='%s_release' % name, command='%s_release' % name)
     try:
         cmds.hotkey(k=hotkey, name='%s_PressNameCommand' % name, releaseName='%s_ReleaseNameCommand' % name,
                     ctl=ctrl, alt=alt, sht=shift)
     except TypeError:
         cmds.hotkey(k=hotkey, name='%s_PressNameCommand' % name, releaseName='%s_ReleaseNameCommand' % name,
                     ctl=ctrl, alt=alt)
     cmds.warning('hotkey created')
Пример #7
0
 def _createHotkey(self):
     if cmds.runTimeCommand('%s_press' % self.ui_txt_name.text(),
                            exists=True):
         if cmds.confirmDialog(m='name is not unique! replace?',
                               b=['yes', 'no']) == 'no':
             return
         else:
             cmds.runTimeCommand('%s_press' % self.ui_txt_name.text(),
                                 delete=True,
                                 e=True)
             cmds.runTimeCommand('%s_release' % self.ui_txt_name.text(),
                                 delete=True,
                                 e=True)
     name = self.ui_txt_name.text()
     menu = self.ui_txt_menu.text()
     command = self.ui_txt_command.text()
     hotkey = self.ui_txt_hotkey.text().lower()
     if not hotkey:
         return
     ctrl = self.ui_chb_ctrl.isChecked()
     alt = self.ui_chb_alt.isChecked()
     shift = self.ui_chb_shift.isChecked()
     if self.SELECT == 1:  # select based
         press = "MMtoKey.press_selected(menu='%s', ctl=%s, alt=%s, sh=%s)" % (
             menu, ctrl, alt, shift)
         release = "MMtoKey.release_selected('%s', %i)" % (
             command, self.ui_cmb_language.currentIndex())
     else:  # preset based
         press = "MMtoKey.press_preset(ctl=%s, alt=%s, sh=%s)" % (ctrl, alt,
                                                                  shift)
         release = "MMtoKey.release_preset()"
     cmds.runTimeCommand('%s_press' % name,
                         c=press,
                         category='MMtoKey',
                         cl='python')
     cmds.runTimeCommand('%s_release' % name,
                         c=release,
                         category='MMtoKey',
                         cl='python')
     cmds.nameCommand('%s_PressNameCommand' % name,
                      annotation='%s_press' % name,
                      command='%s_press' % name)
     cmds.nameCommand('%s_ReleaseNameCommand' % name,
                      annotation='%s_release' % name,
                      command='%s_release' % name)
     try:
         cmds.hotkey(k=hotkey,
                     name='%s_PressNameCommand' % name,
                     releaseName='%s_ReleaseNameCommand' % name,
                     ctl=ctrl,
                     alt=alt,
                     sht=shift)
     except TypeError:
         cmds.hotkey(k=hotkey,
                     name='%s_PressNameCommand' % name,
                     releaseName='%s_ReleaseNameCommand' % name,
                     ctl=ctrl,
                     alt=alt)
     cmds.warning('hotkey created')
Пример #8
0
def create_runtime_commands():
    """ Register macros so they can be bind to hotkeys.
    """
    for label, _, fn_name, command in _ENTRIES:
        # Remove old command if necessary
        if cmds.runTimeCommand(fn_name, exists=True):
            cmds.runTimeCommand(fn_name, edit=True, delete=True)

        cmds.runTimeCommand(fn_name,
                            annotation=label,
                            commandLanguage="python",
                            command=command)
def bt_checkCtrFHotkey():
    
    hotkeyExists = cmds.hotkey('f',query=1,ctl=1)
    
    if hotkeyExists == 1:
        print 'CTRL f hotkey already exists.  If you\'d like CTRL f to be associated with this tool simply delete the existing hotkey and rerun the tool to auto create.'
        
    else:
        print 'Automatically setting CTRL f as hotkey for this tool'
        cmds.nameCommand('bt_moveObjToCameraNameCommand',annotation='bt_moveObjToCameraNameCommand', command='bt_moveObjToCamera')
        runtimeCommandExists = cmds.runTimeCommand('bt_moveObjToCamera', exists=1)
        if runtimeCommandExists == 0:
            cmds.runTimeCommand('bt_moveObjToCamera', category='User', command='from bt_moveObjToCamera import *; bt_moveObjToCamera()')
        cmds.hotkey(keyShortcut='f',ctl=1,name='bt_moveObjToCameraNameCommand')
Пример #10
0
	def post_standalone_initialized(self):
		from mrv.maya.util import OptionVarDict
		import maya.cmds as cmds
		import maya.mel
		
		ovars = OptionVarDict()
		ovar = "TEST_OVAR"
		
		# check runtime comamnds
		assert 'MyTestRuntimeCommand' in (cmds.runTimeCommand(q=1, uca=1) or list())
		
		plugins = ("ge2Export", "decomposeMatrix")
		for plugname in plugins:
			assert cmds.pluginInfo(plugname, q=1, loaded=1)
		# check auto load plugins
		
		
		# check option vars
		assert ovar in ovars
		assert ovars[ovar] == 3 
		
		# check user setup
		tscript = """global int $gTestVar;
		if( $gTestVar != 5 ){
			error("AssertionError, global variable was not set");
		}"""
		maya.mel.eval(tscript)		# shouldn't raise
		assert hasattr(sys, 'userSetup') and sys.userSetup == True
Пример #11
0
def createRunTimeCommand(name, code, ann='', cat='User', lang='python'):
    """
    runTimeCommands are all the entries listed in the Hotkey Editor.
    They can be called directly but they can't be fired by a hotkey. For that
    you need another nameCommand that the hotkey points to...
    DAMN: although it seems to work like any other func runTimeCommand does NOT
    return the name of the created thing!!
    """
    
    edit = cmds.runTimeCommand(name, ex=True)
    # default commands can't be overwritten
    if edit and cmds.runTimeCommand(name, q=True, default=True):
        return name

    cmds.runTimeCommand(name, edit=edit, ann=ann, cat=cat, c=code, commandLanguage=lang)
    return name
Пример #12
0
def _register_hotkey():
    script_path = os.path.dirname(__file__) + "/scripts"

    command = """
# -------------------------
# MayaWindowSwitcher
# Author: @tm8r
# https://github.com/tm8r/MayaWindowSwitcher
# -------------------------

import os
import sys

from maya import cmds

def switch_window():
    script_path = "{0}"
    if not os.path.exists(script_path):
        cmds.error("WindowSwitcher install directory is not found. path={0}")
        return
    if script_path not in sys.path:
        sys.path.insert(0, script_path)

    import window_switcher.view
    window_switcher.view.WindowSwitcher.switch()

switch_window()""".format(script_path)

    command_name = "WindowSwitcher"
    if cmds.runTimeCommand(command_name, ex=True):
        cmds.runTimeCommand(command_name, e=True, delete=True)
    cmds.runTimeCommand(command_name,
                        ann="Open WindowSwitcher",
                        category="User",
                        command=command,
                        commandLanguage="python")
    named_command = command_name + "Command"
    named_command = cmds.nameCommand(
        named_command,
        annotation="Open WindowSwitcher",
        command=command_name,
    )
    if int(cmds.about(v=True)) <= 2015:
        cmds.hotkey(k="T", ctl=True, n=named_command)
        return

    cmds.hotkey(k="t", ctl=True, sht=True, n=named_command)
Пример #13
0
def set_hotkey(key,
               name=None,
               command='',
               release_name=None,
               release_command='',
               ctrl=False,
               alt=False):
    if cmds.runTimeCommand("{0}_runtime_cmd".format(name),
                           query=True,
                           exists=True):
        cmds.runTimeCommand("{0}_runtime_cmd".format(name),
                            edit=True,
                            delete=True)

    if cmds.runTimeCommand("{0}_runtime_cmd".format(release_name),
                           query=True,
                           exists=True):
        cmds.runTimeCommand("{0}_runtime_cmd".format(release_name),
                            edit=True,
                            delete=True)

    if name:
        press_runtime_cmd = cmds.runTimeCommand(
            "{0}_runtime_cmd".format(name),
            annotation="{0}_runtime_cmd".format(name),
            command=command,
            commandLanguage="python")

        name_cmd = cmds.nameCommand("{0}_name_cmd".format(name),
                                    annotation="{0}_name_cmd".format(name),
                                    command=press_runtime_cmd)

        cmds.hotkey(keyShortcut=key,
                    ctrlModifier=ctrl,
                    altModifier=alt,
                    name=name_cmd)

    if release_name:
        release_runtime_cmd = cmds.runTimeCommand(
            "{0}_runtime_cmd".format(release_name),
            annotation="{0}_runtime_cmd".format(release_name),
            command=release_command,
            commandLanguage="python")

        release_name_cmd = cmds.nameCommand(
            "{0}_name_cmd".format(release_name),
            annotation="{0}_name_cmd".format(release_name),
            command=release_runtime_cmd)

        cmds.hotkey(keyShortcut=key,
                    ctrlModifier=ctrl,
                    altModifier=alt,
                    releaseName=release_name_cmd)

    cmds.hotkey(autoSave=True)
Пример #14
0
def runtimeCommand():
    if not cmds.runTimeCommand('switchRTC', exists = True):
        cmds.runTimeCommand('switchRTC',
                            default = True,
                            category = 'User',
                            ann = "switches wieght unlocked influences",
                            c = 'switchInfluence()')
    
    cmds.nameCommand('switchNC',
                     ann = "Create a Sphere",
                     default = True,
                     command = 'switchRTC')
    if version >= 2016:
        clHotkeySet = "slHotKeySet"
        if not cmds.hotkeySet (clHotkeySet, exists = True):
            cmds.hotkeySet(clHotkeySet, source = 'Maya_Default', current = True)
        else:
            cmds.hotkeySet (clHotkeySet, e = True, current = True)
    cmds.hotkey(k = ';', n = 'switchNC')
Пример #15
0
    def harvestCommandsRt(self):
        catDb = self.db[cfg.SEARCH_CATEGORY_CMD_RT]

        for cmd in sorted(m.runTimeCommand(q=True, commandArray=True)):
            annotation = m.runTimeCommand(cmd, q=True, annotation=True).strip()
            if not annotation:
                annotation = cmd
            annotationL = annotation.lower()
            cmdL = cmd.lower()
            if '(press)' in annotationL \
                    or '(release)' in annotationL or \
                    cmdL.endswith('press') or \
                    cmdL.endswith('release'):
                continue

            cd = command_desc.CommandDescMel(cmd)
            cd.run = cmd
            cd.annotation = annotation
            catDb[cmdL] = cd
Пример #16
0
    def createRunTimeCommandForEntry(self, entry):
        name = entry.name
        cmdName = entry.cmdName
        cmdAnnotation = entry.cmdAnnotation

        try:
            if cmds.runTimeCommand(cmdName, q=True, exists=True):
                cmds.runTimeCommand(cmdName, e=True, delete=True)

            cmds.runTimeCommand(cmdName,
                                annotation=cmdAnnotation,
                                category="Custom Scripts",
                                commandLanguage="python",
                                hotkeyCtx="",
                                command="mmmmTools.commander.commands['" +
                                name + "']()")
        except:
            print("Error Creating Runtime Command")
            print(traceback.format_exc())
Пример #17
0
def create_runtime_command(name, callable_object, category="mGui", annotation="", args=(), kwargs=dict()):
    """
    creates a simple runTimeCommand which wraps the supplied function.  The function should be a no-argument callable
    which can be called using the pattern:

        from <module> import <fn>
        fn()

    For this reason, this is only appropriate for module-level functions.
    """

    assert callable(callable_object), "function argument must be callable"

    if cmds.runTimeCommand(name, exists=True):
        cmds.runTimeCommand(name, e=True, delete=True)

    cb_string = create_proxy_command(callable_object, *args, **kwargs)
    cmds.runTimeCommand(name, category=category, annotation=annotation, commandLanguage="python", command=cb_string)
    return name
Пример #18
0
    def _hotkey(self):
        """create hotkey"""
        name = self.ui.line_name.text()
        if cmds.runTimeCommand('%s_press' % name, exists=True):
            if cmds.confirmDialog(m='name is not unique! replace?', b=['yes', 'no']) == 'no':
                return
            else:
                cmds.runTimeCommand('%s_press' % name, delete=True, e=True)
                cmds.runTimeCommand('%s_release' % name, delete=True, e=True)
        hotkey = self.ui.line_hotkey.text().lower()
        if not hotkey:
            return

        # build menu
        ctrl = self.ui.chb_ctrl.isChecked()
        alt = self.ui.chb_alt.isChecked()
        shift = self.ui.chb_shift.isChecked()
        if self.COMMANDS[self.ui.cmb_method.currentIndex()][0] == "custom":
            press = "MMtoKey.pressCustom(ctl=%s, alt=%s, sh=%s, menu_type=%i, menu_name='%s')"
            press %= ctrl, alt, shift, self.ui.cmb_menu.currentIndex(), self.ui.line_menu.text()
        elif self.COMMANDS[self.ui.cmb_method.currentIndex()][0] == "selected":
            press = "MMtoKey.pressSelected(ctl=%s, alt=%s, sh=%s)" % (ctrl, alt, shift)
        else:
            press = "MMtoKey.pressPreset(ctl=%s, alt=%s, sh=%s)" % (ctrl, alt, shift)

        # release command
        if self.COMMANDS[self.ui.cmb_method.currentIndex()][1] == "custom":
            release = "MMtoKey.releaseCustom(command_always=%s, command='%s', language=%i)"
            release %= (self.ui.cmb_menu.currentIndex(), self.ui.line_command.text().replace("'", "\\'"),
                        self.ui.cmb_command.currentIndex())
        elif self.COMMANDS[self.ui.cmb_method.currentIndex()][1] == "selected":
            release = "MMtoKey.releaseSelected()"
        else:
            release = "MMtoKey.releasePreset()"

        # create runtime and name commands
        cmds.runTimeCommand('%s_press' % name, c=press, category='MMtoKey', cl='python')
        cmds.runTimeCommand('%s_release' % name, c=release, category='MMtoKey', cl='python')
        cmds.nameCommand('%s_PressNameCommand' % name, annotation='%s_press' % name, command='%s_press' % name)
        cmds.nameCommand('%s_ReleaseNameCommand' % name, annotation='%s_release' % name, command='%s_release' % name)
        try:
            cmds.hotkey(k=hotkey, name='%s_PressNameCommand' % name, releaseName='%s_ReleaseNameCommand' % name,
                        ctl=ctrl, alt=alt, sht=shift)
        except TypeError:
            cmds.hotkey(k=hotkey, name='%s_PressNameCommand' % name, releaseName='%s_ReleaseNameCommand' % name,
                        ctl=ctrl, alt=alt)
        cmds.warning('hotkey created')
Пример #19
0
 def createRunTimeCommandForEntry( self, entry ):
     name = entry.name
     cmdName = entry.cmdName
     cmdAnnotation = entry.cmdAnnotation
 
     try:
         if cmds.runTimeCommand( cmdName, q=True, exists=True ):
             cmds.runTimeCommand( cmdName, e=True, delete=True )
             
         cmds.runTimeCommand(
             cmdName,
             annotation=cmdAnnotation,
             category="Custom Scripts",
             commandLanguage="python",
             hotkeyCtx="",
             command="mmmmTools.commander.commands['" + name + "']()"
         )
     except:
         print( "Error Creating Runtime Command" )                            
         print( traceback.format_exc()  )        
Пример #20
0
        def create(self, verbose=False):

            if not self.keys:
                return

            for i, k in enumerate(self.keys):

                name = self.name + '.' + self.functions[i]

                if verbose:
                    hotkeyPrint = '\t'
                    if self.altModifier[i]:
                        hotkeyPrint += '[Alt]+'
                    if self.ctrlModifier[i]:
                        hotkeyPrint += '[Ctrl]+'
                    hotkeyPrint = hotkeyPrint + '[' + k + '] :\t' + name
                    print hotkeyPrint

                rtc = 'ml_hk_' + self.name + '_' + self.functions[i]

                nc = rtc + '_NC'

                if not mc.runTimeCommand(rtc, exists=True):
                    rtc = mc.runTimeCommand(rtc,
                                            default=True,
                                            annotation=name +
                                            ' Hotkey generated by ml_toolbox',
                                            category='User',
                                            command=self.commands[i])

                nc = mc.nameCommand(nc,
                                    default=True,
                                    annotation=name +
                                    ' nameCommand generated by ml_toolbox',
                                    command=rtc)

                mc.hotkey(keyShortcut=k,
                          alt=self.altModifier[i],
                          ctl=self.ctrlModifier[i],
                          name=nc,
                          releaseName='')
Пример #21
0
    def harvestCommandsRt(self):
        catDb = self.db[cfg.SEARCH_CATEGORY_CMD_RT]

        for cmd in sorted(m.runTimeCommand(q=True, commandArray=True)):
            annotation = m.runTimeCommand(cmd, q=True, annotation=True).strip()
            if not annotation:
                annotation = cmd
            annotationL = annotation.lower()
            cmdL = cmd.lower()
            if (
                "(press)" in annotationL
                or "(release)" in annotationL
                or cmdL.endswith("press")
                or cmdL.endswith("release")
            ):
                continue

            cd = command_desc.CommandDescMel(cmd)
            cd.run = cmd
            cd.annotation = annotation
            catDb[cmdL] = cd
Пример #22
0
def assignDefaultHotkey(cmd_name, cmd_string, cmd_annotation, cmd_hotkey):
    exists = cmds.runTimeCommand(cmd_name, exists=True)
    if exists:
        cmds.runTimeCommand(cmd_name, edit=True, delete=True)

    runtime = cmds.runTimeCommand(cmd_name,
                                  command=cmd_string,
                                  category='User',
                                  annotation=cmd_annotation)
    if not exists:
        command = cmds.nameCommand(command=runtime,
                                   sourceType='python',
                                   annotation=cmd_annotation)
        cmds.hotkey(altModifier=True,
                    keyShortcut=cmd_hotkey,
                    releaseName=command,
                    releaseCommandRepeat=True)

        cmds.evalDeferred(
            Callback(log, 'Assigned default hotkey (ALT+%s) for command: %s.',
                     cmd_hotkey, cmd_name))
    return
Пример #23
0
def reset(name, config, keyLabel, *args):
    """
    I wish I could actually delete a hotkey completely! But there is no way!
    I can not even hack the userHotkeys.mel and userNamedCommands.mel prefs file!
    Because they might be overwritten anytime.
    """
    prefsDict = prefs.getPrefs()
    if keyLabel not in prefsDict['hotkeyBackups']:
        log.error('keyLabel "%s" could not be found to restore')
        return
    backup = prefsDict['hotkeyBackups'][keyLabel]
    if not backup:
        cmds.hotkey(k=config['key'], name="", alt=config.get('alt', False), ctl=config.get('ctl', False))
        log.info('removed: (%s)' % keyLabel)
    else:
        setHotkey(backup['name'], backup)
        log.info('restored: (%s) %s ' % (keyLabel, backup['name']))
    
    if cmds.runTimeCommand(name, ex=True) and not cmds.runTimeCommand(name, q=True, default=True):
        cmds.runTimeCommand(name, e=True, delete=True)

    prefsDict['hotkeyBackups'].pop(keyLabel)
    prefs.setPrefs(prefsDict)
def bt_checkCtrFHotkey():

    hotkeyExists = cmds.hotkey('f', query=1, ctl=1)

    if hotkeyExists == 1:
        print 'CTRL f hotkey already exists.  If you\'d like CTRL f to be associated with this tool simply delete the existing hotkey and rerun the tool to auto create.'

    else:
        print 'Automatically setting CTRL f as hotkey for this tool'
        cmds.nameCommand('bt_moveObjToCameraNameCommand',
                         annotation='bt_moveObjToCameraNameCommand',
                         command='bt_moveObjToCamera')
        runtimeCommandExists = cmds.runTimeCommand('bt_moveObjToCamera',
                                                   exists=1)
        if runtimeCommandExists == 0:
            cmds.runTimeCommand(
                'bt_moveObjToCamera',
                category='User',
                command='from bt_moveObjToCamera import *; bt_moveObjToCamera()'
            )
        cmds.hotkey(keyShortcut='f',
                    ctl=1,
                    name='bt_moveObjToCameraNameCommand')
Пример #25
0
def cmdArgMakers(force=False):
    global _cmdArgMakers

    if _cmdArgMakers and not force:
        return _cmdArgMakers

    def makeCircle():
        return cmds.circle()[0]

    def makeEp():
        return makeCircle() + '.ep[1]'

    def makeSphere():
        return cmds.polySphere()[0]

    def makeCube():
        return cmds.polyCube()[0]

    def makeIk():
        j1 = cmds.joint()
        j2 = cmds.joint()
        return cmds.ikHandle(j1, j2, solver='ikRPsolver')[0]

    def makeJoint():
        return cmds.joint()

    def makeSkin():
        j1 = cmds.joint()
        j2 = cmds.joint()
        sphere = makeSphere()
        return cmds.skinCluster(j1, j2, sphere)[0]

    _cmdArgMakers = \
        {'tangentConstraint': (makeCircle, makeCube),
         'poleVectorConstraint': (makeSphere, makeIk),
         'pointCurveConstraint': (makeEp, ),
         'skinCluster': (makeJoint, makeJoint, makeSphere),
         }

    constraintCmds = [x for x in dir(cmds)
                      if x.endswith('onstraint')
                      and not cmds.runTimeCommand(x, q=1, exists=1)
                      and x != 'polySelectConstraint']

    for constrCmd in constraintCmds:
        if constrCmd not in _cmdArgMakers:
            _cmdArgMakers[constrCmd] = (makeSphere, makeCube)

    return _cmdArgMakers
Пример #26
0
        def create(self, verbose=False):

            if not self.keys:
                return

            for i, k in enumerate(self.keys):

                name = self.name + "." + self.functions[i]

                if verbose:
                    hotkeyPrint = "\t"
                    if self.altModifier[i]:
                        hotkeyPrint += "[Alt]+"
                    if self.ctrlModifier[i]:
                        hotkeyPrint += "[Ctrl]+"
                    hotkeyPrint = hotkeyPrint + "[" + k + "] :\t" + name
                    print hotkeyPrint

                rtc = "ml_hk_" + self.name + "_" + self.functions[i]

                nc = rtc + "_NC"

                if not mc.runTimeCommand(rtc, exists=True):
                    rtc = mc.runTimeCommand(
                        rtc,
                        default=True,
                        annotation=name + " Hotkey generated by ml_toolbox",
                        category="User",
                        command=self.commands[i],
                    )

                nc = mc.nameCommand(
                    nc, default=True, annotation=name + " nameCommand generated by ml_toolbox", command=rtc
                )

                mc.hotkey(keyShortcut=k, alt=self.altModifier[i], ctl=self.ctrlModifier[i], name=nc, releaseName="")
Пример #27
0
def createUpdateRunTimeCommand():
    runTimeCommandNamePathLangs = getNamePathLang(getRunTimeCommandDir())
    runTimeCommandNamePathLangs.sort()
    updatedMsg = "\nUpdated...\n\n"
    createdMsg = "\nCreated...\n\n"
    for runTimeCommandNamePathLang in runTimeCommandNamePathLangs:
        name, path, commandLanguage = runTimeCommandNamePathLang
        if cmds.runTimeCommand(name, q=True, exists=True):
            cmds.runTimeCommand(name, e=True, delete=True)
            cmds.runTimeCommand(name, category="Custom Scripts", commandLanguage=commandLanguage, command=getCommand(path))
            updatedMsg += "'{}' runtime command\n".format(name)
        else:
            cmds.runTimeCommand(name, category="Custom Scripts", commandLanguage=commandLanguage, command=getCommand(path))
            cmds.nameCommand(name+"NameCommand", annotation=name+"NameCommand", sourceType="mel", command=name)
            createdMsg += "'{}' runtime command.\n".format(name)

    cmds.confirmDialog(title="Run Time Command Results",message="{0}\n-----------------------\n{1}".format(updatedMsg, createdMsg))
Пример #28
0
    def setupCommand(self, command, name, sourceType, annotation):
        """Makes the nameCommand and the runtimeCommand that is linked to by the hotkey"""

        cmds.runTimeCommand(self.name, ann=self.annotation,
                            cat='User', c=self.command, cl=self.sourceType)
Пример #29
0
            pass
    except:
        welcomescreencallback = registerCallbacks()

    ### Registering HotKey ###
    name = "WelcomeScreen"
    annotation = "Welcome Screen Show"
    command = "from {0} import main as WelcomeScreen; WelcomeScreen.start()".format(
        moduleName)

    try:
        if welcomescreeninitialized:
            print("Already Registered")
            pass
    except:
        if cmds.runTimeCommand(name, q=True, exists=True):
            cmds.runTimeCommand(name, e=True, delete=True)
        if not cmds.runTimeCommand(name, q=True, exists=True):
            cmds.runTimeCommand(name,
                                annotation=annotation,
                                command=command,
                                commandLanguage="python",
                                category="Custom Scripts")

            cmds.nameCommand("{0}NameCommand".format(name),
                             annotation=annotation,
                             command=name)

        if cmds.hotkeySet(q=True, current=True) == "Maya_Default":
            if not cmds.hotkeySet("Custom", q=True, exists=True):
                cmds.hotkeySet("Custom", current=True)
Пример #30
0
    def _hotkey(self):
        """create hotkey"""
        name = self.ui.line_name.text()
        if cmds.runTimeCommand('%s_press' % name, exists=True):
            if cmds.confirmDialog(m='name is not unique! replace?',
                                  b=['yes', 'no']) == 'no':
                return
            else:
                cmds.runTimeCommand('%s_press' % name, delete=True, e=True)
                cmds.runTimeCommand('%s_release' % name, delete=True, e=True)
        hotkey = self.ui.line_hotkey.text().lower()
        if not hotkey:
            return

        # build menu
        ctrl = self.ui.chb_ctrl.isChecked()
        alt = self.ui.chb_alt.isChecked()
        shift = self.ui.chb_alt.isChecked()
        if self.COMMANDS[self.ui.cmb_method.currentIndex()][0] == "custom":
            press = "MMtoKey.pressCustom(ctl=%s, alt=%s, sh=%s, menu_type=%i, menu_name='%s')"
            press %= ctrl, alt, shift, self.ui.cmb_menu.currentIndex(
            ), self.ui.line_menu.text()
        elif self.COMMANDS[self.ui.cmb_method.currentIndex()][0] == "selected":
            press = "MMtoKey.pressSelected(ctl=%s, alt=%s, sh=%s)" % (
                ctrl, alt, shift)
        else:
            press = "MMtoKey.pressPreset(ctl=%s, alt=%s, sh=%s)" % (ctrl, alt,
                                                                    shift)

        # release command
        if self.COMMANDS[self.ui.cmb_method.currentIndex()][1] == "custom":
            release = "MMtoKey.releaseCustom(command_always=%s, command='%s', language=%i)"
            release %= (self.ui.cmb_menu.currentIndex(),
                        self.ui.line_command.text().replace("'", "\\'"),
                        self.ui.cmb_command.currentIndex())
        elif self.COMMANDS[self.ui.cmb_method.currentIndex()][1] == "selected":
            release = "MMtoKey.releaseSelected()"
        else:
            release = "MMtoKey.releasePreset()"

        # create runtime and name commands
        cmds.runTimeCommand('%s_press' % name,
                            c=press,
                            category='MMtoKey',
                            cl='python')
        cmds.runTimeCommand('%s_release' % name,
                            c=release,
                            category='MMtoKey',
                            cl='python')
        cmds.nameCommand('%s_PressNameCommand' % name,
                         annotation='%s_press' % name,
                         command='%s_press' % name)
        cmds.nameCommand('%s_ReleaseNameCommand' % name,
                         annotation='%s_release' % name,
                         command='%s_release' % name)
        try:
            cmds.hotkey(k=hotkey,
                        name='%s_PressNameCommand' % name,
                        releaseName='%s_ReleaseNameCommand' % name,
                        ctl=ctrl,
                        alt=alt,
                        sht=shift)
        except TypeError:
            cmds.hotkey(k=hotkey,
                        name='%s_PressNameCommand' % name,
                        releaseName='%s_ReleaseNameCommand' % name,
                        ctl=ctrl,
                        alt=alt)
        cmds.warning('hotkey created')
def cmd_exists(name):
    return cmds.runTimeCommand(name, q=True, exists=True)
Пример #32
0
    def createHotkeyAndRequiredFromEntry(self, entry ):
        hotkeySetAtFunctionStart = pm.hotkeySet( current=True, query=True )

        i = entry                  
        pm.hotkeySet( i['set'], current=True, edit=True )


        ## Determine which modifiers are being used. (Because Maya is already naturally
        ## sensitive to shift, by using capitals or symbols, we don't test for shift.
        try:
            try:
                isCtl=i['ctl']
            except:
                isCtl=False
            try:
                isAlt=i['alt']
            except:
                isAlt=False
        except:
            pass
        ## Based on the above logic, generate strings to be used while creating the hotkeys.    
        if isAlt == True:
            AltString = " Alt + "
        else:
            AltString = " "        
        if isCtl == True:
            CtlString = " Ctrl + "
        else:
            CtlString = " "

        if not i.get('doRelease',False):
            ## Create a printout of the command being made and the hotkey that will use it.
            print(  "About to add runTimeCommand and nameCommand named "\
                + i['name'] + "         Pushing: " + CtlString + AltString + i['key']  )
            try:
                if cmds.runTimeCommand( i['name'], q=True, exists=True ):
                    cmds.runTimeCommand( i['name'], e=True, delete=True )
                    
                cmds.runTimeCommand(
                    i['name'],
                    annotation=i['annotation'],
                    category="Custom Scripts",
                    commandLanguage="mel",
                    hotkeyCtx="",
                    command=i['mel']
                )
            except:
                print( "Error Creating Runtime Command" )                            
                print( traceback.format_exc()  )
                
            try:
                cmds.nameCommand(
                    i['name']+"NameCommand",
                    annotation=i['annotation'],
                    sourceType='mel',
                    command=i['name']
                )
            except:
                print( "Error Creating Named Command" )
            ## Add the actual hotkey to Maya.
            try:                    
                cmds.hotkey( k=i['key'], name=i['name']+"NameCommand", ctl=isCtl, alt=isAlt)
            except:
                print( "Error Binding Hotkey" )
                print( traceback.format_exc()  )


        
        if i.get('doRelease',False):
            ## Create a printout of the command being made and the hotkey that will use it.
            print(  "About to add nameCommandRelease named " + i['name'] + "         Releasing: " + CtlString + AltString + i['key']  )
            
        try:
            if cmds.runTimeCommand( i['name']+"Release", q=True, exists=True ):
                cmds.runTimeCommand( i['name']+"Release", e=True, delete=True )
                
            cmds.runTimeCommand(
                i['name']+"Release",
                annotation=i['annotation'],
                category="Custom Scripts",
                commandLanguage="mel",
                hotkeyCtx="",
                command=i['mel']
            )
        except:
            print( "Error Creating Runtime Command" )                            
            print( traceback.format_exc()  )            
            
            try:
                cmds.nameCommand( i['name']+"Release", annotation=i['annotation']+"Release", command=i['mel']+"Release" )
            except:
                print( "Error Creating Named Command" )

            ## Add the actual hotkey to Maya.                
            try:
                ##Its very important that Release is added to name string below.
                cmds.hotkey( k=i['key'], ctl=isCtl, alt=isAlt ,releaseName=i['name']+"Release" )
            except:
                print( "Error Binding Hotkey" )                    

        pm.hotkeySet( hotkeySetAtFunctionStart, current=True, edit=True )
Пример #33
0
def main():
    print '# Custom Hotkey Set Creation Tool'
    # HotKey Set Creation. Omitting now. Currently
    '''
	### Delete Current Custom Hotkey Sets.
	sSet = 'CustomHotkeySet'
	sSetBU = '%sBU'%sSet# This one is the BU set to be duplicated from.
	aSet = [str(s) for s in cmds.hotkeySet(q = True, hotkeySetArray = True)]

	# Delete previously created Custom Hotkey Sets.
	if sSet in aSet:
		cmds.hotkeySet(sSet, edit = True, delete = True)
		print '%s found. Deleted.'% sSet
	if sSetBU in aSet:
		cmds.hotkeySet(sSetBU, edit = True, delete = True)
		print '%s found. Deleted.'% sSetBU

	# Create a fresh custom Set. (Create BU first for Toggle tool. WIll create sSet at the end of the run.)

	cmds.hotkeySet(sSetBU, current = True)
	print '%s Created.'% sSetBU
	'''

    ### Create Scripts in the Editor. ##

    # Get List of Hotkeys from HotKeys.py
    sScriptName = 'HotKeys'  # remove '.py'
    sScriptPath = '/vol/transfer/dyabu/Scripts/mayaScripts'
    oHotKeys = imp.load_source(sScriptName,
                               '%s/%s.py' % (sScriptPath, sScriptName))

    # Getting List of keys from HotKeys.py (List of all Custom Hotkeys.)
    aKeyList = oHotKeys.KeyList().keys()

    #print aKeyList
    #aKeyList = ['9_N_P','N_ALT_R',] # temp. for testing
    aKeyList = ['L_ALT_P', 'L_ALT_R']  # temp. for testing
    for k in aKeyList:

        if not cmds.runTimeCommand(k, ex=True):

            #mel.eval('runTimeCommand -delete %s '%k) # Not working....
            #cmds.runTimeCommand(k, delete = True)

            aKey = k.split('_')

            # Custom Shortcut command.
            sCommand = '''# Custom Hotkey - Consolidated - v0.0.2

# CUSTOMIZE HERE:
p = '%s/' # Path to HotKeys.py
sChar = '%s' # Key on Keyboard. not case sensitive.
sPress = '%s' # 'P' or 'R' Pressed or Release

# -- Start --
import maya.cmds as cmds
import sys
if p not in sys.path: sys.path.append(p)
import Hotkeys # Hotkeys.py

reload(HotKeys) #Use reload when testing. Comment out when in actual use.

iModifier = cmds.getModifiers()
HotKeys.Execute(sChar, iModifier, sPress)
''' % (sScriptPath, aKey[0], aKey[2])
            aMod = [False, False, False, False]
            if 'SFT' in aKey:
                aMod[0] = True
            if 'CTL' in aKey:
                aMod[1] = True
            if 'ALT' in aKey:
                aMod[2] = True
            if 'CMD' in aKey:
                aMod[3] = True

            sNameCommand = k + aKey[
                2]  # Specific name of the command to assign to a key.
            if 'P' in aKey[2]:
                aRelease = [sNameCommand, False]
            else:
                aRelease = [False, sNameCommand]

            # Key Exceptions
            dExceptions = {
                'SPACE': 'Space',
                'COMMA': ',',
            }
            if aKey[0] in dExceptions.keys():
                sKey = dExceptions[aKey[0]]
            else:
                sKey = aKey[0]

            # Continue here : Shift turns on for some reason
            cmds.runTimeCommand(k,
                                annotation=k.replace('_', ' '),
                                category="Custom Scripts",
                                command=(sCommand),
                                showInHotkeyEditor=1)
            cmds.hotkey(keyShortcut=aKey[0].lower(),
                        sht=aMod[0],
                        ctl=aMod[1],
                        alt=aMod[2],
                        cmd=aMod[3],
                        name=None,
                        rn=None)
            cmds.nameCommand(sNameCommand,
                             ann=k.replace('_', ' '),
                             c=k,
                             stp='python')

            cmds.hotkey(keyShortcut=aKey[0].lower(),
                        sht=aMod[0],
                        ctl=aMod[1],
                        alt=aMod[2],
                        cmd=aMod[3],
                        name=aRelease[0],
                        rn=aRelease[1])
            print '%s : CREATED!' % k