Exemple #1
0
def __addToShalf(shelfCmd, label=''):
    '''
    update : 2015-04-28
    '''

    # 현재 쉐프탭 이름 알아옴.
    currentShelfTab = pm.shelfTabLayout(pm.melGlobals['gShelfTopLevel'],
                                        q=True,
                                        selectTab=True)

    # 생성
    pm.shelfButton(
        commandRepeatable=True,
        image1='commandButton.png',  # 아이콘
        width=32,
        height=32,
        label=label,  # 타이틀
        imageOverlayLabel=label,  # 라벨 (5글자 이하)
        font="smallPlainLabelFont",
        # "boldLabelFont", "smallBoldLabelFont", "tinyBoldLabelFont", "plainLabelFont", "smallPlainLabelFont", "obliqueLabelFont", "smallObliqueLabelFont", "fixedWidthFont", "smallFixedWidthFont".
        #overlayLabelColor     = (1, 1, .25),
        overlayLabelBackColor=(0, 0, 0, 0),  # (.15, .9, .1, .4),
        annotation=label,  # 참조글
        sourceType='python',
        command=shelfCmd,  # 명령어
        doubleClickCommand='',
        parent=currentShelfTab,
    )
Exemple #2
0
    def addToShalf(self):
        '''
        update : 2015-04-28
        '''

        # 현재 쉐프탭 이름 알아옴.
        currentShelfTab = pm.shelfTabLayout( pm.melGlobals['gShelfTopLevel'], q=True, selectTab=True )

        # 생성
        if True:
            pm.shelfButton(
                commandRepeatable=True,
                image1=shelf_icon,                    # 아이콘
                width=32,
                height=32,
                label=title,                          # 타이틀
                imageOverlayLabel=shelf_label,        # 라벨 (5글자 이하)
                font="smallPlainLabelFont",
                # "boldLabelFont", "smallBoldLabelFont", "tinyBoldLabelFont", "plainLabelFont", "smallPlainLabelFont", "obliqueLabelFont", "smallObliqueLabelFont", "fixedWidthFont", "smallFixedWidthFont".
                #overlayLabelColor     = (1, 1, .25), 
                overlayLabelBackColor=(0, 0, 0, 0),  #(.15, .9, .1, .4),
                annotation=shelf_anno,                # 참조글 
                sourceType='python',
                command=shelf_cmd,                    # 명령어
                doubleClickCommand='',
                parent=currentShelfTab,
            )
Exemple #3
0
def onMayaDroppedPythonFile(*args):
    parentTab = mel.eval(
        '''global string $gShelfTopLevel;string $shelves = `tabLayout -q -selectTab $gShelfTopLevel`;'''
    )
    DIR = os.path.dirname(__file__)
    module, ext = os.path.splitext(os.path.basename(__file__))
    pm.shelfButton(commandRepeatable=True,
                   image1="pythonFamily.png",
                   iol="FXPath",
                   label="Path_Tracker_Win",
                   parent=parentTab,
                   command=dedent("""
        import sys
        MODULE = r"{DIR}"
        sys.path.insert(0,MODULE) if MODULE not in sys.path else None
        import VertexAnimationTools
        VertexAnimationTools.UI()
    """.format(DIR=DIR)))

    import sys
    MODULE = DIR
    sys.path.insert(0, MODULE) if MODULE not in sys.path else None
    import VertexAnimationTools
    VertexAnimationTools.UI()


# import sys
# MODULE = r"C:\Users\timmyliang\Desktop\VertexAnimationTools_Maya"
# sys.path.insert(0,MODULE) if MODULE not in sys.path else None
# import VertexAnimationTools_CMDS
# reload(VertexAnimationTools_CMDS)
# import VertexAnimationTools
# reload(VertexAnimationTools)
# VertexAnimationTools.UI()
Exemple #4
0
def onMayaDroppedPythonFile(*args):
    qInitResources()
    parentTab = mel.eval(
        '''global string $gShelfTopLevel;string $shelves = `tabLayout -q -selectTab $gShelfTopLevel`;'''
    )
    module, ext = os.path.splitext(os.path.basename(__file__))
    pm.shelfButton(commandRepeatable=True,
                   image1="FightExport.png",
                   iol="export",
                   label="Fight Export Window",
                   parent=parentTab,
                   command=dedent("""
        import {module}
        reload({module})
        from {module} import ExportRigWindow
        try:
            MF_RigWin = ExportRigWindow()
            MF_RigWin.mayaShow()
        except :
            import traceback
            traceback.print_exc()
        
    """.format(module=module)))

    try:
        MF_RigWin = ExportRigWindow()
        MF_RigWin.mayaShow()
    except:
        import traceback
        traceback.print_exc()

    # NOTE 构建 Mod
    createModFolder(module)
Exemple #5
0
def install():
    """
    Call this function to install Mosketch for Maya
        mosketch_for_maya.install()
    """
    shelf_name = "MosketchForMaya"

    # First get maya "official" shelves layout
    top_level_shelf_layout = mel.eval(
        "global string $gShelfTopLevel; $temp = $gShelfTopLevel;")
    # Get all shelves
    shelf_layout = pmc.shelfLayout(shelf_name, parent=top_level_shelf_layout)
    start_icon_name = os.path.dirname(os.path.abspath(__file__)) + "/start.png"
    stop_icon_name = os.path.dirname(os.path.abspath(__file__)) + "/stop.png"
    pmc.shelfButton(
        label='Start',
        parent=shelf_layout,
        image1=start_icon_name,
        command=
        'import mosketch_for_maya;reload(mosketch_for_maya);mosketch_for_maya.start()'
    )
    pmc.shelfButton(label='Stop',
                    parent=shelf_layout,
                    image1=stop_icon_name,
                    command='mosketch_for_maya.stop()')
