예제 #1
0
    def populate_selection_layout(self):        
        
        pm.setParent(self.widgets['selectionSet_vertical'])
        self.widgets['selectionSet_vertical'].clear()        
        
        treeViewSelected =  pm.treeView (self.widgets["directory_treeView"], q=True, selectItem=True)
        
        if not treeViewSelected:
            return
        
        pm.scrollLayout(cr=True)

        path = os.path.abspath(treeViewSelected[0])
        
        set_paths = []
        for dir in os.listdir(path):
             if dir.find(self.library_objects_suffix[2]) != -1: #.set 
                 set_paths.append(os.path.abspath(os.path.join(path, dir)))        
                
        for set_path in set_paths:
            print "create button"
            set_obj = Set(set_path)
            
            infos = set_obj.get_info()
            label = infos['name'].split('.')[0]

            pm.iconTextButton(style='textOnly',label=label, c=pm.Callback(self.selection_set_button_load, set_obj))
            pm.popupMenu()
            pm.menuItem(label='Save Pose', c=pm.Callback(self.selection_set_button_save, set_obj))        
            pm.menuItem(label='Load Pose', c=pm.Callback(self.selection_set_button_load, set_obj))
 
        self.widgets["selectionSet_vertical"].redistribute()
예제 #2
0
 def _categoryUpdated(self, add=None, rename=None, delete=None):
     _pmCore.setParent(self._uiWidget[_UiWidgetEnum.categoryTabLayout])
     if add:
         # Add a tab in main asset view.
         childLayout = _pmCore.scrollLayout(width=300, height=200, childResizable=True)
         self._uiWidget[add] = _pmCore.gridLayout(numberOfColumns=3, cellHeight = self._iconSize, cellWidth=self._iconSize)
         _pmCore.tabLayout(self._uiWidget[_UiWidgetEnum.categoryTabLayout], tabLabel=((childLayout, add),), edit=True)
         # Add a menu item in category list. From example in Maya doc optionMenuGrp.
         newMenuItem = _pmCore.menuItem(label=add, parent=self._uiWidget[_UiWidgetEnum.categoryCombox]+'|OptionMenu')
         self._uiWidget[_UiWidgetEnum.categoryMenuList].append(newMenuItem)
     if rename:
         tabNameList = _pmCore.tabLayout(self._uiWidget[_UiWidgetEnum.categoryTabLayout], query=True, tabLabel=True)
         childLayoutList = _pmCore.tabLayout(self._uiWidget[_UiWidgetEnum.categoryTabLayout], query=True, childArray=True)
         _pmCore.tabLayout(self._uiWidget[_UiWidgetEnum.categoryTabLayout], edit=True, tabLabel=((childLayoutList[tabNameList.index(rename[0])], rename[1])))
         for item in self._uiWidget[_UiWidgetEnum.categoryMenuList]:
             if _pmCore.menuItem(item, query=True, label=True) != rename[0]:
                 continue
             _pmCore.menuItem(item, edit=True, label=rename[1])
             break
     if delete:
         tabNameList = _pmCore.tabLayout(self._uiWidget[_UiWidgetEnum.categoryTabLayout], query=True, tabLabel=True)
         childLayoutList = _pmCore.tabLayout(self._uiWidget[_UiWidgetEnum.categoryTabLayout], query=True, childArray=True)
         _pmCore.deleteUI(childLayoutList[tabNameList.index(delete)])
         for item in self._uiWidget[_UiWidgetEnum.categoryMenuList]:
             if _pmCore.menuItem(item, query=True, label=True) != delete:
                 continue
             _pmCore.deleteUI(item)
             break
예제 #3
0
def doUpdateScnAOV(type, *args):
    #// first, update string attr in each AOV
    if type == 0:
        updateAOVStrAttr()
    
    # next, update AOV list
    AOVList = []
    sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True)
    for aovName, aovNode in sceneAOVs:
        if( aovName.find('id_') == 0 and aovNode.hasAttr('isID') ):
            AOVList.append( str(aovName) )
    
    enumUIParent = pm.optionMenu( 'enumAOVList', q=True, parent=True )
    
    curr_aov = pm.optionMenu( 'enumAOVList', q=True, value=True )
    if curr_aov == None: return
  
    pm.deleteUI('enumAOVList')
        
    pm.optionMenu( 'enumAOVList', bgc=[0.2, 0.2, 0.2], label="AOVs: ", width=120, parent=enumUIParent )
    for aov in AOVList:
        pm.menuItem( aov )
    
    if( ( len(curr_aov) != 0 ) and ( len( pm.ls(aovs.AOVInterface().getAOVNode(curr_aov)) ) != 0 ) ):
        pm.optionMenu( 'enumAOVList', e=True, value=curr_aov )
        
    #// if curr_aov is not existing...

    return 1
예제 #4
0
파일: test.py 프로젝트: loichuss/maya
    def _updateNameSpaceList(self):
        """update namespace menu item"""
       
        # delete all items
        self._deleteNameSpaceList()
       

       
        # get current namespace
        current = pmc.namespaceInfo(currentNamespace=True)
       
        # get all namespace
        pmc.namespace(set=':')
        listNamespace = pmc.namespaceInfo(listOnlyNamespaces=True, recurse=True)
        pmc.namespace(set=current)
       
       
        if current == ':':
            current = self.rootNamespace
       
        # add root namespace
        listNamespace.append(self.rootNamespace)

        # add menuItem
        i = 1
        for nameSpace in listNamespace:
            if nameSpace in ['UI', 'shared']:
                continue
            pmc.menuItem(label=nameSpace, parent=self.uiMain['namespaceOpM'])
           
            if nameSpace == current:
                self.uiMain['namespaceOpM'].setSelect(i)
            i=i+1
    def test_rowGroupLayout(self):
        self.assertEqual(pm.currentParent(), self.win)
        self.assertEqual(pm.currentMenuParent(), None)
        with pm.textFieldButtonGrp( label='Label', text='Text', buttonLabel='Button' ) as tfbg:
            self.assertEqual(pm.currentParent(), tfbg)
            self.assertEqual(pm.currentMenuParent(), None)
            cmds.button()
            with pm.popupMenu() as m:
                self.assertEqual(pm.currentParent(), tfbg)
                self.assertEqual(pm.currentMenuParent(), m)
                with pm.menuItem(subMenu=1) as sm:
                    self.assertEqual(pm.currentParent(), tfbg)
                    self.assertEqual(pm.currentMenuParent(), sm)
                self.assertEqual(pm.currentParent(), tfbg)
                self.assertEqual(pm.currentMenuParent(), m)
            self.assertEqual(pm.currentParent(), tfbg)
        self.assertEqual(pm.currentParent(), self.win)

        fl = pm.formLayout()
        tfbg2 = pm.textFieldButtonGrp( label='Label', text='Text', buttonLabel='Button' )
        self.assertEqual(pm.currentParent(), fl)
        with pm.columnLayout() as cl:
            cmds.button()
            with pm.popupMenu() as m:
                self.assertEqual(pm.currentParent(), cl)
                self.assertEqual(pm.currentMenuParent(), m)
                with pm.menuItem(subMenu=1) as sm:
                    self.assertEqual(pm.currentParent(), cl)
                    self.assertEqual(pm.currentMenuParent(), sm)
                self.assertEqual(pm.currentParent(), cl)
                self.assertEqual(pm.currentMenuParent(), m)
            self.assertEqual(pm.currentParent(), cl)
        self.assertEqual(pm.currentParent(), fl)
