Установка горячей клавиши для пользовательского runTimeCommand в Maya - PullRequest
0 голосов
/ 27 января 2020

Моя цель: Создать простой класс для добавления некоторых макросов клавиатуры в Maya при запуске.

Моя проблема: Предполагаемые назначения клавиш не установлены в редакторе горячих клавиш. Редактирование их вручную работает, но так как это команды по умолчанию, их нужно устанавливать программно.

-thanks

class Macros(object):
    '''
    '''
    def __init__(self):
        '''
        '''

    def setMacro(self, name=None, k=None, cat=None, ann=None):
        '''
        Sets a default runtime command with a keyboard shotcut.
        args:
            name = 'string' - The command name you provide must be unique. The name itself must begin with an alphabetic character or underscore followed by alphanumeric characters or underscores.
            cat = 'string' - catagory - Category for the command.
            ann = 'string' - annotation - Description of the command.
            k = 'string' - keyShortcut - Specify what key is being set.
                            modifiers: alt, ctl, sht - Modifier values are set by adding a '+' between chars. ie. 'sht+z'.
        '''
        command = "from macros import Macros; Macros.{0}();".format(name)

        #set runTimeCommand
        pm.runTimeCommand(
                name,
                annotation=ann,
                category=cat,
                command=command,
                default=True,
        )

        #set hotkey
        #modifiers
        ctl=False; alt=False; sht=False
        for char in k.split('+'):
            if char=='ctl':
                ctl = True
            elif char=='alt':
                alt = True
            elif char=='sht':
                sht = True
            else:
                key = char

        pm.hotkey(keyShortcut=key, name=name, ctl=ctl, alt=alt, sht=sht) #set only the key press.




    #  ------------------------------------------------------

    @staticmethod
    def hk_back_face_culling():
        '''
        hk_back_face_culling
        Toggle Back-Face Culling
        1
        '''
        print 'hk_back_face_culling()'

Вызов:

m = Macros()
m.setMacro(name='hk_back_face_culling', k='1', cat='Display', ann='Toggle back-face culling')

Редактировать: Я сделал это наполовину, добавив команду name.

#set command
nameCommand = pm.nameCommand(
        '{0}Command'.format(name),
        annotation=ann,
        command='python("{0}")'.format(command),
)

1 Ответ

0 голосов
/ 29 января 2020

Вот полностью рабочий пример. Возможно, это может помочь кому-то в будущем.

class Macros(object):
    '''
    '''
    def __init__(self):
        '''
        '''

        self.setMacro(name='hk_back_face_culling', k='1', cat='Display', ann='Toggle back-face culling')


    def setMacro(self, name=None, k=None, cat=None, ann=None):
        '''
        Sets a default runtime command with a keyboard shotcut.
        args:
            name = 'string' - The command name you provide must be unique. The name itself must begin with an alphabetic character or underscore followed by alphanumeric characters or underscores.
            cat = 'string' - catagory - Category for the command.
            ann = 'string' - annotation - Description of the command.
            k = 'string' - keyShortcut - Specify what key is being set.
                        key modifier values are set by adding a '+' between chars. ie. 'sht+z'.
                        modifiers:
                            alt, ctl, sht
                        additional valid keywords are:
                            Up, Down, Right, Left,
                            Home, End, Page_Up, Page_Down, Insert
                            Return, Space
                            F1 to F12
                            Tab (Will only work when modifiers are specified)
                            Delete, Backspace (Will only work when modifiers are specified)
        '''
        command = self.formatSource(name, removeTabs=2)

        #set runTimeCommand
        pm.runTimeCommand(
                name,
                annotation=ann,
                category=cat,
                command=command,
                default=True,
        )

        #set command
        nameCommand = pm.nameCommand(
                '{0}Command'.format(name),
                annotation=ann,
                command=name,
        )

        #set hotkey
        #modifiers
        ctl=False; alt=False; sht=False
        for char in k.split('+'):
            if char=='ctl':
                ctl = True
            elif char=='alt':
                alt = True
            elif char=='sht':
                sht = True
            else:
                key = char

        # print name, char, ctl, alt, sht
        pm.hotkey(keyShortcut=key, name=nameCommand, ctl=ctl, alt=alt, sht=sht) #set only the key press.


    def formatSource(self, cmd, removeTabs=0):
        '''
        Return the text of the source code for an object.
        The source code is returned as a single string.
        Removes lines containing '@' or 'def ' ie. @staticmethod.
        args:
            cmd = module, class, method, function, traceback, frame, or code object.
            removeTabs = int - remove x instances of '\t' from each line.
        returns:
            A Multi-line string.
        '''
        from inspect import getsource
        source = getsource(getattr(Macros, cmd))

        l = [s.replace('\t', '', removeTabs) for s in source.split('\n') if s and not '@' in s and not 'def ' in s]
        return '\n'.join(l)



    #--------------------------------------------------------------------------------------


    @staticmethod
    def hk_back_face_culling():
        '''
        hk_back_face_culling
        Toggle Back-Face Culling
        '''
        print 'hk_back_face_culling()'
...