Exemple #6
0
def loadShelfs():
    grid.maya.general.login.checkLogin()

    iconFolderPath = grid.path.path(os.environ.get('ICONS_PATH', None))

    #    get shelfTopLevel from mel command
    shelfTopLevel = pm.mel.eval('$tmpVar=$gShelfTopLevel')

    #    get user shelf from shelf.xml
    shelfXmlPath = grid.path.path(__file__).parent.joinpath('shelf.xml')

    if shelfXmlPath.exists():
        print('Build Grid Shelf')

        #  open xml document
        shelfXml = xml.dom.minidom.parse(shelfXmlPath)

        #    search shelf node
        for shelf in shelfXml.getElementsByTagName('shelf'):

            # delete shelf if it already exist
            name = shelf.attributes["name"].value
            if pm.shelfLayout(name, exists=True):
                pm.deleteUI(name)

            newShelf = pm.shelfLayout(name, p=shelfTopLevel)
            newShelf.setWidth(32)
            newShelf.setHeight(32)

            for button in shelf.childNodes:
                if button.nodeType == 1:
                    cmd = button.attributes['cmd'].value
                    iconFile = button.attributes['icon'].value
                    iconPath = iconFolderPath.joinpath(iconFile)
                    annotation = button.attributes['annot'].value
                    sourceType = button.attributes['mode'].value
                    imageOverlayLabel = button.attributes['iol'].value
                    style = button.attributes['style'].value

                    try:
                        # Command executed when the control is double clicked.
                        dccmd = button.attributes['dccmd'].value
                    except KeyError:
                        dccmd = None
                    if dccmd:
                        pm.shelfButton(c=cmd,
                                       image=iconPath,
                                       ann=annotation,
                                       stp=sourceType,
                                       iol=imageOverlayLabel,
                                       st=style,
                                       dcc=dccmd)
                    else:
                        pm.shelfButton(c=cmd,
                                       image=iconPath,
                                       ann=annotation,
                                       stp=sourceType,
                                       iol=imageOverlayLabel,
                                       st=style)
def build_shelf( shelf_name, tools ):
  for tool in tools:
    if not __shelf_button_exists( shelf_name, tool[ 'name'] ):
      pmc.shelfButton( c = tool['command'],
                       i = tool['image'],
                       l = tool['name'],
                       stp = tool['sourceType'],
                       p = shelf_name )
Exemple #8
0
def onMayaDroppedPythonFile(*args, **kwargs):
    current_shelf = pm.mel.eval(
        "shelfTabLayout -query -selectTab $gShelfTopLevel")

    pm.shelfButton(i='MS_shotSculptor_Icon.png',
                   p=current_shelf,
                   sourceType='python',
                   label='MS-Shot-Sculptor',
                   c="import MS_ShotSculptor; reload(MS_ShotSculptor)",
                   ann="Open MS-Shot-Sculptor")
Exemple #9
0
 def do_create(self):
     # save image
     # todo: fix the hard coding of icon_dir with configs
     icon_dir = r"C:\Users\aaron\Documents\maya\2016\prefs\icons"
     icon_path = os.path.join(icon_dir, "%s.png" % self.script_name)
     self.icon_label.pixmap().save(icon_path, "PNG")
     # create shelf button
     command_type, command = self.get_command()
     pm.shelfButton(image="%s.png" % self.script_name,
                    style="iconOnly",
                    command=command,
                    sourceType=command_type,
                    parent=self.current_shelf_name)
Exemple #10
0
def toolShelf():

    tab = tabLayout()
    shelfLayout(
        'Tools - Copy these freely into your shelf, they will get remade when fossil is opened'
    )

    shelfButton(
        image1='zeropose.png',
        annotation='Zero Controllers',
        command=
        "import pdil.tool.fossil.userTools;pdil.core.alt.call('Zero Controllers')()"
    )

    shelfButton(
        image1='skeletonTool.png',
        annotation='Open Fossil',
        command="import pdil.tool.fossil.main;pdil.core.alt.call('Rig Tool')()"
    )

    shelfButton(
        image1='selectAllControls.png',
        annotation='Select All Controllers',
        command=
        "import pdil.tool.fossil.userTools;pdil.core.alt.call('Select All Controllers')()"
    )

    shelfButton(
        image1='quickHideControls.png',
        annotation='Similar to "Isolated Selected" but just for rig controls',
        command=
        "import pdil.tool.rigControls;pdil.core.alt.call('Quick Hide Controls')()"
    )

    return tab
Exemple #11
0
  def makeShelfButton(cls, name, command, icon, annotation='', *args, **kwargs):
      """ """
      currentShelf = pm.mel.eval('tabLayout -q -st $gShelfTopLevel;')

      buttonArray = pm.shelfLayout(currentShelf, query=True, childArray=True)
      if buttonArray:
        for item in buttonArray:
          label = pm.shelfButton(item, query=True, label=True)
          if label == name:
            pm.deleteUI(item)

      pm.setParent(currentShelf)

      pm.shelfButton(label=name, annotation=annotation, image1=icon, command=command)