예제 #6
0
def MakeRandomizeOptionsMenu(randomizerController, annotation=None):
    """
    Creates & returns a menu group giving the the randomiser options for a given randomizeController. 
    
    :param randomizerController: RandomiseController instance. 
    :param annotation: toolTip annotation, or None. 
    """
    if(type(randomizerController) != at.RandomizeController):
        raise TypeError("Attempt to make randomizer menu from non-RandomizeController attribute.")
    
    rowLayout = MakeRowLayout(2, rightColumnWidth=__OPTIONS_MENUS_WIDTH__, makeAdjustable=False)
    
    text = MakeText(randomizerController.attributeLabel, annotation)
    
    optionMenu = pm.optionMenu()
    try:
        for i in xrange(sys.maxint):
            pm.menuItem(label=at.RandomizeController.StringForOption(i))
    except Exception:
        pass
    
    optionMenu.changeCommand(lambda *args: randomizerController._setValue(optionMenu.getValue()))
    randomizerController.updateUiCommand = optionMenu.setValue
    randomizerController.uiEnableMethod = rowLayout.setEnable
    if(annotation is not None):
        optionMenu.setAnnotation(annotation)
    elif(randomizerController.annotation is not None):
        optionMenu.setAnnotation(randomizerController.annotation)
    
    SetAsChildLayout(rowLayout)
    
    return rowLayout
예제 #7
0
def aiHyperShadeCreateMenu_BuildMenu():
    """
    Function:   aiHyperShadeCreateMenu_BuildMenu()
    Purpose:    Builds menu items for creating arnold nodes, organized
                into submenus by category.

    Notes:  When this function is invoked, it is inside of the Create menu.
            This function mimics the buildCreateSubmenu() function in 
            hyperShadePanel.mel, and in fact calls that function with a slightly
            different set of arguments than the other Maya node types.  For 
            arnold nodes, the menu items are set up to call back to the
            aiCreateCustomNode() function for node creation.
    """

    # build a submenu for each node category
    #
    for (staticClass, runtimeClass, nodePath, nodeTypes) in getTypeInfo():
        # skip unclassified
        if staticClass == 'rendernode/arnold' or staticClass == 'rendernode/arnold/shader':
            continue
        pm.menuItem(label = nodePath.replace('/', ' '), 
                      tearOff = True, subMenu = True)
        
        # call buildCreateSubMenu() to create the menu entries.  The specified 
        # creation command is aiCreateCustomNode runtimeClassification.  The
        # buildCreateSubMenu will append to that argument list the name of the
        # node type, thereby completing the correct argument list for the 
        # creation routine.
        #
        pm.mel.buildCreateSubMenu(staticClass, '%s %s ""' % (_createNodeCallbackProc,
                                                             runtimeClass) )
        pm.setParent('..', menu=True)
예제 #8
0
 def createLayout(self, *args):
     #creates the layout and attaches the controls to the given field the class has been called in
     self.disabler = pm.optionMenu( l='Auto-detect Proxy', cc=self._disableButton )
     for option in self.o:
         pm.menuItem( label=option )
     self.button = pm.textFieldButtonGrp( adj=1, ad2=1, ad3=1 , cw=[2, self.w/2], w=self.w, label = self.n, text='', buttonLabel=self.b, buttonCommand = self._buttonAction )
     self.textField = pm.textFieldButtonGrp(self.button, e=True, cw=[1, self.w/4])
def multi_MentalRaySettings():
	# Mental Ray Settings
	pm.rowColumnLayout(nc=2)
	pm.text(l='Mental Ray Settings', w=106, al='left', en=False)
	pm.separator(w=marginWidth-106, h=14)
	pm.setParent(multiLight_layout)

	pm.rowColumnLayout(nc=2)
	pm.text(l='', w=142) # GUI SPACER
	multi_MrAreaLight_box = pm.checkBox('hp3dUseShapeCheckbox', l='Use Light Shape', cc=fun.partial(multi_checkboxChange, '.areaLight', 'area & spot', 'hp3dUseShapeCheckbox'))
	pm.setParent(multiLight_layout)

	pm.rowColumnLayout(nc=3)
	pm.text(l='Type', w=140, al='right')
	pm.text(l='', w=3)
	multi_areaType_menu = pm.optionMenu('hp3dAreaTypeMenu', bgc=primary_componentColor, cc=fun.partial(multi_menuChange, '.areaType', 'area & spot', 'hp3dAreaTypeMenu'))
	pm.menuItem(l='Rectangle', da=0)
	pm.menuItem(l='Disc', da=1)
	pm.menuItem(l='Sphere', da=2)
	pm.menuItem(l='Cylinder', da=3)
	pm.menuItem(l='Custom', da=4)
	pm.setParent(multiLight_layout)

	multi_highSamples = pm.intFieldGrp('hp3dHighSamplesField', numberOfFields=1, label='High Samples', v1=8, cc=fun.partial(multi_samplesChange, 'highSamp'))
	multi_highSampLimit = pm.intFieldGrp('hp3dHighSampleLimitField', numberOfFields=1, label='High Sample Limit', v1=1, cc=fun.partial(multi_samplesChange, 'highSampLimit'))
	multi_lowSamples = pm.intFieldGrp('hp3dLowSamplesField', numberOfFields=1, label='Low Samples', v1=1, cc=fun.partial(multi_samplesChange, 'lowSamp'))
	pm.setParent(multiLight_layout)
예제 #10
0
    def __init__(self):
        if pm.window(win, q=True, exists=True ): 
            pm.deleteUI(win)

        with pm.window(win, wh=[300,600], t=title):
            with pm.frameLayout( lv=False, cll=False, mw=1, mh=1):
                with pm.formLayout() as mainForm:

                    # 상단 
                    with pm.tabLayout(tv=False) as top:
                        with pm.frameLayout(lv=False, cll=False, mw=2, mh=2, bv=False):
                            with pm.rowLayout(nc=3, adj=2):
                                pm.image( image = shelf_icon )
                                pm.text(l='  %s'%title, fn='boldLabelFont', align='left')
                                pm.image( image = alfredIcon )
                   
                    #
                    # Contents start ===========================================================
                    # 중단
                    with pm.tabLayout(tv=False, scr=True, childResizable=True) as self.mid:
                        #with pm.columnLayout(adj=True):
                        with pm.frameLayout( lv=False, cll=False, mw=3, mh=3, bv=False):
                            uiContents()

                    #
                    # Contents end =============================================================
                    #
                    
                    # 하단
                    with pm.columnLayout(adj=True) as btm:
                        pm.helpLine()
       
            # 팝업메뉴
            # 왼쪽 마우스 클릭
            pm.popupMenu(button=1, p=top)
            pm.menuItem(l='Add To Shelf',  c=pm.Callback( self.addToShalf ) )

            # 오른쪽 마우스 클릭
            pm.popupMenu(button=3, p=top)
            pm.menuItem(l='Help', en=False )
           
            # 폼조정
            pm.formLayout( mainForm, e=True, 
                attachForm=[
                    (top, 'top', 3), 
                    (top, 'left', 3), 
                    (top, 'right', 3), 

                    (self.mid, 'left', 3), 
                    (self.mid, 'right', 3), 

                    (btm, 'left', 3), 
                    (btm, 'right', 3), 
                    (btm, 'bottom', 3),
                    ], 
                attachControl=[
                    (self.mid, 'top', 3, top), 
                    (self.mid, 'bottom', 0, btm)
                    ],
                )
예제 #11
0
 def __init__( self, label='', options=[], parent='..', cc=None):
     self.custom={}
     if cc!=None: self.optionMenu=pm.optionMenu( l=label, p=parent, cc=cc)
     else: self.optionMenu=pm.optionMenu( l=label, p=parent)
     for i,option in enumerate(options):
         self.custom[i+1]=option
         pm.menuItem(l=option)