Exemple #12
0
def loadShelfs():
    grid.maya.general.login.checkLogin()
    
    iconFolderPath = grid.path.path(os.environ.get('ICONS_PATH',None))
    
    #    get shelfTopLevel from mel command
    shelfTopLevel = pm.mel.eval('$tmpVar=$gShelfTopLevel')
    
    #    get user shelf from shelf.xml
    shelfXmlPath = grid.path.path(__file__).parent.joinpath('shelf.xml')
    
    
    if shelfXmlPath.exists() :        
        print ('Build Grid Shelf')

        #  open xml document
        shelfXml = xml.dom.minidom.parse(shelfXmlPath)
        
        #    search shelf node
        for shelf in shelfXml.getElementsByTagName('shelf'):
            
            # delete shelf if it already exist
            name = shelf.attributes["name"].value
            if pm.shelfLayout(name,exists=True) :
                pm.deleteUI(name)
            
            newShelf = pm.shelfLayout(name,p=shelfTopLevel)
            newShelf.setWidth(32)
            newShelf.setHeight(32)
            
            for button in shelf.childNodes:
                if button.nodeType == 1 :
                    cmd = button.attributes['cmd'].value
                    iconFile = button.attributes['icon'].value
                    iconPath =iconFolderPath.joinpath(iconFile)
                    annotation = button.attributes['annot'].value
                    sourceType = button.attributes['mode'].value
                    imageOverlayLabel = button.attributes['iol'].value
                    style = button.attributes['style'].value
                    
                    try :
                        # Command executed when the control is double clicked.
                        dccmd = button.attributes['dccmd'].value
                    except KeyError :
                        dccmd = None
                    if dccmd :
                        pm.shelfButton(c=cmd, image=iconPath, ann=annotation, stp=sourceType, iol=imageOverlayLabel, st=style, dcc=dccmd)
                    else :
                        pm.shelfButton(c=cmd, image=iconPath, ann=annotation, stp=sourceType, iol=imageOverlayLabel, st=style)
Exemple #13
0
def get_shelf_submenus(shelf_button):
    popup_menus = pm.shelfButton(shelf_button, q=True, popupMenuArray=True)
    if not popup_menus:
        return []

    popup_menu = popup_menus[0]
    popup_menu_items = pm.popupMenu(popup_menu, q=True, itemArray=True) or []

    # Ignore popup items that are defaults, eg. "Open" and "Edit" that appear in the
    # shelf context menu.
    def is_default_menu_item(popup):
        cmd = pm.menuItem(p, q=True, command=True)
        return isinstance(cmd, basestring) and cmd.startswith('/*dSBRMBMI*/')

    popup_menu_items = [
        p for p in popup_menu_items if not is_default_menu_item(p)
    ]

    # popupMenu returns ambiguous paths.  Prefix the path to the popup menu to make
    # sure we query the right thing.
    popup_menu_items = [popup_menu + '|' + item for item in popup_menu_items]

    # Replace any dividers with separator.
    popup_menu_items = [
        separator if pm.menuItem(p, q=True, divider=True) else p
        for p in popup_menu_items
    ]

    return popup_menu_items
Exemple #14
0
def onMayaDroppedPythonFile(*args):
    parentTab = mel.eval(
        '''global string $gShelfTopLevel;string $shelves = `tabLayout -q -selectTab $gShelfTopLevel`;'''
    )
    module, ext = os.path.splitext(os.path.basename(__file__))
    pm.shelfButton(commandRepeatable=True,
                   image1="pythonFamily.png",
                   iol="FXPath",
                   label="Path_Tracker_Win",
                   parent=parentTab,
                   command=dedent("""
        import {module}
        reload({module})
        {module}.show()
    """.format(module=module)))

    show()
Exemple #15
0
def load_shelf():
    delete_shelf()
    ReloadScripts().go()

    gShelfTopLevel = pm.mel.eval(
        'global string $gShelfTopLevel; string $temp=$gShelfTopLevel')
    pm.shelfLayout(PROJ, cellWidth=33, cellHeight=33, p=gShelfTopLevel)

    # Load in the buttons
    json_file = file(os.path.join(SHELF_DIR, "shelf.json"))
    data = json.loads(json_file.read())
    for shelf_item in data['shelfItems']:
        if shelf_item['itemType'] == 'button':
            icon = os.path.join(ICON_DIR, shelf_item['icon'])
            annotation = shelf_item['annotation']

            path = "pipe.tools." + shelf_item['tool']
            function = shelf_item['function']
            class_with_method = function.split(".")
            module = class_with_method[0]
            method = class_with_method[1]

            pm.shelfButton(
                command="from %s import %s; shelf_item = %s(); shelf_item.%s" %
                (path, module, module, method),
                annotation=annotation,
                image=icon,
                label=annotation)
        else:
            pm.separator(horizontal=False,
                         style='shelf',
                         enable=True,
                         width=35,
                         height=35,
                         visible=1,
                         enableBackground=0,
                         backgroundColor=(0.2, 0.2, 0.2),
                         highlightColor=(0.321569, 0.521569, 0.65098))

    # Set default preferences
    pm.env.optionVars['generateUVTilePreviewsOnSceneLoad'] = 1

    # shelf loaded correctly
    print("*** Shelf loaded :) ***")
    sys.path.append(os.getcwd())
Exemple #16
0
 def addButton(self,
               label,
               icon="commandButton.png",
               command=_null,
               doubleCommand=_null):
     '''Adds a shelf button with the specified label, command, double click command and image.'''
     pm.setParent(self.name)
     if icon:
         icon = self.iconPath + icon
     pm.shelfButton(width=37,
                    height=37,
                    image=icon,
                    l=label,
                    command=command,
                    dcc=doubleCommand,
                    imageOverlayLabel=label,
                    olb=self.labelBackground,
                    olc=self.labelColour)
Exemple #17
0
    def makeLctShelf(cls, *args, **kwargs):
        """ """
        src = lcPath.Path.getSrcPath()
        mel = lcPath.Path.getMelPath()
        shelf = os.path.normpath(os.path.join(mel, 'shelf_LCT.mel'))

        file = open(shelf, 'w+')
        opening = 'global proc shelf_LCT () {\n    global string $gBuffStr;\n    global string $gBuffStr0;\n    global string $gBuffStr1;\n\n'
        closing = '\n}'

        file.write(opening)

        initShelfIcon = os.path.normpath(
            os.path.join(src, 'icons', 'shelf.png'))
        initShelfLabel = 'Init Shelf'
        initShelfAnno = 'Initialize LCT Shelf'
        initShelfCommand = 'from lct.src.core.lcShelf import Shelf as shelf\nshelf.makeLctShelf()'

        file.write(closing)

        file.close()

        if not pm.layout('LCT', ex=True):
            if os.name == 'nt':
                shelf = shelf.replace('\\', '/')
            pm.mel.loadNewShelf(shelf)
            pm.shelfButton(label=initShelfLabel,
                           annotation=initShelfAnno,
                           image1=initShelfIcon,
                           command=initShelfCommand)
        else:
            pm.mel.eval(
                'shelfTabLayout -edit -selectTab "LCT" $gShelfTopLevel;')

        list = lcUtility.Utility.buildPublishList(inline=False)
        for item in list:
            if item[3] == 'True':
                label = item[0]
                annotation = item[2]
                icon = os.path.normpath(
                    os.path.join(src, label, item[0] + '.png'))
                runCommand = item[4]

                cls.makeShelfButton(label, runCommand, icon, annotation)
Exemple #18
0
def saveToTab_feet(target_feetShelf):
    #Clear out old data to store clean new data
    storeCmds_feet = ""

    #List selected
    selPose = pm.ls(sl=True)

    #Error window if nothing selected
    #List keyable, readable, writable, connectable, and unlocked attributes in selected
    #Grab values of selected and concatenates keyable channels
    if len(selPose) < 1:
        pm.warning("Nothing Selected.  Please select at least one object.")
    else:
        for all in selPose:
            keyable = pm.listAttr(all, k=True, r=True, w=True, c=True, u=True)
            print keyable
            for vals in keyable:
                findVal = pm.getAttr(all + "." + vals)
                print findVal
                starterCiph = "setAttr "
                enderCiph = ";\n"
                shelfSave = (starterCiph +
                             (all + "." + vals) + " %f" + enderCiph) % findVal
                storeCmds_feet += shelfSave
                print storeCmds_feet

        #prompt dialog for artist to enter a name of the pose and button to save to shelf
        pd_feet = pm.promptDialog(t="Feet Pose",
                                  m="Name of Pose?",
                                  b="Save to Shelf")

        if pd_feet == "Save to Shelf":

            pd_feet_name = pm.promptDialog(q=True, text=True)
            #pm.internalVar(usd = True)
            pm.shelfButton(l=pd_feet_name,
                           ann=pd_feet_name,
                           imageOverlayLabel=pd_feet_name,
                           i1="zenRemember_feetIcon.png",
                           command=storeCmds_feet,
                           p=target_feetShelf,
                           sourceType="mel")
Exemple #19
0
def createShelfBtn():
    # Get top shelf as parent
    pm.mel.eval('global string $gShelfTopLevel')
    topShelf = pm.mel.eval('$temp = $gShelfTopLevel')
    currentShelf = pm.tabLayout(topShelf, query=True, selectTab=True)
    pm.setParent(topShelf + '|' + currentShelf)

    # Create the button
    pm.shelfButton(
        annotation='myRigTool',
        command='python(\"import sys\");\n'
        '\n'
        'catchQuiet ( `python(\"del sys.modules[\'myRigTool\']\")`);\n'
        'catchQuiet ( `python(\"del sys.modules[\'myRigTool.UI\']\")`);\n'
        'catchQuiet ( `python(\"del sys.modules[\'myRigTool.core\']\")`);\n'
        '\n'
        'python(\"import myRigTool\");',
        label='myRigTool',
        image1='commandButton.png',
        sourceType='mel')
Exemple #20
0
    def addCustomLauncherToShelf(self):
        if not self._deadlineUIStatus:
            raise DeadlineMayaException('Deadline UI not initialized')

        command = (
            'import ideadline.maya._deadlinemaya as deadlineSubmitter;'
            'deadlineSubmitter.DeadlineMayaSubmitterUI().openSubmissionWindow()'
        )
        try:
            pc.uitypes.ShelfButton(
                self._deadlineShelfButton).setCommand(command)

        except:
            pc.shelfButton(self._deadlineShelfButton,
                           parent=self._deadlineShelfName,
                           annotation=self._deadlineShelfButton +
                           ": Use this one to submit",
                           image1="pythonFamily.xpm",
                           stp="python",
                           command=command)