def createUI( SWindowTitle, pApplyCallback ):
    
    windowID = 'vcgnWindowID'
    
    # If Window is Already Open, Delete it and Open a New One
    if pm.window( windowID, exists=True ):
        pm.deleteUI( windowID )
        
    # Init Window
    pm.window( windowID, title=SWindowTitle, sizeable=False, resizeToFitChildren=True )
        
    pm.rowColumnLayout( numberOfColumns=3, columnWidth=[ (1, 75), (2, 75), (3,75) ], columnOffset=[ (1,'right', 3) ])
        
    pm.text( label='Min Value:' )
        
    # Minimum Value Field, Default = 0.0, min = 0.0, max = 1.0, invisible slider step = 0.01
    MinValueField = pm.floatField( value=0.0, minValue=0.0, maxValue=1.0, step=0.01, annotation="This is the Minimum Value, It Can't Go below 0.0 or above 1.0" )
    pm.separator( h=10, style='none' )
        
    pm.text( label='Max Value:' )
        
    # Maximum Value Field, Default = 1.0, min = 0.0, max = 1.0, invisible slider step = 0.01
    MaxValueField = pm.floatField( value=1.0, minValue=0.0, maxValue=1.0, step=0.01, annotation="This is the Maximum Value, It Can't Go below 0.0 or above 1.0" )
    pm.separator( h=10, style='none' )
    
    # Formatting
    pm.separator( h=10, style='none' )     
    pm.separator( h=10, style='none' )
    pm.separator( h=10, style='none' )
        
    pm.text( label='Noise Type:' )
    
    # Noise Options - Enabled in 2.0    
    NoiseOption = pm.optionMenu( 'NoiseFunctions', enable=True, annotation="Select Alternate Distributions and Generation Functions Here" )
    pm.menuItem( label='Simple', parent='NoiseFunctions', annotation="A Simple Psuedo Random Noise Function that generates Random Values Between Min and Max" )
    pm.menuItem( label='Perlin', parent='NoiseFunctions', annotation="Try Moving the Object Around for More Variety with Perlin Noise" )
    pm.menuItem( label='3D Weighted', parent='NoiseFunctions', annotation="This Function Uses a Mixed Up Vertex List Randomly Adjust the Appearance of a Psuedo Random Number Generation" )
    pm.menuItem( label='Triangular', parent='NoiseFunctions', annotation="This Function Uses a Psuedo Random Number Generator with a Triangular Distribution" )
    pm.menuItem( label='Gamma', parent='NoiseFunctions', annotation="This Function Uses the Gamma Distribution, Does Not Work Well with Low Min Values, Suggestion Minimum 0.1" )
    pm.separator( h=10, style='none' )
    
    # Formatting
    pm.separator( h=10, style='none' )
    pm.separator( h=10, style='none' )
    pm.separator( h=10, style='none' )
    
    # Buttons 
    pm.separator( h=10, style='none' )   
    pm.button( label='Apply', command=functools.partial(pApplyCallback,
                                                        NoiseOption,
                                                        MaxValueField,
                                                        MinValueField) )
        
    def cancelCallback( *Args ):
        if pm.window( windowID, exists=True ):
            pm.deleteUI( windowID )
        
    pm.button( label='Cancel', command=cancelCallback )
        
    pm.showWindow()       
예제 #13
0
파일: pbUV.py 프로젝트: aaronfang/pbUV
    def __init__(self):
        respresets = [4096, 2048, 1024, 512, 256, 128, 64, 32]
        with pm.frameLayout(l='Options', cll=True, cl=False, bs='out'):
            with pm.columnLayout():
                pm.text('Map Size:')
                pm.separator(st='in', width=160, height=8)
                with pm.rowColumnLayout(nc=3, cw=[20, 60]):
                    pm.text(l='Width:')
                    self.width = pm.intField(v=1024, width=42)
                    with pm.optionMenu():
                        for i in respresets:
                            pm.menuItem(l=i)
                    pm.text(l='Height:')
                    self.height = pm.intField(v=1024, width=42)
                    with pm.optionMenu():
                        for i in respresets:
                            pm.menuItem(l=i)
                pm.button(l='Get Map Size')

                pm.separator(st='in', width=160, height=8)
                with pm.columnLayout():
                    self.compSpace = pm.checkBox(l='Retain Component Spaceing',
                                                 cc=lambda *args: pm.texMoveContext('texMoveContext', e=True,
                                                                                    scr=self.compSpace.getValue()),
                                                 v=pm.texMoveContext('texMoveContext', q=True, scr=True))
                    self.pixelUnits = pm.checkBox(l='Transform In Pixels')
예제 #14
0
 def loadDriven(self, *args): 
     """
      Load object name for driven object in text field
     """
     sel = pm.ls(sl=True, fl=True)
     pm.textFieldButtonGrp(self.drivenField, edit=True, text=sel[0])  
     
     # Clear the menu items so list doesn't grow
     items = pm.optionMenu(self.drivenAttField, q=True, ill=True)
     if(items):
             pm.setParent(self.drivenAttField, menu=True)
             for each in items:
                     pm.deleteUI(each)
     
     # Check if blendshape
     if 'BlendShape' in str(type(sel[0])):  
         bs = sel[0]
     
         temp = pm.aliasAttr(bs, q=1)
         temp.sort()
         targets = []
         for each in temp:
             if each.startswith('weight'): continue
             targets.append(each)
     
         for tgt in targets:
             try:
                 pm.menuItem(parent=self.drivenAttField, label=tgt)
             except Exception, e:
                 print e
                 pm.warning('%s failed to create / connect' % tgt)
예제 #15
0
def add_menu():
    m1, m2 = None, None
    ok = False
    if not "$gMainWindowMenu" in pmc.melGlobals:
        reload(pmc)
    
    menus1 = get_menus()
    if not menus1:
        pmc.mel.eval("buildDeferredMenus();")
        menus1 = get_menus()
    
    for m1 in menus1:
        try:
            if pmc.windows.menu(m1, q=True, label=True) == "General Editors":
                menus2 = pmc.windows.menu(m1, q=True, ia=True)
                if not menus2:
                    pmc.mel.eval('buildObjectEdMenu("%s");' % m1)
                    menus2 = pmc.windows.menu(m1, q=True, ia=True)
                for m2 in menus2:
                    try:
                        if pmc.windows.menuItem(m2, q=True, label=True) == "Script Editor":
                            ok = True
                            break
                    except Exception, error:
                        print error
        except:
            continue
        if ok:
            break
    
    label = "Source Python"
    if m1 and m2:
        pmc.menuItem(label=label, parent=m1, ia=m2, c=NP_source_python_main)
    elif m1:
        pmc.menuItem(label=label, parent=m1, c=NP_source_python_main)
예제 #16
0
파일: crm_ui.py 프로젝트: myCodeTD/pkmel
	def __init__(self, baseUi, parent):
		BaseUi.__init__(self, parent)
		self.uiparent = parent
		self.baseUi = baseUi
		self.tmpJnts = []
		self.attrCtrl = None

		#ui
		try:
			pm.deleteUI(self.rigCol)
		except: pass

		with pm.columnLayout(adj=True, rs=3, parent=self.uiparent) as self.rigCol:
			with pm.rowColumnLayout(nc=2, co=[(1, 'left', 130), (2, 'left', 5)]):
				pm.text(l='Finger Name')
				with pm.optionMenu(w=60) as self.fingerNameMenu:
					pm.menuItem(l='index')
					pm.menuItem(l='middle')
					pm.menuItem(l='ring')
					pm.menuItem(l='pinky')
					pm.menuItem(l='thumb')
			with pm.rowColumnLayout(nc=3, co=[(1, 'left', 30), (2, 'left', 5), (3, 'left', 5)]):
				pm.text(l='attrCtrl')
				self.attrCtrlTxtFld = pm.textField(w=230, ed=False)
				self.loadAttrCtrlButt = pm.button(l='<<', c=pm.Callback(self.loadAttrCtrl))
				pm.text(l='tmpJnts')
				self.tmpJntsTxtFld = pm.textField(w=230, ed=False)
				self.loadTmpJntButt = pm.button(l='<<', c=pm.Callback(self.loadTmpJnts))

		self.baseUi.clearElemSideTxtFld()
예제 #17
0
def main(parent):
    ''' main function to create custom menu
    
        Arguments:
            parent : root menu item for parenting.
    '''
    logger.debug("Function Called ( %s )"%inspect.stack()[0][3])
     
    pm.menuItem(parent=parent, label="Facial Control Creator", command=facial_control_creator_callback)
예제 #18
0
def main(parent):
    ''' main function to create custom menu
    
        Arguments:
            parent : root menu item for parenting.
    '''
    logger.debug("Function Called ( %s )"%inspect.stack()[0][3])
     
    pm.menuItem(parent=parent, label="Animation GUI", command=animationGui_callback)
예제 #19
0
    def create_menu(self, *args):
        """
        Render the entire Shotgun menu.
        In order to have commands enable/disable themselves based on the enable_callback, 
        re-create the menu items every time.
        """
        self._menu_handle.deleteAllItems()
        
        # now add the context item on top of the main menu
        self._context_menu = self._add_context_menu()
        pm.menuItem(divider=True, parent=self._menu_handle)


        # now enumerate all items and create menu objects for them
        menu_items = []
        for (cmd_name, cmd_details) in self._engine.commands.items():
             menu_items.append( AppCommand(cmd_name, cmd_details) )

        # sort list of commands in name order
        menu_items.sort(key=lambda x: x.name) 

        # now add favourites
        for fav in self._engine.get_setting("menu_favourites"):
            app_instance_name = fav["app_instance"]
            menu_name = fav["name"]
            # scan through all menu items
            for cmd in menu_items:                 
                 if cmd.get_app_instance_name() == app_instance_name and cmd.name == menu_name:
                     # found our match!
                     cmd.add_command_to_menu(self._menu_handle)
                     # mark as a favourite item
                     cmd.favourite = True

        pm.menuItem(divider=True, parent=self._menu_handle)
        
        # now go through all of the menu items.
        # separate them out into various sections
        commands_by_app = {}
        
        for cmd in menu_items:

            if cmd.get_type() == "context_menu":
                # context menu!
                cmd.add_command_to_menu(self._context_menu)             
                
            else:
                # normal menu
                app_name = cmd.get_app_name()
                if app_name is None:
                    # un-parented app
                    app_name = "Other Items" 
                if not app_name in commands_by_app:
                    commands_by_app[app_name] = []
                commands_by_app[app_name].append(cmd)
        
        # now add all apps to main menu
        self._add_app_menu(commands_by_app)
예제 #20
0
def mantraMainMenu():
    log.debug("Creating mantra main menu")
    menuName = "Mantra"
    if pm.menu(menuName, query=True, exists=True):
        pm.deleteUI(menuName)
    gMainWindow = pm.mel.eval('$tmpVar=$gMainWindow')
    mantraMenu = pm.menu(menuName, label=menuName, parent=gMainWindow, tearOff=True)
    pm.menuItem(label='Create Geo Standin', command=pm.Callback(menuCallback, "GeoStandin"))
    pm.setParent("..", menu=True)
예제 #21
0
def create_tank_disabled_menu(menu_name):
    """
    Render a special "shotgun is disabled menu"
    """
    if pm.menu("ShotgunMenu", exists=True):
        pm.deleteUI("ShotgunMenu")

    sg_menu = pm.menu("ShotgunMenuDisabled", label=menu_name, parent=pm.melGlobals["gMainWindow"])
    pm.menuItem(label="Sgtk is disabled.", parent=sg_menu, 
                command=lambda arg: tank_disabled_message())
예제 #22
0
    def populateMelNameMenu(self):
        """called to populate the popup menu for choosing the mel equivalent to an api method"""
        self.melNameOptMenu.deleteAllItems()

        pm.menuItem(parent=self.melNameOptMenu, label='[None]', command=pm.Callback( MethodRow.melNameChangedCB, self, '[None]' ))
        # need to add a listForNone to this in windows
        items = self.parent.parent.unassignedMelMethodLister.getAllItems()
        if items:
            for method in items:
                pm.menuItem(parent=self.melNameOptMenu, label=method, command=pm.Callback( MethodRow.melNameChangedCB, self, str(method) ))
예제 #23
0
def lcCameraToolsUI(dockable=False, *args, **kwargs):
  ''' '''
  ci = 0 #color index iterator
  windowName = 'lcCameraTools'
  shelfCommand = 'import lct.src.lcCameraTools.lcCameraTools as lcCam\nreload(lcCam)\nlcCam.lcCameraToolsUI()'
  icon = basePath+'lcCameraTools.png'
  winWidth  = 204
  winHeight = 209
  
  mainWindow = lcWindow(windowName=windowName, width=winWidth, height=winHeight, icon=icon, shelfCommand=shelfCommand, annotation=annotation, dockable=dockable, menuBar=True)
  mainWindow.create()
  pm.menu(l='Options', helpMenu=True)
  pm.menuItem(l='Reset Gradient Colors', command=lambda *args: cam_set_default_colors() )

  #
  pm.columnLayout(prefix+'_columLayout_main')
  
  #
  pm.rowColumnLayout(nc=2, cw=([1,50], [2,150]) )
  pm.text(l='Edit:', al='right')
  cameraListDropdown = pm.optionMenu(prefix+'_optionMenu_camera_list', bgc=colorWheel.getColorRGB(ci), w=150, h=25 )
  ci+=1
  cameraListDropdown.changeCommand(lambda *args: cam_get_cam_attrs(cameraListDropdown) )
  pm.setParent(prefix+'_columLayout_main')
  
  #  
  pm.rowColumnLayout(nc=2, cw=([1,125], [2,75]) )
  pm.text(l='Focal Length:', al='right')
  pm.floatField(prefix+'_floatField_focal_length', min=0.0, v=0.0, pre=1, w=75, changeCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown), receiveFocusCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown) )
  pm.text(l='Near Clip Plane:', al='right')
  pm.floatField(prefix+'_floatField_near_clip_plane', min=0.0, v=0.0, pre=4, w=75, changeCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown), receiveFocusCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown) )
  pm.text(l='Far Clip Plane:', al='right')
  pm.floatField(prefix+'_floatField_far_clip_plane', min=0.0, v=0.0, pre=0, w=75, changeCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown), receiveFocusCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown) )
  pm.text(l='Overscan:', al='right')
  pm.floatField(prefix+'_floatField_overscan', min=0.0, v=0.0, pre=3, w=75, changeCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown), receiveFocusCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown) )
  pm.text(l='Background Color:', al='right')
  pm.colorSliderGrp(prefix+'_colorSliderGrp_background_color', cw1=50, rgb=(0.0,0.0,0.0), changeCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown) )
  pm.text(l='Gradient Top:', al='right')
  pm.colorSliderGrp(prefix+'_colorSliderGrp_gradient_top', cw1=50, rgb=(0.54,0.62,0.70), changeCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown) )
  pm.text(l='Gradient Bottom:', al='right')
  pm.colorSliderGrp(prefix+'_colorSliderGrp_gradient_bottom', cw1=50, rgb=(0.1,0.1,0.1), changeCommand=lambda *args: cam_set_cam_attrs(cameraListDropdown) )
  pm.setParent(prefix+'_columLayout_main')
  
  #
  pm.rowColumnLayout(nc=2, cw=([1,175], [2,25]) )
  pm.button(prefix+'_button_toggle_bkgd', l='Toggle Background', bgc=colorWheel.getColorRGB(ci), w=200, h=25, annotation='Toggle between flat color and gradient background', command=lambda *args: camera.toggleBackground() )
  ci+=1
  pm.iconTextButton(w=25, h=25, style='iconOnly', image=iconBasePath+'addToShelf.png', highlightImage=iconBasePath+'addToShelf_over.png', annotation='Add to Shelf', command=lambda *args: shelf.makeShelfButton('Toggle Camera Background', 'from lct.src.core.lcUtility import Camera as camera\ncamera.toggleBackground()', iconBasePath+'toggleBackground.png', "Toggle Camera's Viewport Background") )

  #
  mainWindow.show()
  
  cam_populate_camera_list(cameraListDropdown)  
  cam_get_cam_attrs(cameraListDropdown)