Exemple #21
0
def createShelfBtn():
    # Get top shelf as parent
    pm.mel.eval('global string $gShelfTopLevel')
    topShelf = pm.mel.eval('$temp = $gShelfTopLevel')
    currentShelf = pm.tabLayout(topShelf, query=True, selectTab=True)
    pm.setParent(topShelf + '|' + currentShelf)

    # Create the button
    pm.shelfButton(
    annotation = 'myRigTool',
    command =
    'python(\"import sys\");\n'
    '\n'
    'catchQuiet ( `python(\"del sys.modules[\'myRigTool\']\")`);\n'
    'catchQuiet ( `python(\"del sys.modules[\'myRigTool.UI\']\")`);\n'
    'catchQuiet ( `python(\"del sys.modules[\'myRigTool.core\']\")`);\n'
    '\n'
    'python(\"import myRigTool\");',
    label='myRigTool',
    image1='commandButton.png',
    sourceType='mel'
    )
Exemple #22
0
def onMayaDroppedPythonFile(*args):
    parentTab = mel.eval(
        '''global string $gShelfTopLevel;string $shelves = `tabLayout -q -selectTab $gShelfTopLevel`;'''
    )
    py_path = __file__[:-1] if __file__.endswith(".pyc") else __file__
    pm.shelfButton(commandRepeatable=True,
                   image1="commandButton.png",
                   iol="export",
                   label="Minigame Export Window",
                   parent=parentTab,
                   command=dedent(ur"""
        import os
        path = r"%s"
        if os.path.exists(path):
            try:
                exec(open(path).read())
            except:
                QtWidgets.QMessageBox.warning(self,u"警告",u"执行错误\n请重新安装")
        else:
            QtWidgets.QMessageBox.warning(self,u"警告",u"脚本路径不存在\n请重新安装")
    """ % py_path))
    show()
Exemple #23
0
def make_shelf_icon(name,
                    icon_path,
                    command_str,
                    source_type="python",
                    annotation=None):
    """
    make an icon on the current shelf
    Args:
        name (str): the string name for this shelf item
        icon_path (str): the path to the image to use for the shelf item
        command_str (str): the command to run when pressing this shelf item
        source_type (str): the type of command, mel or python
        annotation (str): the tool-tip annotation to display on hovering over this shelf item

    Returns:
        returns the button just created
    """
    # type: (str, str, str, str, str) -> pm.uitypes.ShelfButton
    icon_path = os.path.normpath(icon_path)

    # Maya requires all paths to be forward slash for internal use
    if platform.system().startswith("Win"):
        icon_path = icon_path.replace("\\", "/")

    try:
        current_shelf = pm.uitypes.ShelfLayout(
            pm.mel.eval('tabLayout -q -st $gShelfTopLevel;'))

        for item in [
                x for x in current_shelf.getChildren()
                if isinstance(x, pm.uitypes.ShelfButton)
        ]:
            if name == item.getLabel():
                item.delete()

        # you must set the active parent before creating shelf buttons or they will be parented under maya's main window
        pm.setParent(current_shelf)

        shelf_button = pm.shelfButton(label=name)
        shelf_button.setSourceType(source_type)
        shelf_button.setCommand(command_str)
        shelf_button.setImage(icon_path)
        if annotation:
            shelf_button.setAnnotation(annotation)

        return shelf_button

    except Exception as e:
        pm.warning(
            "Something went wrong making the shelf item: {}\n Exception Msg: {}"
            .format(name, e.message))
Exemple #24
0
  def makeLctShelf(cls, *args, **kwargs):
      """ """
      src = path.getSrcPath()
      mel = path.getMelPath()
      shelf = os.path.normpath(os.path.join(mel, 'shelf_LCT.mel'))

      file = open(shelf, 'w+')
      opening = 'global proc shelf_LCT () {\n    global string $gBuffStr;\n    global string $gBuffStr0;\n    global string $gBuffStr1;\n\n'
      closing = '\n}'

      file.write(opening)

      initShelfIcon = os.path.normpath(os.path.join(src, 'icons', 'shelf.png'))
      initShelfLabel = 'Init Shelf'
      initShelfAnno = 'Initialize LCT Shelf'
      initShelfCommand = 'from lct.src.core.lcShelf import Shelf as shelf\nshelf.makeLctShelf()'

      file.write(closing)

      file.close()

      if not pm.layout('LCT', ex=True):
        if os.name == 'nt':
            shelf = shelf.replace('\\','/')
        pm.mel.loadNewShelf(shelf)
        pm.shelfButton(label=initShelfLabel, annotation=initShelfAnno, image1=initShelfIcon, command=initShelfCommand)
      else:
        pm.mel.eval('shelfTabLayout -edit -selectTab "LCT" $gShelfTopLevel;')
        
      list = utility.buildPublishList(inline=False)
      for item in list:
        if item[3] == 'True':
          label = item[0]
          annotation = item[2]
          icon = os.path.normpath(os.path.join(src, label, item[0]+'.png'))
          runCommand = item[4]

          cls.makeShelfButton(label, runCommand, icon, annotation)