예제 #24
0
 def set_recents_ui(self, *args):
     tmp = pmc.promptBox("Recents max length", "Enter the max value", "Ok", "Cancel")
     if tmp:
         try:
             self.max_recents = int(tmp)
             self.update_recents()
             self.update_recents_menu()
             pmc.menuItem(self.max_recents_ui, e=True, label="Set length (%s)" % self.max_recents)
             self.save_options()
         except:
             pmc.warning("Please enter a integer value, i.e.: 5")
예제 #25
0
def ui():
    if pm.window("Depth tool", q=True, exists=True):
        pm.deleteUI("Depth tool")
    with pm.window("Depth tool", menuBar=True, s=False):
        pm.menu(l="help")
        pm.menuItem(l="document", c=pm.Callback(os.system, "D:/Users/blood/Desktop/eyeTest_01.mov"))
        pm.menuItem(l="tutorial", c=pm.Callback(pm.launch, web="https://www.youtube.com/watch?v=-JwXfnrX1wM"))
        with pm.columnLayout(adj=True):
            with pm.rowLayout(nc=2):
                pm.button(l="Create" + "\n" + "Depth", w=64, h=64, bgc=(0.2, 0.2, 0.2), c=creatAll)
                pm.button(l="Adjust" + "\n" + "Min&&Max", w=64, h=64, bgc=(0.8, 0.8, 0.8), c=adjustAll)
예제 #26
0
    def createImageFormatControls(self):
        self.createGlobalsNode()
        self.createImageFormats()
        if pm.optionMenuGrp("openMayaImageFormats", q=True, exists=True):
            pm.deleteUI("openMayaImageFormats")
        self.imageFormatCtrl = pm.optionMenuGrp("openMayaImageFormats", label="Image Formats", cc=pm.Callback(self.imageFormatCallback))

        for pr in self.imageFormats:
            log.debug("adding image format: " + pr)
            pm.menuItem(pr)
        return self.imageFormatCtrl
예제 #27
0
 def __init__(self):
     if pm.window(self.uiID, exists=True):
         pm.deleteUI(self.uiID)
     win = pm.window(self.uiID, title=self.title, menuBar=True)
     with win:
         pm.menu( label='Create', tearOff=True )
         for type in deformerTypes:
             pm.menuItem( label=type, c=pm.Callback( self.initPlugin, type) )
         self._parentLayout = pm.columnLayout( adj=True )
         with self._parentLayout:
             self.createUISet()
예제 #28
0
 def __init__(self):
     if pm.window(self.uiID, exists=True):
         pm.deleteUI(self.uiID)
     win = pm.window(self.uiID, title=self.title, menuBar=True)
     with win:
         pm.menu( label='CageDeformer', tearOff=True )
         pm.menuItem( label="CageDeformer", c=pm.Callback( self.initPlugin, "cage") )
         pm.menuItem( label="CageDeformerARAP", c=pm.Callback( self.initPlugin, "cageARAP") )
         self._parentLayout = pm.columnLayout( adj=True )
         with self._parentLayout:
             self.createUISet()
예제 #29
0
    def decorator(func):
        pm.menuItem(parent=parent,
                         label=label,
                         command=lambda arg: func())
        if optionBox:
            pm.menuItem(parent=parent,
                             label="Opt ",
                             optionBox=True,
                             command=lambda arg: func(optionBox=True),
                             imageOverlayLabel=overlayLabel)

        return func
def overrideFileMenuCommands():
    filemenu = pc.mel.eval("$res = $gMainFileMenu;")
    pc.mel.eval("buildFileMenu();")
    pc.mel.eval("checkMainFileMenu();")
    pc.menuItem('%s|newProjectScene'%(filemenu),
                e=True,
                command='sceneManager_mayaLauncher.newSceneProjectOverride()'
               )
    pc.menuItem('%s|openProject'%(filemenu),
                e=True,
                command='sceneManager_mayaLauncher.openProjectOverride()'
               )
예제 #31
0
    def isRadialPositionOccupied(self, radialPosition: str):
        """
        Return true if a radial position is currently occupied by an existing menu item.
        """
        if not radialPosition:
            return False

        menu_items = pm.menu(self.menu, q=True, itemArray=True)
        for menu_item in menu_items:
            if pm.menuItem(menu_item, q=True, radialPosition=True) == radialPosition:
                return True
        return False
예제 #32
0
    def find_menu_section_around_index(cls, menu_items, idx):
        """
        Find the section containing the menu_items[idx], and return its start and end
        index.
        """
        start_idx = idx
        # Search upwards for the start of the section.
        while start_idx > 0:
            if pm.menuItem(menu_items[start_idx], q=True, divider=True):
                start_idx += 1
                break

            start_idx -= 1

        for end_idx in range(start_idx + 1, len(menu_items)):
            if not pm.menuItem(menu_items[end_idx], q=True, divider=True):
                continue

            return menu_items[start_idx:end_idx]
        else:
            return menu_items[start_idx:]
예제 #33
0
파일: menu.py 프로젝트: rBrenick/b-tools
def setup_menu_item(item_name, item_data):
    item_is_divider = item_data == "-----"
    if item_is_divider:
        pm.menuItem(label=item_name, divider=True)
        return

    item_is_sub_menu = item_data.get("sub_menu", "False") == "True"
    if item_is_sub_menu:
        pm.menuItem(subMenu=True, label=item_name)
        item_data.pop("sub_menu")
        for item_name, item_data in item_data.items():
            setup_menu_item(item_name, item_data)  # recursive
        pm.setParent('..', menu=True)
        return

    item_module = item_data.get("module")
    item_command = item_data.get("command")
    item_is_option_box = item_data.get("option_box", "False") == "True"
    item_language = item_data.get("language")

    menu_item_kwargs = dict()
    menu_item_kwargs["command"] = create_command(item_module, item_command)
    menu_item_kwargs["optionBox"] = item_is_option_box

    pm.menuItem(item_name, **menu_item_kwargs)
예제 #34
0
	def create(self):
		try:
			pm.deleteUI(self.WINDOW_NAME,window=True)
		except:pass
		
		with pm.window(self.WINDOW_NAME) as res_window:
			with pm.columnLayout(adjustableColumn=True):
				with pm.horizontalLayout():
					pm.text(label='Resolution')
					with pm.optionMenu() as self.res_menu:
						pm.menuItem(l='Low')
						pm.menuItem(l='Med')
						pm.menuItem(l='Hig')
					set_res_btn = pm.button(
						label:'Set LOD',
						command=pm.Callback(self.on_set_res_btn)
					)
				pm.separator(style='in',height=4)
				with pm.horizontalLayout() as h1:
					pm.text(label = 'Low')
					select_low_btn=pm.button(
						label='Select All',
						command=pm.Callback(
							self.on_select_btn,
							'Low'
						)
					)
예제 #35
0
 def createMenus(self):
     pm.popupMenu(parent=self.widgetName)
     pm.menuItem(label='add folder', c=self.addFolderCallBack)
     pm.menuItem(label='add multiple folders', c=self.addMultipleFoldersCallback)
     pm.menuItem(label='remove folder', c=self.removeFolderCallBack)
     if self.projectName:
         self.getFolderTree()
예제 #36
0
    def updateEnvLightControl(self):
        if "envLight" in self._uis:
            logger.debug("Updating env lights menu")

            uiName = self._uis["envLight"]

            # Return if the menu does not exist yet.
            if not pm.optionMenu(uiName, exists=True):
                return

            # Remove the callback.
            pm.optionMenu(uiName, edit=True, changeCommand="")

            # Delete the menu items.
            items = pm.optionMenu(uiName, query=True, itemListLong=True)
            for item in items:
                pm.deleteUI(item)

            connections = mc.listConnections("appleseedRenderGlobals.envLight")

            # Rebuild the menu.
            pm.menuItem(parent=uiName, label="<none>")
            for envLight in g_environmentLightsList:
                pm.menuItem(parent=uiName, label=envLight)

            # Update the currently selected item.
            if connections:
                node = connections[0]
                if mc.nodeType(node) == "transform":
                    shapes = mc.listRelatives(node, shapes=True)
                    assert shapes
                    node = shapes[0]
                    pm.optionMenu(uiName, edit=True, value=node)
            else:
                pm.optionMenu(uiName, edit=True, value="<none>")

            # Restore the callback.
            pm.optionMenu(uiName,
                          edit=True,
                          changeCommand=self.__environmentLightSelected)