Exemple #25
0
    def makeShelfButton(cls,
                        name,
                        command,
                        icon,
                        annotation='',
                        *args,
                        **kwargs):
        """ """
        myPlatform = platform.system()
        if myPlatform.startswith('Win'):
            icon = icon.replace('\\', '/')

        try:
            currentShelf = pm.mel.eval('tabLayout -q -st $gShelfTopLevel;')

            # find the button if it already exists and delete it
            buttonArray = pm.shelfLayout(currentShelf,
                                         query=True,
                                         childArray=True)
            if buttonArray:
                items = [
                    item for item in buttonArray
                    if pm.objectTypeUI(item) == 'shelfButton'
                ]  # get only shelfButtons, just in case
                for i in items:
                    label = pm.shelfButton(i, query=True, label=True)
                    if label == name:
                        pm.deleteUI(i)

            pm.setParent(currentShelf)

            pm.shelfButton(label=name,
                           annotation=annotation,
                           image1=icon,
                           command=command)
        except:
            lcUtility.Utility.lc_print_exception(
                message='Something went wrong making the shelf icon')
def BYU_load_shelf():
    BYU_delete_shelf()

    gShelfTopLevel = pm.mel.eval(
        'global string $gShelfTopLevel; string $temp=$gShelfTopLevel')
    pm.shelfLayout(PROJ, cellWidth=33, cellHeight=33, p=gShelfTopLevel)

    #### Okay, for some reason, deleting the shelf from a shelf button crashes Maya.
    #### I'm saving this for another day, or for someone more adventurous.
    #### Make the hard-coded reload button:
    # shelfButton(command="printcow()", annotation="Reload the shelf",
    #			 image=os.path.join(ICON_DIR, "reload.xpm"))

    #### Load in the buttons
    json_file = file(os.path.join(SHELF_DIR, "shelf.json"))
    data = json.loads(json_file.read())
    for shelfItem in data['shelfItems']:
        if shelfItem['itemType'] == 'button':
            icon = os.path.join(ICON_DIR, shelfItem['icon'])
            annotation = shelfItem['annotation']
            pythonFile = shelfItem['pythonFile'][:-3]
            pm.shelfButton(command="import %s; %s" %
                           (pythonFile, shelfItem['function']),
                           annotation=annotation,
                           image=icon,
                           label=annotation)
        else:
            pm.separator(horizontal=False, style='none', enable=True, width=7)
            pm.separator(horizontal=False,
                         style='none',
                         enable=True,
                         width=2,
                         backgroundColor=(0.5, 0.5, 0.5))
            pm.separator(horizontal=False, style='none', enable=True, width=7)

    #setUpSoup(gShelfTopLevel)
    # Set default preferences
    pm.env.optionVars['generateUVTilePreviewsOnSceneLoad'] = 1
Exemple #27
0
 def add_button(self,
                shelf,
                label='',
                annotation='',
                command='',
                icon='',
                image_overlay_label=''):
     button_name = pm.shelfButton(image1=icon,
                                  parent=shelf,
                                  label=label,
                                  annotation=annotation,
                                  command=command,
                                  imageOverlayLabel=image_overlay_label)
     return button_name
    def makeShelfButton(cls,
                        name,
                        command,
                        icon,
                        annotation='',
                        *args,
                        **kwargs):
        """ """
        currentShelf = pm.mel.eval('tabLayout -q -st $gShelfTopLevel;')

        buttonArray = pm.shelfLayout(currentShelf, query=True, childArray=True)
        if buttonArray:
            for item in buttonArray:
                label = pm.shelfButton(item, query=True, label=True)
                if label == name:
                    pm.deleteUI(item)

        pm.setParent(currentShelf)

        pm.shelfButton(label=name,
                       annotation=annotation,
                       image1=icon,
                       command=command)
Exemple #29
0
def FbxExporterInstall():
    DTag = 'FbxExporter'
    icLab = 'FbxExp'
    ann = 'Click export, Double click UI'
    shelf = 'JAShelf'
    icon = 'fbxReview.png'

    command = """
from FbxExporter import FbxExporter
fbxExp = FbxExporter.FbxExporter.instance()
if len(fbxExp):
	fbxExp.export(True)"""

    command2 = """
from FbxExporter import FbxExporterUI
from FbxExporter import FbxExporter
ui = FbxExporterUI.FbxExporterUI(True)"""

    if not pm.layout(shelf, q=True, ex=True):
        pm.mel.addNewShelfTab(shelf)

    shelfButtons = pm.shelfLayout(shelf, q=True, ca=True)
    print shelfButtons
    if isinstance(shelfButtons, list):
        for button in shelfButtons:
            if pm.shelfButton(button, q=True, docTag=True) == DTag:
                logging.warn('%s is yet in your shelf tab' % icLab)
                return

    pm.shelfButton('FbxExp',
                   ann=ann,
                   iol=icLab,
                   i1=icon,
                   dtg=DTag,
                   c=command,
                   dcc=command2,
                   p=shelf)
def __shelf_button_exists( shelf_name, button_name ):
    
    exists = False
    
    main_shelf = __get_main_shelf( )
    if main_shelf is None:
      return False
    
    tabs = pmc.shelfTabLayout( main_shelf, q = True, ca = True )
    if not tabs is None:
      __select_shelf( shelf_name )
      full_shelf = '{0}|{1}'.format( main_shelf, shelf_name )
      buttons = pmc.shelfLayout( full_shelf, q = True, ca = True )
      for button in buttons:
        full_button = '{0}|{1}'.format( full_shelf, button )
        if button_name == pmc.shelfButton( full_button, q = True, l = True ):
          return True