예제 #37
0
    def _buildMarkingMenu(self, menu, parent):

        ## Radial positioned
        pm.menuItem(p=menu,
                    l="FK / IK",
                    rp="SW",
                    c="print 'FK to IK Switching'")
        pm.menuItem(p=menu,
                    l="FK to IK",
                    rp="SE",
                    c="print 'IK to FK Snaping'")
        # pm.menuItem(p=menu, l="North East Button", rp="NE", c="pm.circle()")

        # subMenu = pm.menuItem(p=menu, l="North Sub Menu", rp="N", subMenu=1)
        # pm.menuItem(p=subMenu, l="North Sub Menu Item 1")
        # pm.menuItem(p=subMenu, l="North Sub Menu Item 2")

        # pm.menuItem(p=menu, l="South", rp="S", c="print 'South'")
        # pm.menuItem(p=menu, ob=1, c="print 'South with Options'")

        ## List
        # pm.menuItem(p=menu, l="First menu item")
        # pm.menuItem(p=menu, l="Second menu item")
        # pm.menuItem(p=menu, l="Third menu item")
        # pm.menuItem(p=menu, l="Create poly cube", c="pm.polyCube()")

        pm.menuItem(p=menu, l="Rebuild Marking Menu", c=rebuildMarkingMenu)
예제 #38
0
    def menus(self):

        # popUpMenu
        self.popUp = pm.popupMenu(parent=self.scrollField)
        #opening the file
        self.commentFile = open(self.fileName, 'r')
        # reading
        self.comments = self.commentFile.readlines()
        # closing
        self.commentFile.close()

        # the label is the first line
        # the actual comment is after the label
        # so the pattern is label, comment, label, comment, label, comment
        label = 0
        comment = 1
        pm.menuItem(label='Clear', command=pm.Callback(self.clear))
        pm.menuItem(label='Custom', command=pm.Callback(self.custom))
        while comment < len(self.comments):
            # menuItems for the popUpMenu
            write = self.comments[comment]
            pm.menuItem(label=self.comments[label],
                        command=pm.Callback(self.insertText, write))
            label += 2
            comment += 2
예제 #39
0
파일: menu.py 프로젝트: mgear-dev/mgear4
def install():
    """Install Simple Rig submenu
    """
    pm.setParent(mgear.menu_id, menu=True)
    pm.menuItem(divider=True)
    pm.menuItem(label="Simple Rig Tool", command=str_open_simple_rig)
    pm.menuItem(divider=True)
예제 #40
0
 def __add_pose_actions(cls, root_menu, selection):
     selected_control = luna_rig.Control(selection[-1])
     pm.menuItem(p=root_menu,
                 l="Mirror pose (Behaviour)",
                 rp="SW",
                 c=lambda *args: [
                     luna_rig.Control(trs).mirror_pose(behavior=True,
                                                       direction="source")
                     for trs in selection
                     if luna_rig.Control.is_control(trs)
                 ])
     pm.menuItem(p=root_menu,
                 l="Mirror pose (No behaviour)",
                 rp="S",
                 c=lambda *args: [
                     luna_rig.Control(trs).mirror_pose(behavior=False,
                                                       direction="source")
                     for trs in selection
                     if luna_rig.Control.is_control(trs)
                 ])
     pm.menuItem(p=root_menu,
                 l="Asset bind pose",
                 rp="N",
                 c=lambda *args: selected_control.character.to_bind_pose(),
                 i=fileFn.get_icon_path("bindpose.png"))
     pm.menuItem(p=root_menu,
                 l="Component bind pose",
                 rp="NE",
                 c=lambda *args: selected_control.connected_component.
                 to_bind_pose(),
                 i=fileFn.get_icon_path("bodyPart.png"))
     pm.menuItem(p=root_menu,
                 l="Control bind pose",
                 rp="E",
                 c=lambda *args: [
                     luna_rig.Control(trs).to_bind_pose()
                     for trs in selection
                     if luna_rig.Control.is_control(trs)
                 ],
                 i=fileFn.get_icon_path("control.png"))
예제 #41
0
        def replace(self, plug):
            plug = pm.Attribute(plug)
            pm.connectControl(self._coordsys.name(), plug, index=2)
            
            # populate the popup menu with coordinate systems
            self._popupMenu.deleteAllItems()
            
            with self._popupMenu:
                objects = []
                
                # include the default, if any
                if self.attr.default:
                    objects.append(self.attr.default)
                
                # add 3delight coordinate systems
                objects.extend(pm.ls(type="delightCoordinateSystem"))
                
                # TODO: add maya cameras
                
                for obj in objects:
                    pm.menuItem(label=str(obj), command=lambda arg, plug=plug, coordsys=obj: plug.set(coordsys))

                if objects:
                    pm.menuItem(divider=True)

                pm.menuItem(label="Create New Coordinate System", boldFont=True,
                            command=lambda arg, plug=plug: plug.set(self._createCoordsys()))
예제 #42
0
 def __add_component_actions(cls, root_menu, selected_control):
     if not selected_control.connected_component:
         return
     pm.menuItem(p=root_menu,
                 l=str(selected_control.connected_component),
                 en=0)
     # Space switching
     if selected_control.spaces:
         spaces_menu = pm.subMenuItem(p=root_menu, l="Spaces")
         for space_name in selected_control.spaces_dict.keys():
             pm.menuItem(p=spaces_menu,
                         l=space_name,
                         c=lambda triggered=True, name=space_name, *args:
                         selected_control.switch_space(
                             selected_control.spaces_dict.get(name)))
     # Actions callbacks
     if hasattr(selected_control.connected_component, "actions_dict"):
         for label, data_dict in selected_control.connected_component.actions_dict.items(
         ):
             pm.menuItem(
                 p=root_menu,
                 l=label,
                 c=lambda *args: data_dict.get("callback", cls.__null_cmd)
                 (),
                 i=fileFn.get_icon_path(data_dict.get("icon")))
예제 #43
0
    def _add_context_menu(self):
        """
        Adds a context menu which displays the current context
        """

        ctx = self._engine.context
        ctx_name = str(ctx)

        # create the menu object
        # the label expects a unicode object so we cast it to support when the context may
        # contain info with non-ascii characters
        ctx_menu = pm.subMenuItem(label=ctx_name.decode("utf-8"),
                                  parent=self._menu_handle)

        # link to UI
        pm.menuItem(label="Jump to Shotgun",
                    parent=ctx_menu,
                    command=Callback(self._jump_to_sg))

        # Add the menu item only when there are some file system locations.
        if ctx.filesystem_locations:
            pm.menuItem(label="Jump to File System",
                        parent=ctx_menu,
                        command=Callback(self._jump_to_fs))

        # divider (apps may register entries below this divider)
        pm.menuItem(divider=True, parent=ctx_menu)

        return ctx_menu
예제 #44
0
 def _populateUI(self):
     '''run once to populate ui objects after their initial creation'''
     
     #cameras list
     self.widgets['cameraList'].removeAll()
     for cam in self.cameras:
         self.widgets['cameraList'].append(cam.name())
         if cam.renderable.get():
             self.widgets['cameraList'].setSelectItem(cam.name())
     
     #pools list        
     if self.pools:
         for pool in sorted(self.pools):
             pm.menuItem(label = pool, parent = (self.widgets['pool'] + '|OptionMenu'))
     
     #users list         
     if self.userPass:
         for user in sorted(self.userPass.keys()):
             pm.menuItem(label = user, parent = (self.widgets['user'] + '|OptionMenu'))
             
         compUser = os.getenv('USER') or os.getenv('USERNAME') #returns None if it does not exist
         if compUser in self.userPass.keys():
             self.widgets['user'].setValue(compUser)
     
     #renderers list         
     if self.renderers:
         for ren in sorted(self.renderers.keys()):
             pm.menuItem(label = ren, parent = (self.widgets['renderer'] + '|OptionMenu'))
         
     #layers list
     self.updateLayers()
예제 #45
0
파일: mimic_ui.py 프로젝트: yazici/Mimic
def _build_add_robot_frame(parent_layout):
    # Create frame layout with one column
    add_robot_frame = pm.frameLayout(label="Add Robot", collapsable=True)
    add_robot_col = pm.columnLayout(adj=True, columnAttach=('both', 5))
    pm.separator(height=5, style='none')

    # Create list of robots
    pm.rowLayout(numberOfColumns=2,
                 adjustableColumn=1,
                 columnAttach=(1, 'left', 3),
                 columnWidth=[(1, 158), (2, 45)],
                 height=20)

    pm.optionMenu('robotImportList')

    rigs = general_utils.get_rigs_dict()
    rig_names = general_utils.get_rigs_names(rigs)
    for rig_name in rig_names:
        pm.menuItem(label=rig_name)

    # Get required rigs directories
    dir_mimic = general_utils.get_mimic_dir()
    dir_rigs = dir_mimic + '/rigs'
    add_robot_command_string = \
        'import mimic_utils; reload(mimic_utils); ' \
        'mimic_utils.import_robot("{}"); ' \
        'mimic_utils.add_mimic_script_node(); ' \
        'mimic_utils.add_hud_script_node()' \
            .format(dir_rigs)

    pm.button(label=' Add ',
              command=add_robot_command_string,
              width=45,
              height=20,
              annotation='Imports selected robot into the scene')

    pm.setParent(add_robot_frame)

    pm.separator(style='none')
    pm.setParent(parent_layout)
예제 #46
0
파일: plebes.py 프로젝트: mgear-dev/shifter
 def populate_template_menu(self, template_menu):
     """Populate the template menu from PLEBE_TEMPLATES_DIR environment
     """
     template_paths = []
     if os.getenv('PLEBE_TEMPLATES_DIR'):
         template_paths = os.getenv('PLEBE_TEMPLATES_DIR').split(':')
     template_paths.append(
         os.path.join(os.path.dirname(os.path.realpath(__file__)),
                      'plebes_templates'))
     for template_path in template_paths:
         template_pattern = os.path.join(template_path, '*.json')
         for filename in sorted(glob(template_pattern)):
             template_name = os.path.basename(filename).\
                 replace('.json', '').replace('_', ' ').title()
             self.template_menu_entries[template_name] = filename
             pm.menuItem(
                 'templateMenuItem_{name}'.format(name=template_name),
                 label=template_name,
                 parent=template_menu,
                 command=pm.Callback(self.set_template, filename))
     self.set_template(
         self.template_menu_entries.get(template_menu.getValue()))
예제 #47
0
def demo1_createmenu():
    import mayautils
    menu = pmc.menu('DemoMenu', parent=mayautils.get_main_window_name())

    def callback(_):
        print 'Hello, reader!'

    menuitem = pmc.menuItem(parent=menu, label='Greet', command=callback)

    print repr(menuitem)
    # ui.SubMenuItem('MayaWindow|DemoMenu|menuItem254')

    return menuitem
예제 #48
0
    def __init__(self, name, label, update_func, parent_menu=None):
        self.is_top_level_menu = parent_menu is None
        self.update_func = update_func

        if self.is_top_level_menu:
            pm.setParent(gMainWindow)
            self.menu_item = name
            if not pm.menu(name, q=True, exists=True):
                pm.menu(name, tearOff=True)
            pm.menu(name, e=True, label=label)
            pm.menu(name, e=True, postMenuCommand=self.update_menu)
        else:
            pm.setParent(parent_menu, menu=True)
            self.menu_item = pm.menuItem(name, label=label, subMenu=True, tearOff=True)
            pm.menuItem(self.menu_item, e=True, postMenuCommand=self.update_menu)
            pm.setParent("..", menu=True)

        # Set a callback to populate the menu when it's opened.
        if self.is_top_level_menu:
            pm.menu(self.menu_item, e=True, postMenuCommand=self.update_menu)
        else:
            pm.menuItem(self.menu_item, e=True, postMenuCommand=self.update_menu)
def iscWindow():
    if pm.window('iscWin', exists=True):
        pm.deleteUI('iscWin', window=True)
    shaderlist = {
        'Blinn': 'isc.InstantBlinn(path)',
        'Lambert': 'isc.InstantLambert(path)',
        'Phong': 'isc.InstantPhong(path)',
        'Arnold aiStandardSurface': 'isc.InstantaiStandardSurface(path)'
    }
    iscWin = pm.window('iscWin',
                       title='Charles Kinters instant shader',
                       rtf=True,
                       h=256)
    menuBar = pm.menuBarLayout(w=100)
    contactMenu = pm.menu(label='Help')
    contactLink = pm.menuItem(
        label='Website: http://charles.kinters.net',
        command=
        'pm.launch(web="http://charles.kinters.net/sample-page/contact-me/")')
    iscWinlayout = pm.rowColumnLayout('iscWinlayout')
    iscWintitle = pm.text(
        label='Please select the type of Instant Shader you wish to create.',
        align='left')

    iscMenu = pm.optionMenu('iscMenu', label='Shader Type?')
    skip = pm.menuItem(label='Please Select Shader')
    for option in shaderlist.keys():
        pm.menuItem(label=option)
    iscPath = pm.folderButtonGrp(label='Path to texture folder:',
                                 cl3=('left', 'left', 'left'))
    btnLayout = pm.rowColumnLayout('butns', nc=2, p='iscWinlayout')
    SubmitButton = pm.button(label='Create',
                             c=Callback(CreateShader, iscMenu, shaderlist,
                                        iscPath),
                             p='butns')
    close = pm.button(label='Close',
                      command=('pm.deleteUI(\"' + iscWin + '\", window=True)'),
                      p='butns')
    pm.showWindow(iscWin)
예제 #50
0
파일: syShaders.py 프로젝트: jonike/sytoons
 def customCreateFlt(self, attr):
     # print "creating %s" % attr
     pname = attr.split('.')[-1]
     ptype = self.params[pname].ptype
     plabel = self.params[pname].label
     pann = self.params[pname].annotation
     presets = self.params[pname].presets
     precision = self.params[pname].precision
     controlName = pname + 'Ctrl'
     l = plabel
     if presets is not None:
         l += ' <span>&#8801;</span>' # fix unicode problem in Windows using html
     pm.attrFieldSliderGrp(controlName, attribute=attr, label=l, annotation=pann, precision=precision)
     if presets is not None:
         # pm.attrFieldSliderGrp(controlName, edit=True)
         # pm.popupMenu()
         # for k in sorted(presets, key=presets.get):
         #     pm.menuItem(label=k, command=pm.Callback(setPresetFlt, controlName, presets[k]))
         attrChildren = pm.layout(controlName, query=True, childArray=True)
         pm.popupMenu(button=1, parent=attrChildren[0])
         for k in sorted(presets, key=presets.get):
             pm.menuItem(label=k, command=pm.Callback(setPresetFlt, controlName, presets[k]))
예제 #51
0
    def customCreateRgb(self, attr):
        pname = attr.split('.')[-1]
        ptype = self.params[pname].ptype
        plabel = self.params[pname].label
        pann = self.params[pname].annotation
        presets = self.params[pname].presets
        controlName = pname + 'Ctrl'

        l = plabel
        if presets is not None:
            l = unicode(plabel) + u' \u1392'
        pm.attrColorSliderGrp(controlName,
                              attribute=attr,
                              label=l,
                              annotation=pann)
        if presets is not None:
            pm.attrColorSliderGrp(controlName, edit=True)
            pm.popupMenu()
            for k in sorted(presets):
                pm.menuItem(label=k,
                            command=pm.Callback(setPresetRgb, controlName,
                                                presets[k]))