Exemple #31
0
def load_shelf():
	delete_shelf()
	ReloadScripts().go()

	gShelfTopLevel = pm.mel.eval('global string $gShelfTopLevel; string $temp=$gShelfTopLevel')
	pm.shelfLayout(PROJ, cellWidth=33, cellHeight=33, p=gShelfTopLevel)

	# Load in the buttons
	json_file = file(os.path.join(SHELF_DIR, "shelf.json"))
	data = json.loads(json_file.read())
	for shelf_item in data['shelfItems']:
		if shelf_item['itemType'] == 'button':
			icon = os.path.join(ICON_DIR, shelf_item['icon'])
			annotation = shelf_item['annotation']
			label = shelf_item['label']

			# dcc = double click command: we can add a different command that goes when double clicked.
			dcc = shelf_item['double-click']
			# menu = submenu for right-click
			menu = shelf_item['menu']

			path = "pipe.tools." + shelf_item['tool']
			function = shelf_item['function']
			class_with_method = function.split(".")
			module = class_with_method[0]
			method = class_with_method[1]

			command_base = "from " + str(path) + " import " + str(module) + "; shelf_item = " + str(module) + "(); shelf_item."
			command = command_base + str(method)

			if dcc == 0:
				dcc = command
			else:
				dcc = command_base + str(dcc)

			if menu == 0:
				pm.shelfButton(c=command, ann=annotation, i=icon, l=annotation, iol=label, olb=(0,0,0,0), dcc=dcc)
			elif menu == 1:
				menu_items = shelf_item['menu_items']
				new_menu = build_menu_string(command_base, menu_items)
				mip = []
				for i in range (len(new_menu)):
					mip.append(i)
				pm.shelfButton(c=command, ann=annotation, i=icon, l=annotation, iol=label, olb=(0,0,0,0), dcc=dcc, mi=new_menu, mip=mip)

		else:
			pm.separator(horizontal=False, style='shelf', enable=True, width=35, height=35, visible=1, enableBackground=0, backgroundColor=(0.2,0.2,0.2), highlightColor=(0.321569, 0.521569, 0.65098))

	project_tools = get_production_scripts()
	if project_tools:
		pm.separator(horizontal=False, style='shelf', enable=True, width=35, height=35, visible=1, enableBackground=0, backgroundColor=(0.2,0.2,0.2), highlightColor=(0.321569, 0.521569, 0.65098))

		custom_modules = []
		for tool in project_tools:
			module = tool['function'].split(".")[0]
			custom_modules.append(module)

		create_tools_init(custom_modules)

		for tool in project_tools:
			name = tool['name']
			description = tool['description']
			icon = os.path.join(Environment().get_tools_dir(), tool['icon'])
			label = tool['label']
			function = tool['function']

			pm.shelfButton(c=get_production_tool_command(function), ann=description, i=icon, l=name, iol=label, olb=(0,0,0,0), dcc=dcc)

	# Set default preferences
	pm.env.optionVars['generateUVTilePreviewsOnSceneLoad'] = 1

	# shelf loaded correctly
	print("*** Shelf loaded :) ***")
	sys.path.append(os.getcwd())
Exemple #32
0
 def _createDeleteTabButton(self, shelfTab=None, *args):
     pm.shelfButton(annotation='Delete this tab.',
                    image1='delete-icon.xpm',
                    label='Delete',
                    command=partial(self._deleteShelfTab, shelfTab))
Exemple #33
0
    def add_shelf_item(parent_menu, shelf_button):
        # See if this shelf button has any submenus.
        popup_menus = pm.shelfButton(shelf_button, q=True, popupMenuArray=True)
        popup_menu_items = []
        if popup_menus:
            popup_menu = popup_menus[0]
            popup_menu_items = pm.popupMenu(popup_menu, q=True,
                                            itemArray=True) or []

            # Ignore popup items that are defaults, eg. "Open" and "Edit" that appear in the
            # shelf context menu.
            def is_default_menu_item(popup):
                cmd = pm.menuItem(p, q=True, command=True)
                return isinstance(
                    cmd, basestring) and cmd.startswith('/*dSBRMBMI*/')

            popup_menu_items = [
                p for p in popup_menu_items if not is_default_menu_item(p)
            ]

            # popupMenu returns ambiguous paths.  Prefix the path to the popup menu to make
            # sure we query the right thing.
            popup_menu_items = [
                popup_menu + '|' + item for item in popup_menu_items
            ]

        has_popup_menu = len(popup_menu_items) > 0

        # Create a menuItem matching the shelfButton.
        cmd = get_menu_item_params(shelf_button, pm.shelfButton)

        # Set the command to run.  We always wrap commands, so we can read the current script.
        # This way, we always run the latest version of the script, even if it's in a torn-off
        # menu and the shelf script has been changed.
        cmd['command'] = execute_menu_item(shelf_button, pm.shelfButton)
        cmd['sourceType'] = 'python'

        if has_popup_menu:
            cmd['subMenu'] = True
            cmd['tearOff'] = True

        def add_menu_item(name, cmd, with_option_button=None):
            pm.menuItem(name, **cmd)
            if with_option_button is not None:
                pm.menuItem(name + '_opt',
                            optionBox=True,
                            command=with_option_button)

        pm.setParent(parent_menu, menu=True)
        if popup_menu_items:
            # We can't show an option box if there's a popup menu.
            option_button_func = None
        else:
            option_button_func = lambda unused: shelf.show_in_shelf_editor(
                shelf_button)

        add_menu_item(shelf_button, cmd, with_option_button=option_button_func)

        # If this shelf button has popup menu items, add them in a submenu.
        for popup_menu_item in popup_menu_items:
            if pm.menuItem(popup_menu_item, q=True, divider=True):
                pm.menuItem(divider=True)
                continue

            cmd = get_menu_item_params(popup_menu_item, pm.menuItem)

            # This function is just to capture popup_menu_item:
            def add_submenu_item(popup_menu_item):
                cmd['command'] = execute_menu_item(popup_menu_item,
                                                   pm.menuItem)
                cmd['sourceType'] = 'python'
                add_menu_item(
                    popup_menu_item,
                    cmd,
                    with_option_button=lambda unused: shelf.
                    show_popup_in_shelf_editor(shelf_button, popup_menu_item))

            add_submenu_item(popup_menu_item)