예제 #52
0
    def _get_sorted_insertion_point(cls, name, subMenu, parent):
        # Get the label and submenu flag for the menu items that will be label's siblings.
        class Item(object):
            def __init__(self, label, submenu):
                self.label = label
                self.submenu = submenu

            def __cmp__(self, rhs):
                if self.submenu != rhs.submenu:
                    # self.submenu true comes before self.submenu false.
                    return cmp(not self.submenu, not rhs.submenu)
                if self.label != rhs.label:
                    return cmp(self.label, rhs.label)
                return 0

            def __lt__(self, rhs):
                if self.submenu != rhs.submenu:
                    # self.submenu true comes before self.submenu false.
                    return (not self.submenu) < (not rhs.submenu)
                if self.label != rhs.label:
                    return self.label < rhs.label
                return 0

        submenu_items = pm.menu(parent, q=True, ia=True)
        sibling_labels = []
        for item in submenu_items:
            # Ignore options boxes.
            if pm.menuItem(item, q=True, optionBox=True):
                continue

            label = Item(item, pm.menuItem(item, q=True, subMenu=True))
            sibling_labels.append(label)

        item = Item(name, subMenu)
        insertion_point = bisect.bisect_left(sibling_labels, item)
        if insertion_point == 0:
            return None
        else:
            return sibling_labels[insertion_point - 1].label
예제 #53
0
    def add_submenu(self, submenu_name, parent=None):
        """
        Add sub menu container
        :param submenu_name: Label for Sub_menuItem (String)
        :param parent: (String)
        :return:
        """
        if parent is None:
            parent = self.lib_menu.name()

        self.item[submenu_name] = pm.menuItem(submenu_name, p=parent, subMenu=True, tearOff=True)
        ret_parent = self.item[submenu_name]
        return ret_parent.rpartition('|')[-1]
예제 #54
0
    def find_item_with_command(cls, menu_items, command, divider=False, return_last_item_by_default=True):
        """
        Find an item with the given command, and return its index.
        
        If it's not found, return the last element in the menu if return_last_item_by_default
        is true, otherwise return None.

        This is more reliable than find_item_by_name, since it's not affected by localization.
        """
        for idx, item in enumerate(menu_items):
            if divider and not pm.menuItem(item, q=True, divider=True):
                continue

            section = pm.menuItem(item, q=True, c=True)
            if section == command:
                return idx

        log.warning('Couldn\'t find the menu item with command "%s"' % command)
        if return_last_item_by_default:
            return len(menu_items)-1
        else:
            return None
예제 #55
0
    def _makeArgRow(self, methodIndex, type, argName, direction, annotation=''):
        COL1_WIDTH = 260
        COL2_WIDTH = 120
        pm.rowLayout( nc=4, cw4=[COL1_WIDTH,COL2_WIDTH, 70, 150], **self.layout )

        label = str(type)

        pm.text( l=label, ann=annotation )
        pm.text( l=argName, ann=annotation )

        if direction == 'return':
            pm.text( l='(result)' )
        else:
            direction_om = pm.optionMenu(l='', w=60, ann=annotation, cc=pm.CallbackWithArgs( MethodRow.setDirection, self, methodIndex, argName ) )
            for unit in ['in', 'out']:
                pm.menuItem(l=unit)
            direction_om.setValue(direction)

        if self._isPotentialUnitType(type) :
            om = pm.optionMenu(l='', ann=annotation, cc=pm.CallbackWithArgs( MethodRow.setUnitType, self, methodIndex, argName ) )
            for unit in ['unitless', 'linear', 'angular', 'time']:
                pm.menuItem(l=unit)
            if argName == 'return':
                try:
                    value = factories.apiClassOverrides[self.apiClassName]['methods'][self.apiMethodName][methodIndex]['returnInfo']['unitType']
                except KeyError:
                    pass
            else:
                try:
                    value = factories.apiClassOverrides[self.apiClassName]['methods'][self.apiMethodName][methodIndex]['argInfo'][argName]['unitType']
                except KeyError:
                    pass
            try:
                om.setValue(value)
            except: pass

        else:
            pm.text( l='', ann=annotation )
        pm.setParent('..')
예제 #56
0
    def build_menu(self, menu, panel):
        '''
        Resets the menu, then builds all menu items based on the node and adds them to the context menu

        Args:
            menu (ui.PopupMenu): menu to add items to
            panel (ui.Panel): The active model panel, generally the active viewport
        '''
        self.reset_menu()

        pm.dagObjectHit(mn=self.menu)
        dag_menu = pm.popupMenu(self.menu, q=True, itemArray=True)

        context_pynode = None
        if dag_menu:
            context_obj = pm.menuItem(dag_menu[0], q=True, l=True).strip(".")
            context_pynode = pm.PyNode(context_obj)

        sel_node = pm.ls(sl=True)[-1] if pm.ls(sl=True) else None

        pm.popupMenu(self.menu, e=True, deleteAllItems=True)
        if context_pynode:
            self.node = context_pynode
        elif sel_node:
            self.node = sel_node

        if self.node:
            node_simple_name = self.node.name().split('|')[-1]
            #pm.inViewMessage(assistMessage = node_simple_name, position = "topCenter", fade = True, fontSize = 10, fst = 2000, dragKill = False)
            rig_menu = pm.menuItem(label=node_simple_name,
                                   parent=self.menu,
                                   rp="N")
            if not metadata.meta_properties.get_properties_dict(self.node).get(
                    metadata.meta_properties.ControlProperty):
                # Build our Context Menu if we've found a dag object
                self.menu_dict['properties'] = self.build_property_menu()
            else:
                self.menu_dict['rigging'] = self.build_rig_component_menu()
예제 #57
0
    def select_blend_shape(self, blend_shape):
        menu_items = pm.optionMenu('sbsList|OptionMenu', q=True, itemListLong=True)
        for idx, menu_item in enumerate(menu_items):
            item = pm.menuItem(menu_item, q=True, label=True)

            nodes = pm.ls(item)
            if not nodes:
                continue
            node = nodes[0]

            if node != blend_shape:
                continue;

            pm.optionMenuGrp('sbsList', edit=True, select=idx + 1)
예제 #58
0
    def __init__(self):
        if pm.menu(self.top_menu_name, exists=True):
            pm.deleteUI(self.top_menu_name)

        self.menu_flottitools = pm.menu(self.top_menu_name,
                                        parent=get_gmain_window(),
                                        tearOff=True,
                                        label=self.top_menu_label)

        def make_sub_menu(label):
            return pm.menuItem(parent=self.menu_flottitools,
                               label=label,
                               subMenu=True,
                               tearOff=True)

        self.menu_rigging = make_sub_menu("Rigging")

        pm.menuItem(parent=self.menu_flottitools, divider=True)

        # Classes that inherit from MenuItem are added to menu_flotti_tools in the order that they appear in this file.
        menu_items = _get_menu_item_classes()
        for menu_item in menu_items:
            menu_item(self)
예제 #59
0
파일: menu.py 프로젝트: S0nic014/luna
    def addSubMenu(parent,
                   label,
                   tear_off=False,
                   icon=None,
                   use_maya_icons=False):
        '''Adds a sub menu item with the specified label and icon to the specified parent popup menu.'''
        if icon and not use_maya_icons:
            icon = fileFn.get_icon_path(icon)

        return pm.menuItem(p=parent,
                           l=label,
                           i=icon,
                           subMenu=True,
                           to=tear_off)
예제 #60
0
    def uiWindow(self):
        # checking for duplicate windows
        windowID = 'PrismRigger'
        if pm.window(windowID, exists=True):
            pm.deleteUI(windowID)
            pm.windowPref(windowID, remove=True)

        # creating window
        pm.window(windowID, title=u'Prism リガー', widthHeight=(600, 800))

        # menu bar
        menuBar = pm.menuBarLayout()
        helpMenu = pm.menu(label=u'Help')
        manualMenu = pm.menuItem(label=u'仕様書', parent=helpMenu, subMenu=True)#help