Exemple #34
0
def load_shelf(shelfName, fileName):
    print("loading ", shelfName)
    delete_shelf(shelfName)
    ReloadScripts().go()

    gShelfTopLevel = pm.mel.eval(
        'global string $gShelfTopLevel; string $temp=$gShelfTopLevel')
    pm.shelfLayout(shelfName, cellWidth=33, cellHeight=33, p=gShelfTopLevel)

    # Load in the buttons
    json_file = open(os.path.join(SHELF_DIR, fileName))
    data = json.loads(json_file.read())
    for shelf_item in data['shelfItems']:
        if shelf_item['itemType'] == 'button':
            icon = os.path.join(ICON_DIR, shelf_item['icon'])
            annotation = shelf_item['annotation']
            label = shelf_item['label']

            # dcc = double click command: we can add a different command that goes when double clicked.
            dcc = shelf_item['double-click']
            # menu = submenu for right-click
            menu = shelf_item['menu']

            path = "pipe.tools." + shelf_item['tool']
            function = shelf_item['function']
            class_with_method = function.split(".")
            module = class_with_method[0]
            method = class_with_method[1]

            command_base = "from " + str(path) + " import " + str(
                module) + "; shelf_item = " + str(module) + "(); shelf_item."
            command = command_base + str(method)

            if dcc == 0:
                dcc = command
            else:
                dcc = command_base + str(dcc)

            if menu == 0:
                pm.shelfButton(c=command,
                               ann=annotation,
                               i=icon,
                               l=annotation,
                               iol=label,
                               olb=(0, 0, 0, 0),
                               dcc=dcc)
            elif menu == 1:
                menu_items = shelf_item['menu_items']
                new_menu = build_menu_string(command_base, menu_items)
                mip = []
                for i in range(len(new_menu)):
                    mip.append(i)
                pm.shelfButton(c=command,
                               ann=annotation,
                               i=icon,
                               l=annotation,
                               iol=label,
                               olb=(0, 0, 0, 0),
                               dcc=dcc,
                               mi=new_menu,
                               mip=mip)

        else:
            pm.separator(horizontal=False,
                         style='shelf',
                         enable=True,
                         width=35,
                         height=35,
                         visible=1,
                         enableBackground=0,
                         backgroundColor=(0.2, 0.2, 0.2),
                         highlightColor=(0.321569, 0.521569, 0.65098))

    # Set default preferences
    pm.env.optionVars['generateUVTilePreviewsOnSceneLoad'] = 1

    # shelf loaded correctly
    print("*** Shelf loaded :) ***")
    sys.path.append(os.getcwd())

    #load up this plugin bc rigging used it
    pm.loadPlugin("ngSkinTools2")
import os
import distutils
import pymel.core as pm
from PySide2 import QtWidgets


def onMayaDroppedPythonFile(*args):
    pass

script_dir = pm.internalVar(usd=True)
icon_dir = pm.internalVar(ubd=True)
dl_dir = os.path.dirname(__file__)

distutils.dir_util.copy_tree(os.path.join(dl_dir, 'scripts'), os.path.dirname(script_dir))
distutils.dir_util.copy_tree(os.path.join(dl_dir, 'icons'), os.path.dirname(icon_dir))

shelves = pm.tabLayout(pm.getMelGlobal('string', '$gShelfTopLevel'), query=True, childArray=True)
current = shelves.index(pm.tabLayout(pm.getMelGlobal('string', '$gShelfTopLevel'), query=True, selectTab=True))
itm, accepted = QtWidgets.QInputDialog().getItem(None, 'Shelf Button', 'Which Shelf Do You Wish to Add the Button To?',
                                                 shelves, editable=False, current=current)

if accepted:
    pm.shelfButton(style="iconOnly", parent=itm, image='na_scratch_paper', label='Scratch Paper',
                   command='import na_scratch_paper\nna_scratch_paper.run_maya()')
 def creat_shelf_button(self, image, command, parent):
     pm.shelfButton(annotation='',
                    image="{}/Icon/{}.png".format(self.project_path, image),
                    command=command,
                    parent=parent)
 def _createDeleteTabButton(self, shelfTab=None, *args):
     pm.shelfButton(annotation='Delete this tab.', 
                    image1='delete-icon.xpm', 
                    label='Delete',
                    command=partial(self._deleteShelfTab,shelfTab))
Exemple #38
0
def create_shelf_button(btn_label, shelf, command, icon_path):
    pm.shelfButton(label=btn_label,
                   parent=shelf,
                   command=command,
                   image1=icon_path)