Esempio n. 1
0
 def addAttrsFromList( self ):
     # Get the attribute list items in the UI.
     rows = cmds.scrollLayout( self.attrList, query=True, childArray=True )
     
     # Get the rows that are active (check box is True) and put them in a list.
     activeRows = []
     for row in rows:
         for element in cmds.rowColumnLayout( row, query=True, childArray=True ):
             elementType = cmds.objectTypeUI( element )
             if elementType == 'checkBox':
                 if cmds.checkBox( element, query=True, value=True ):
                     activeRows.append( row )
     
     # Get the attribute list from the XML file. This is used to pull the settings for a given
     # attribute type.
     attList = getAttrXML()
     
     # Now we loop through all the active items from the the list and add them to the selected
     # object.
     for row in activeRows:
         rowChildren = cmds.rowColumnLayout( row, query=True, childArray=True )
         for child in rowChildren:
             elementType = cmds.objectTypeUI( child )
             if elementType == 'staticText':
                 label = cmds.text( child, query=True, label=True )
                 for attr in attList:
                     if attr['name'] == label:
                         addAttr( [{ 'attrName':attr['name'], 'attrType':attr['attrType'], 'attrDataType':attr['attrDataType'] }] )
Esempio n. 2
0
def loadDirectoryPath(textField,caption='Load Directory',startDir=None):
	'''
	Select a file path to load into a specified textField.
	@param textField: TextField UI object to load file path to
	@type textField: str
	@param caption: File selection UI caption string
	@type caption: str
	@param startDir: Directory to start browsing from. In None, use the default or last selected directory.
	@type startDir: str
	'''
	# Get File Path
	dirPath = mc.fileDialog2(	dialogStyle=2,
								fileMode=3,
								caption=caption,
								okCaption='Load',
								startingDirectory=startDir )

	# Check File Path
	if not dirPath:
		print('Invalid directory path!')
		return

	# Load File Path to TextField
	if mc.textField(textField,q=True,ex=True):
		mc.textField(textField,e=True,text=dirPath[0])
	elif mc.textFieldGrp(textField,q=True,ex=True):
		mc.textFieldGrp(textField,e=True,text=dirPath[0])
	elif mc.textFieldButtonGrp(textField,q=True,ex=True):
		mc.textFieldButtonGrp(textField,e=True,text=dirPath[0])
	else:
		print('UI element "'+textField+'" is of type "'+mc.objectTypeUI(textField)+'"! Expected textField, textFieldGrp or textFieldButtonGrp.')
		return

	# Return Result
	return dirPath[0]
def add_to_menu_snippet():
	model_panels = cmds.getPanel(type='modelPanel')
	TAG_NAME = '_viewport_button'
	for panel in model_panels:
		bar_layout = cmds.modelPanel(panel, query=True, barLayout=True)
		if not bar_layout:
			continue
		menu_layout = cmds.layout(bar_layout, query=True, childArray=True)[0]
		# example for icontextcheckbox
		tagged_items = [
			child for child in cmds.layout(layout, query=True, childArray=True)
			if cmds.objectTypeUI(child) == 'iconTextCheckBox'
			and cmds.iconTextCheckBox(child, query=True, label=True) == TAG_NAME
		]
		if not tagged_items:
			cmds.iconTextCheckBox(
				image=icon_path,
				style='iconOnly',
				annotation='Toggle ' + name.capitalize(),
				label=TAG_NAME
				width=18,
				height=18,
				onCommand=on_command, # some function
				offCommand=off_command, # some function
				parent=menu_layout,
			)
		OpenMayaUI.M3dView.getM3dViewFromModelPanel(menu_layout).refresh(force=True)
Esempio n. 4
0
def denyDrops(*args):
    try:
        from PySide import QtGui
        import shiboken
    except:
        cmds.warning('Cannot import PySide or shiboken, skipping...')
        return

    panels = args or cmds.lsUI(panels=True, l=True) or list()
    for p in panels:
        if not cmds.objectTypeUI(p) == 'modelEditor':
            continue

        cmds.setFocus(p)
        mp = cmds.playblast(activeEditor=True)
        mp = omui.MQtUtil.findControl(mp)

        try:
            mp = shiboken.wrapInstance(long(mp), QtGui.QWidget)
        except OverflowError:
            continue

        if mp.acceptDrops():
            mp.setAcceptDrops(False)
            om.MGlobal.displayInfo('Denied drops for editor: %s' % p)
Esempio n. 5
0
def loadDirectoryPath(textField,caption='Load Directory',startDir=None):
	'''
	Select a file path to load into a specified textField.
	@param textField: TextField UI object to load file path to
	@type textField: str
	@param caption: File selection UI caption string
	@type caption: str
	@param startDir: Directory to start browsing from. In None, use the default or last selected directory.
	@type startDir: str
	'''
	# Get File Path
	dirPath = mc.fileDialog2(	dialogStyle=2,
								fileMode=3,
								caption=caption,
								okCaption='Load',
								startingDirectory=startDir )
	
	# Check File Path
	if not dirPath:
		print('Invalid directory path!')
		return
	
	# Load File Path to TextField
	if mc.textField(textField,q=True,ex=True):
		mc.textField(textField,e=True,text=dirPath[0])
	elif mc.textFieldGrp(textField,q=True,ex=True):
		mc.textFieldGrp(textField,e=True,text=dirPath[0])
	elif mc.textFieldButtonGrp(textField,q=True,ex=True):
		mc.textFieldButtonGrp(textField,e=True,text=dirPath[0])
	else:
		print('UI element "'+textField+'" is of type "'+mc.objectTypeUI(textField)+'"! Expected textField, textFieldGrp or textFieldButtonGrp.')
		return
	
	# Return Result
	return dirPath[0]
Esempio n. 6
0
    def dropEvent(self, event):
        self.highlight.hide()
        dropIndex = self.getIndexFrom(event.pos())

        print 'Drop Index:', dropIndex
        #print event
        #print '\n'.join(event.mimeData().formats())

        if 'application/x-maya-data' in event.mimeData().formats():
            widget = event.source()

            controlPath = qt.widgetToMayaName(widget).split('|')

            control = controlType = None
            for i in range(len(controlPath)):
                try:
                    if i:
                        path = '|'.join(controlPath[:-i])
                    else:
                        path = '|'.join(controlPath)
                    controlType = cmds.objectTypeUI(path)
                    control = path
                    break
                except:
                    continue

            btn = shelfbutton.ShelfButton.createFromMaya(
                event.mimeData(), control, controlType)
            self.shelfLayout.insertWidget(dropIndex, btn)
Esempio n. 7
0
 def readUI(self):
     '''
     This reads the UI elements and turns them into arguments saved in a kwargs style member variable
     '''
     
     if self.uiArgDict:
         #this is some fanciness to read the values of UI elements and generate or run the resulting command
         #keys represent the argument names, the values are UI elements
         
         for k in self.uiArgDict.keys():
             
             uiType = mc.objectTypeUI(self.uiArgDict[k])
             value = None
             if uiType == 'rowGroupLayout':
                 controls = mc.layout(self.uiArgDict[k], query=True, childArray=True)
                 if 'check1' in controls:
                     value = mc.checkBoxGrp(self.uiArgDict[k], query=True, value1=True)
                 elif 'radio1' in controls:
                     buttonNumber = mc.radioButtonGrp(self.uiArgDict[k], query=True, select=True)
                     #there should be a control for the label and each the buttons..I hope
                     labels = mc.radioButtonGrp(self.uiArgDict[k], query=True, **{'labelArray'+str(len(controls)-1):True})
                     value = labels[buttonNumber-1]
             else:
                 OpenMaya.MGlobal.displayWarning('Cannot read '+uiType+' UI element: '+self.uiArgDict[k])
                 continue
             
             self.kwargs[k] = value
Esempio n. 8
0
def setUIObjectVisibility(item, visState):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Toggle for turning off and on the visibility of a menu section

    ARGUMENTS:
    stateToggle(string) - this should point to the variable holding a (bool) value
    listOfItems(list) - list of menu item names to change

    RETURNS:
    locatorName(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    uiType = mc.objectTypeUI(item)

    if uiType == 'staticText':
        mc.text(item, edit = True, visible = visState)
    elif uiType == 'separator':
        mc.separator(item, edit = True, visible = visState)
    elif uiType == 'rowLayout':
        mc.rowLayout(item, edit = True, visible = visState)
    elif uiType == 'rowColumnLayout':
        mc.rowColumnLayout(item, edit = True, visible = visState)
    elif uiType == 'columnLayout':
        mc.columnLayout(item, edit = True, visible = visState)
    elif uiType == 'formLayout':
        mc.formLayout(item, edit = True, visible = visState)
        #print ('%s%s%s%s%s%s%s' % ('"python(mc.',uiType,"('",item,"', edit = True, visible = ",visState,'))"'))
        #mel.eval(('%s%s%s%s%s%s%s' % ('"python(mc.',uiType,"('",item,"', edit = True, visible = ",visState,'))"')))
        #mc.separator(item, edit = True, visible = visState)
    else:
        warning('%s%s%s' %('No idea what ', item, ' is'))
Esempio n. 9
0
	def dropEvent(self, event):
		self.highlight.hide()
		dropIndex = self.getIndexFrom(event.pos())

		print 'Drop Index:',dropIndex
		#print event
		#print '\n'.join(event.mimeData().formats())

		if 'application/x-maya-data' in event.mimeData().formats():
			widget = event.source()

			controlPath = qt.widgetToMayaName(widget).split('|')

			control = controlType = None
			for i in range(len(controlPath)):
				try:
					if i:
						path = '|'.join(controlPath[:-i])
					else:
						path = '|'.join(controlPath)
					controlType = cmds.objectTypeUI(path)
					control = path
					break
				except:
					continue


			btn = shelfbutton.ShelfButton.createFromMaya(event.mimeData(), control, controlType)
			self.shelfLayout.insertWidget(dropIndex, btn)
Esempio n. 10
0
def hiButton(theShelf, buttonCommand, srDir):
    cmds.setParent(theShelf)
    buttonTag = True
    shelfButton = cmds.shelfLayout(theShelf, q=1, ca=1)

    if shelfButton is None:
        cmds.shelfButton(annotation=buttonAnnotation,
                         image1=srDir + theIcon,
                         command="mel.eval(\"" + buttonCommand + "\")",
                         label=buttonLabel,
                         scaleIcon=True)
        buttonTag = False
    else:
        for button in shelfButton:
            label = ""
            if cmds.objectTypeUI(button, isType="shelfButton"):
                label = str(cmds.shelfButton(button, q=1, label=1))
                if buttonLabel == label:
                    buttonTag = False
    if buttonTag:
        cmds.shelfButton(annotation=buttonAnnotation,
                         image1=srDir + theIcon,
                         command="mel.eval(\"" + buttonCommand + "\")",
                         label=buttonLabel,
                         scaleIcon=True)
Esempio n. 11
0
def setUIObjectVisibility(item, visState):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Toggle for turning off and on the visibility of a menu section

    ARGUMENTS:
    stateToggle(string) - this should point to the variable holding a (bool) value
    listOfItems(list) - list of menu item names to change

    RETURNS:
    locatorName(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    uiType = mc.objectTypeUI(item)

    if uiType == 'staticText':
        mc.text(item, edit=True, visible=visState)
    elif uiType == 'separator':
        mc.separator(item, edit=True, visible=visState)
    elif uiType == 'rowLayout':
        mc.rowLayout(item, edit=True, visible=visState)
    elif uiType == 'rowColumnLayout':
        mc.rowColumnLayout(item, edit=True, visible=visState)
    elif uiType == 'columnLayout':
        mc.columnLayout(item, edit=True, visible=visState)
    elif uiType == 'formLayout':
        mc.formLayout(item, edit=True, visible=visState)
        #print ('%s%s%s%s%s%s%s' % ('"python(mc.',uiType,"('",item,"', edit = True, visible = ",visState,'))"'))
        #mel.eval(('%s%s%s%s%s%s%s' % ('"python(mc.',uiType,"('",item,"', edit = True, visible = ",visState,'))"')))
        #mc.separator(item, edit = True, visible = visState)
    else:
        warning('%s%s%s' % ('No idea what ', item, ' is'))
Esempio n. 12
0
    def getVal(self, control):

        #control = self.getControlByName( control )

        if cmds.objectTypeUI(control) == "field":
            return cmds.textField(control, query=True, text=True)

        elif cmds.objectTypeUI(control) == "checkBox":
            return cmds.checkBox(control, query=True, value=True)

        elif cmds.objectTypeUI(control) == "radioCluster":
            return cmds.radioCollection(control, query=True, sl=True)

        elif cmds.objectTypeUI(control) == "rowGroupLayout":
            return cmds.optionMenuGrp(control, query=True, value=True)

        else:
            return None
def imgPlaneCreator():
    #get show, shot, asset, version
    showName = os.getenv('SHOW')
    shotName = os.getenv('SHOT')
    assetName = 'BG_light_flatanim_plate'
    highestVersion = shotgun.getLastVersion(showName, shotName, assetName)[assetName]
    if highestVersion == 0:
        #no light flatanim plate published, set starting path to lib/images
        startPath = '/X/projects/' + showName + '/SHOTS/' + shotName + '/lib/images'
    else:
        #get version name
        if len(str(highestVersion)) == 1:
            versionName = 'v00' + str(highestVersion)
        if len(str(highestVersion)) == 2:
            versionName = 'v0' + str(highestVersion)
        if len(str(highestVersion)) == 3:
            versionName = 'v' + str(highestVersion)
        #create starting path
        startPath = '/X/projects/' + showName + '/SHOTS/' + shotName + '/lib/images/anim/BG_flatanim_plate/' + assetName + '/' + versionName 
    #get render settings
    renderEngine = mc.getAttr("defaultRenderGlobals.ren")
    resWidth = mc.getAttr('defaultResolution.width')
    resHeight = mc.getAttr('defaultResolution.height')
    deviceAspectRatio = mc.getAttr('defaultResolution.deviceAspectRatio')
    #get selected panel
    activePanel = mc.getPanel(withFocus = True)
    if (mc.objectTypeUI(activePanel) == 'modelEditor'):
        #get camera
        activeCam = mc.modelPanel(activePanel, q = True, camera = True)
        camShape = mc.listRelatives(activeCam, shapes = True)
        #get camera info
        camScale = mc.getAttr(camShape[0]+'.cameraScale')
        camAperture = mc.getAttr(camShape[0]+'.horizontalFilmAperture')
        regSizeX = float(camAperture)
        regSizeY = float(camAperture) / float(deviceAspectRatio)
        newSizeX = regSizeX * float(camScale)
        newSizeY = regSizeY * float(camScale)
        #open file browser
        filePath = mc.fileDialog2(fileMode = 1, caption = 'Create Image Plane', dir = startPath)
        #create image plane and setup attributes
        if filePath:
            if (len(filePath) == 1):
                imgPlaneName = mc.imagePlane(camera = camShape[0], fileName = filePath[0])
                mc.setAttr(imgPlaneName[0]+'.useFrameExtension',1)
                mc.setAttr(imgPlaneName[0]+'.depth',5000)
                mc.setAttr(imgPlaneName[0]+'.fit',4)
                mc.setAttr(imgPlaneName[0]+'.coverageX',resWidth)
                mc.setAttr(imgPlaneName[0]+'.coverageY',resHeight)
                if renderEngine == "vray":
                    mc.setAttr(imgPlaneName[0]+'.sizeX',newSizeX)
                    mc.setAttr(imgPlaneName[0]+'.sizeY',newSizeY)
                else:
                    mc.setAttr(imgPlaneName[0]+'.sizeX',regSizeX)
                    mc.setAttr(imgPlaneName[0]+'.sizeY',regSizeY)
    else:
        mc.warning('Please select a view and try again.')
Esempio n. 14
0
def RemoveSeparator(shelfName, iconName):
    createShelf(shelfName)
    shelfButtons = cmds.shelfLayout(shelfName, q=True, childArray=True)

    if shelfButtons:
        for btn in shelfButtons:
            label = ''

            #Assert that this is a shelfButton
            if cmds.objectTypeUI(btn, isType='separator'):
                cmds.deleteUI(btn)
Esempio n. 15
0
def byeButton(theShelf):
    shelfButtons = cmds.shelfLayout(theShelf, q=1, ca=1)
    for button in shelfButtons:
        label = ""
        # Assert that this is a shelfButton
        if cmds.objectTypeUI(button, isType="shelfButton"):
            label = str(cmds.shelfButton(button, q=1, label=1))
            # If this button has the label we're looking for,
            # delete the button.
            if buttonLabel == label:
                cmds.deleteUI(button)
Esempio n. 16
0
def RemoveButton(shelfName, iconName):
    shelfButtons = cmds.shelfLayout(shelfName, q=True, childArray=True)

    if shelfButtons:
        for btn in shelfButtons:
            label = ''

            #Assert that this is a shelfButton
            if cmds.objectTypeUI(btn, isType='shelfButton'):

                label = cmds.shelfButton(btn, q=True, label=True)

                #If this button has the label we're looking for,
                #delete the button.
                if iconName == label:
                    cmds.deleteUI(btn)
Esempio n. 17
0
File: base.py Progetto: kthulhu/mrv
    def _exists(cls, uiname):
        """
		:return: 1 if the given UI element exists, 0 if it does not exist
			and 2 it exists but the passed in name does not guarantee there are not more
			objects with the same name"""
        try:
            uitype = cmds.objectTypeUI(uiname)
        except RuntimeError:
            return 0
        else:
            # short names can only be used with top level items like
            # windows - for everything else we cannot know how many items
            # with the same name exist and which one we should actually wrap
            # Claim it does not exist
            if "Window" not in uitype and cls._sep not in uiname:
                return 2
            return 1
Esempio n. 18
0
	def _exists( cls, uiname ):
		"""
		:return: 1 if the given UI element exists, 0 if it does not exist
			and 2 it exists but the passed in name does not guarantee there are not more
			objects with the same name"""
		try:
			uitype = cmds.objectTypeUI( uiname )
		except RuntimeError:
			return 0
		else:
			# short names can only be used with top level items like
			# windows - for everything else we cannot know how many items
			# with the same name exist and which one we should actually wrap
			# Claim it does not exist
			if "Window" not in uitype and cls._sep not in uiname:
				return 2
			return 1
Esempio n. 19
0
    def wrap(cls, control_name, key=None):

        def _spoof_create(*_, **__):
            return control_name

        try:
            cache_CMD = cls.CMD
            cls.CMD = _spoof_create

            # allow wrapping of abstract types, but make sure derived types are correct
            if cls.__name__ not in ('Control', 'Layout', 'Nested', 'Panel', 'MenuItem', 'PopupMenu'):
                if not cmds.objectTypeUI(control_name, isType = cache_CMD.__name__):
                    raise RuntimeError( "{} is not an instance of {}".format(control_name, cache_CMD.__name__))
            return cls(key=control_name)

        finally:
            cls.CMD = cache_CMD
Esempio n. 20
0
def removeButton(shelfName, iconName):
    shelfButtons = cmds.shelfLayout(shelfName, q=True, childArray=True)

    for btn in shelfButtons:
        label = ''

        #Assert that this is a shelfButton
        if cmds.objectTypeUI(btn, isType='shelfButton'):

            label = cmds.shelfButton(btn, q=True, image=True)

            #If this button has the label we're looking for,
            #delete the button.
            if iconName == label:
                cmds.deleteUI(btn)


#removeButton('Toolbox','abc_reassignShaders.svg')
Esempio n. 21
0
    def get_menu_item(label, parent_menu=None):
        'returns menu item with label in parent_menu'
        menu_item = None
        
        # if it is top level menu
        for m in mc.lsUI(type='menu'):
            if mc.objectTypeUI(m) != 'commandMenuItem' and mc.menu(m, q=1, l=1) == label:
                menu_item = m

                if parent_menu:
                    if not menu_item in mc.menu(parent_menu, q=1, ia=1) or []:
                        continue
                else:
                    break

        pmc = mc.menu(menu_item, q=1, pmc=1)
        if pmc:
            mm.eval(pmc)

        return menu_item
Esempio n. 22
0
    def get_menu_item(label, parent_menu=None):
        'returns menu item with label in parent_menu'
        menu_item = None
        
        # if it is top level menu
        for m in mc.lsUI(type='menu'):
            if mc.objectTypeUI(m) != 'commandMenuItem' and mc.menu(m, q=1, l=1) == label:
                menu_item = m

                if parent_menu:
                    if not menu_item in mc.menu(parent_menu, q=1, ia=1) or []:
                        continue
                else:
                    break

        pmc = mc.menu(menu_item, q=1, pmc=1)
        if pmc:
            mm.eval(pmc)

        return menu_item
def turnOffModelEditors():
    """
    Turns off all modelEditors in maya
    """
    mel.eval('cycleCheck -e off;')

    for editor in cmds.lsUI(panels = True):
        if cmds.objectTypeUI(editor) == 'modelEditor':
            logger.info('Turning off %s' % editor)
            cmds.modelEditor(editor, edit = True, allObjects = False)
    for editor in cmds.lsUI(editors = True):
        if 'BB_myMayaEditor' in editor:
            logger.info('Turning off %s' % editor)

    ## check for height fields that need to be turned of manually as they still display
    heightFields = cmds.ls(type = 'heightField')
    for eachHF in heightFields:
        try:
            cmds.setAttr('%s.visibility' % eachHF, 0)
        except:
            pass
def turnOnModelEditors():
	"""
	Turns on all modelEditors in maya
	"""
	for editor in cmds.lsUI(panels= True):
		if cmds.objectTypeUI(editor)=='modelEditor':
			print 'Turning on %s' % editor
			cmds.modelEditor(editor, edit = True, allObjects = True)
	for editor in cmds.lsUI(editors= True):
		if 'BB_myMayaEditor' in editor:
			print 'Turning on %s' % editor
			cmds.modelEditor(editor, edit = True, allObjects = True)
			cmds.modelEditor(editor, edit = True, allObjects = False)

	## check for height fields that need to be turned of manually as they still display
	heightFields = cmds.ls(type = 'heightField')
	for eachHF in heightFields:
		try:
			cmds.setAttr('%s.visibility' % eachHF, 1)
		except:
			pass
Esempio n. 25
0
def turnOffModelEditors():
    """
    Turns off all modelEditors in maya
    """
    mel.eval('cycleCheck -e off;')

    for editor in cmds.lsUI(panels=True):
        if cmds.objectTypeUI(editor) == 'modelEditor':
            print 'Turning off %s' % editor
            cmds.modelEditor(editor, edit=True, allObjects=False)
    for editor in cmds.lsUI(editors=True):
        if 'BB_myMayaEditor' in editor:
            print 'Turning off %s' % editor

    ## check for height fields that need to be turned of manually as they still display
    heightFields = cmds.ls(type='heightField')
    for eachHF in heightFields:
        try:
            cmds.setAttr('%s.visibility' % eachHF, 0)
        except:
            pass
Esempio n. 26
0
    def start(self):
        """
        :summary: is called in the start() function, contains the main UI for the scripts
        :parameter: none
        :return: nothing
        """
        self.typeCol = cmds.columnLayout(self.col,
                                         parent=self.window,
                                         w=self.width)
        """
        # section one
        frameLayout1 = cmds.frameLayout(width=self.width, label="Rocks", collapse=True, collapsable=True,
                                        marginHeight=10,
                                        marginWidth=5, parent=self.typeCol,
                                        ec=partial(frameCollapseChanged, str(self.col)),
                                        cc=partial(frameCollapseChanged, str(self.col)))

        cmds.rowColumnLayout(numberOfColumns=1, columnWidth=[(1, self.width - 10)], parent=frameLayout1,
                             co=[1, "both", 5])
        cmds.text("stuff")
        """

        # section two
        frameLayoutFence = cmds.frameLayout(width=self.width,
                                            label="Fences",
                                            collapse=True,
                                            collapsable=True,
                                            marginHeight=10,
                                            marginWidth=5,
                                            parent=self.typeCol,
                                            ec=partial(frameCollapseChanged,
                                                       str(self.col)),
                                            cc=partial(frameCollapseChanged,
                                                       str(self.col)))

        cmds.rowColumnLayout(numberOfColumns=2,
                             columnWidth=[(1, (self.width - 20) / 2.0),
                                          (2, (self.width - 20) / 2.0)],
                             parent=frameLayoutFence,
                             co=[1, "both", 5])
        cmds.button(label="Curve",
                    h=20,
                    command=lambda args: fl.Logger().curve("curve"))
        cmds.textField("curve", en=False, text="None", height=20)
        cmds.button(label="Post",
                    h=20,
                    command=lambda args: fl.Logger().fencePost("post"))
        cmds.textField("post", en=False, text="None", height=20)
        cmds.button(label="Picket",
                    h=20,
                    command=lambda args: fl.Logger().fencePicket("picket"))
        cmds.textField("picket", en=False, text="None", height=20)

        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutFence,
                             co=[1, "both", 5])
        cmds.floatSliderGrp('spacing',
                            label='Picket Spacing',
                            field=True,
                            minValue=1,
                            maxValue=100,
                            value=1,
                            columnWidth=[(1, 100), (2, 50),
                                         (3, self.width - 150)],
                            cal=[1, "center"])
        cmds.intSliderGrp('postNum',
                          label='Number of Posts',
                          field=True,
                          minValue=2,
                          maxValue=30,
                          value=2,
                          step=2,
                          columnWidth=[(1, 100), (2, 50),
                                       (3, self.width - 150)],
                          cal=[1, "center"])
        cmds.text("Cross Beams", height=20)
        cmds.text("select edge-loop location on post")

        cmds.rowColumnLayout(numberOfColumns=2,
                             columnWidth=[(1, (self.width - 20) / 2.0),
                                          (2, (self.width - 20) / 2.0)],
                             parent=frameLayoutFence,
                             co=[1, "both", 5])
        cmds.button(label="Location One",
                    h=20,
                    command=lambda args: fl.Logger().logLoop_1("locationOne"))
        cmds.textField("locationOne", en=False, text="None", height=20)
        cmds.button(label="Location Two",
                    h=20,
                    command=lambda args: fl.Logger().logLoop_2("locationTwo"))
        cmds.textField("locationTwo", en=False, text="None", height=20)
        cmds.button(
            label="Location Three",
            h=20,
            command=lambda args: fl.Logger().logLoop_3("locationThree"))
        cmds.textField("locationThree", en=False, text="None", height=20)
        cmds.button(label="Location Four",
                    h=20,
                    command=lambda args: fl.Logger().logLoop_4("locationFour"))
        cmds.textField("locationFour", en=False, text="None", height=20)
        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutFence,
                             co=[1, "both", 5])
        cmds.intSliderGrp('sidesNum',
                          label='Number of Sides',
                          field=True,
                          minValue=3,
                          maxValue=30,
                          value=1,
                          columnWidth=[(1, 100), (2, 50),
                                       (3, self.width - 150)],
                          cal=[1, "center"])
        cmds.floatSliderGrp('crossWidth',
                            label='Width',
                            field=True,
                            minValue=5,
                            maxValue=75,
                            value=1,
                            columnWidth=[(1, 100), (2, 50),
                                         (3, self.width - 150)],
                            cal=[1, "center"])
        cmds.floatSliderGrp('crossHeight',
                            label='Height',
                            field=True,
                            minValue=5,
                            maxValue=75,
                            value=1,
                            columnWidth=[(1, 100), (2, 50),
                                         (3, self.width - 150)],
                            cal=[1, "center"])

        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutFence,
                             co=[1, "both", 5])
        cmds.button(
            label="Test",
            h=20,
            command=lambda args:
            (fl.Logger().confirm(), nl.FindPositions().postPositions()))

        # section three
        frameLayoutStacking = cmds.frameLayout(
            width=self.width,
            label="Stacking Objects",
            collapse=True,
            collapsable=True,
            marginHeight=10,
            marginWidth=5,
            parent=self.typeCol,
            ec=partial(frameCollapseChanged, str(self.col)),
            cc=partial(frameCollapseChanged, str(self.col)))
        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutStacking,
                             co=[1, "both", 5])
        cmds.text("Load In Objects")
        cmds.rowColumnLayout(numberOfColumns=3,
                             columnWidth=[
                                 (1, (self.width - 10) / 3.0),
                                 (2, (self.width - 10) / 3.0),
                                 (3, (self.width - 10) / 3.0),
                             ],
                             parent=frameLayoutStacking,
                             co=[1, "both", 5])
        cmds.button("Object One",
                    command=lambda args: st.LogObjects().saveObject(
                        "object_one", 1))  # 1
        cmds.textField("object_one", en=False, text="None")
        cmds.button(
            "Clear One",
            command=lambda args: st.LogObjects().deleteObject("object_one", 1))
        cmds.button("Object Two",
                    command=lambda args: st.LogObjects().saveObject(
                        "object_two", 2))  # 2
        cmds.textField("object_two", en=False, text="None")
        cmds.button(
            "Clear Two",
            command=lambda args: st.LogObjects().deleteObject("object_two", 2))
        cmds.button("Object Three",
                    command=lambda args: st.LogObjects().saveObject(
                        "object_three", 3))  # 3
        cmds.textField("object_three", en=False, text="None")
        cmds.button("Clear Three",
                    command=lambda args: st.LogObjects().deleteObject(
                        "object_three", 3))

        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutStacking,
                             co=[1, "both", 5])
        cmds.text("StackSize")

        cmds.rowColumnLayout(numberOfColumns=3,
                             columnWidth=[
                                 (1, (self.width - 10) / 3.0),
                                 (2, (self.width - 10) / 3.0),
                                 (3, (self.width - 10) / 3.0),
                             ],
                             parent=frameLayoutStacking,
                             co=[1, "both", 5])
        cmds.radioCollection("size")
        cmds.radioButton("smallStack", label="Small")
        cmds.radioButton("mediumStack", label="Medium", sl=True)
        cmds.radioButton("largeStack", label="Large")

        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutStacking,
                             co=[1, "both", 5])
        cmds.text("Disorder")
        cmds.text("(least to most)")
        cmds.floatSlider("disorder", min=0, max=1, value=0.5)
        cmds.text("")
        cmds.button(label="Stack It!",
                    h=30,
                    command=lambda args: st.Stack().create())

        # section four
        frameLayoutLeaning = cmds.frameLayout(
            width=self.width,
            label="Lean Against Wall",
            collapse=False,
            collapsable=True,
            marginHeight=10,
            marginWidth=5,
            parent=self.typeCol,
            ec=partial(frameCollapseChanged, str(self.col)),
            cc=partial(frameCollapseChanged, str(self.col)))
        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutLeaning,
                             co=[1, "both", 5])
        cmds.button(label="Load Object",
                    h=30,
                    command=lambda args: lw.LeanObject().loadInObject())
        cmds.button(label="Wall",
                    h=30,
                    command=lambda args: lw.LeanObject().loadInWall())
        cmds.button(label="Lean It",
                    h=30,
                    command=lambda args: lw.LeanObject().leanIt())

        # section five
        frameLayoutRenamer = cmds.frameLayout(
            width=self.width,
            label="Renaming Objects",
            collapse=False,
            collapsable=True,
            marginHeight=10,
            marginWidth=5,
            parent=self.typeCol,
            ec=partial(frameCollapseChanged, str(self.col)),
            cc=partial(frameCollapseChanged, str(self.col)))

        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutRenamer,
                             co=[1, "both", 5])

        cmds.text("Prefix", align="center")
        cmds.radioCollection("prefix")
        cmds.radioButton("character", label="Character")
        cmds.radioButton("ui", label="UI")
        cmds.radioButton("staticMesh", label="Static Mesh", sl=True)
        cmds.radioButton("vehicle", label="Vehicle")
        cmds.radioButton("weapon", label="Weapon")

        cmds.text("", h=2)
        cmds.separator()
        cmds.text(" ", h=2)

        cmds.text("Object Name", h=20)
        cmds.text("  ", h=2)
        cmds.textField("baseName")

        cmds.rowColumnLayout(numberOfColumns=1,
                             columnWidth=[(1, self.width - 10)],
                             parent=frameLayoutRenamer,
                             co=[1, "both", 5])
        cmds.button(label="Rename Object",
                    h=30,
                    command=lambda args: rn.rename())

        # put this at end
        winHeight = 0
        for child in cmds.columnLayout(self.typeCol, q=1, ca=1):
            winHeight += eval('cmds.' + cmds.objectTypeUI(child) + '("' +
                              child + '", q=1, h=1)')
        cmds.window(self.window, e=1, h=winHeight)
        cmds.showWindow(self.window)
Esempio n. 27
0
def capture_viewport(size=1.0):
    """Saves a versioned capture to the ``capture_folder`` defined in the
    preferences.

    The script will output to an image sequence and if FFFmpeg can be found
    converts it to a h264 movie file.
    It will also try to create a ``latest`` folder with a copy of the last
    exported image sequence.

    """
    ext = 'png'
    scene_info = QtCore.QFileInfo(cmds.file(q=True, expandName=True))

    # CAPTURE_DESTINATION
    capture_folder, workspace, base_destination_path = \
        base.capture_viewport_destination()

    _dir = QtCore.QFileInfo(base_destination_path).dir()
    if not _dir.exists():
        _dir.mkpath('.')

    # Use our custom ModelPanel picker to select the viewport we want to
    # capture
    from . import main

    picker = main.PanelPicker()
    picker.exec_()
    panel = picker.panel

    # Cancel if no selection was made
    if not panel:
        return

    # Make sure we have selected a valid panel as not all panels are modelEditors
    if panel is None or cmds.objectTypeUI(panel) != 'modelEditor':
        s = 'Activate a viewport before starting a capture.'
        raise RuntimeError(s)

    camera = cmds.modelPanel(panel, query=True, camera=True)

    # The panel settings using capture.py and update it with our
    # custom settings. See `base.CaptureOptions` for the hard-coded
    # defaults we're using here
    options = capture.parse_view(panel)
    options['viewport_options'].update(base.CaptureOptions)

    # Hide existing panels
    current_state = {}
    for panel in cmds.getPanel(type='modelPanel'):
        if not cmds.modelPanel(panel, exists=True):
            continue

        try:
            ptr = OpenMayaUI.MQtUtil.findControl(panel)
            if not ptr:
                continue
            panel_widget = shiboken2.wrapInstance(int(ptr), QtWidgets.QWidget)
            current_state[panel] = panel_widget.isVisible()
            if panel_widget:
                panel_widget.hide()
        except:
            log.error('# An error occured hiding {}'.format(panel))

    width = int(cmds.getAttr('defaultResolution.width') * size)
    height = int(cmds.getAttr('defaultResolution.height') * size)

    try:
        capture.capture(
            camera=camera,
            width=width,
            height=height,
            display_options=base.DisplayOptions,
            camera_options=base.CameraOptions,
            viewport2_options=options['viewport2_options'],
            viewport_options=options['viewport_options'],
            format='image',
            compression=ext,
            filename=base_destination_path,
            overwrite=True,
            viewer=False
        )
        log.success(f'Capture saved to {_dir.path()}')
    except:
        raise
    finally:
        cmds.ogs(reset=True)

        # Show hidden panels
        for panel in cmds.getPanel(type='modelPanel'):
            if not cmds.modelPanel(panel, exists=True):
                continue
            try:
                ptr = OpenMayaUI.MQtUtil.findControl(panel)
                if not ptr:
                    continue
                panel_widget = shiboken2.wrapInstance(
                    int(ptr), QtWidgets.QWidget
                )
                if panel_widget:
                    if panel in current_state:
                        panel_widget.setVisible(current_state[panel])
                    else:
                        panel_widget.setVisible(True)
            except:
                print(f'# Could not restore {panel} after capture')

    # Publish output
    publish_capture(workspace, capture_folder, scene_info, ext)

    # Push and reveal output
    path = base.CAPTURE_FILE.format(
        workspace=workspace,
        capture_folder=capture_folder,
        scene=scene_info.baseName(),
        frame='{}'.format(int(cmds.playbackOptions(q=True, minTime=True))).zfill(
            base.DefaultPadding
        ),
        ext=ext
    )
    push_capture(path)
    reveal_capture(path)
Esempio n. 28
0
def override_toolbox_ui():
    """Add custom buttons in Toolbox as replacement for Maya web help icon."""

    import colorbleed
    res = os.path.join(os.path.dirname(os.path.dirname(colorbleed.__file__)),
                       "res")
    icons = os.path.join(res, "icons")

    import avalon.tools.sceneinventory as inventory
    import avalon.tools.loader as loader
    from avalon.maya.pipeline import launch_workfiles_app

    # Ensure the maya web icon on toolbox exists
    web_button = "ToolBox|MainToolboxLayout|mayaWebButton"
    if not mc.iconTextButton(web_button, query=True, exists=True):
        return

    mc.iconTextButton(web_button, edit=True, visible=False)

    # real = 32, but 36 with padding - according to toolbox mel script
    icon_size = 36
    parent = web_button.rsplit("|", 1)[0]

    # Ensure the parent is a formLayout
    if not mc.objectTypeUI(parent) == "formLayout":
        return

    # Create our controls
    background_color = (0.267, 0.267, 0.267)
    controls = []

    control = mc.iconTextButton("colorbleed_toolbox_workfiles",
                                annotation="Work Files",
                                label="Work Files",
                                image=os.path.join(icons, "workfiles.png"),
                                command=lambda: launch_workfiles_app(),
                                bgc=background_color,
                                width=icon_size,
                                height=icon_size,
                                parent=parent)
    controls.append(control)

    control = mc.iconTextButton("colorbleed_toolbox_loader",
                                annotation="Loader",
                                label="Loader",
                                image=os.path.join(icons, "loader.png"),
                                command=lambda: loader.show(use_context=True),
                                bgc=background_color,
                                width=icon_size,
                                height=icon_size,
                                parent=parent)
    controls.append(control)

    control = mc.iconTextButton("colorbleed_toolbox_manager",
                                annotation="Inventory",
                                label="Inventory",
                                image=os.path.join(icons, "inventory.png"),
                                command=lambda: inventory.show(),
                                bgc=background_color,
                                width=icon_size,
                                height=icon_size,
                                parent=parent)
    controls.append(control)

    control = mc.iconTextButton("colorbleed_toolbox",
                                annotation="Colorbleed",
                                label="Colorbleed",
                                image=os.path.join(
                                    icons, "colorbleed_logo_36x36.png"),
                                bgc=background_color,
                                width=icon_size,
                                height=icon_size,
                                parent=parent)
    controls.append(control)

    # Add the buttons on the bottom and stack
    # them above each other with side padding
    controls.reverse()
    for i, control in enumerate(controls):
        previous = controls[i - 1] if i > 0 else web_button

        mc.formLayout(parent,
                      edit=True,
                      attachControl=[control, "bottom", 0, previous],
                      attachForm=([control, "left", 1], [control, "right", 1]))
from PySide import QtGui, QtCore 
from shiboken import wrapInstance 
import maya.cmds as mc
import maya.OpenMayaUI as mui


class ToolTipFilter(QtCore.QObject):
    '''A simple event filter to catch tooltip events'''
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.ToolTip:
            QtGui.QToolTip.hideText() 
            QtGui.QToolTip.showText(event.globalPos(), '%04f, %04f'%(event.globalX(), event.globalY()), obj)
            return False
        return True


global filter 
filter = ToolTipFilter()

for editor in mc.lsUI(panels=True): 
    if mc.objectTypeUI(editor)=='modelEditor':
        ptr = mui.MQtUtil.mainWindow()
        viewWidget = wrapInstance( long( ptr ), QtGui.QWidget ) 
        viewWidget.installEventFilter(filter)



Esempio n. 30
0
File: base.py Progetto: kthulhu/mrv
def getUIType(uiname):
    """
	:return: uitype string having a corresponding mel command - some types returned do not correspond
		to the actual name of the command used to manipulate the type """
    uitype = cmds.objectTypeUI(uiname)
    return typ._typemap.get(uitype, uitype)
Esempio n. 31
0
 def get(cls, editor_string):
     ptype = cmds.objectTypeUI(str(editor_string))
     pfclass = cls.TYPES.get(ptype, None)
     if not pfclass:
         raise RuntimeError("Unknown editor type: {}".format(ptype))
     return pfclass.wrap(editor_string)
Esempio n. 32
0
print mc.outlinerPanel(myOutliner, parent=True, q=True)        

##
mc.select("c_*")
selectionList = mc.ls(sl=True, type="transform")
mc.select(selectionList)
if selectionList:
    for item in selectionList:
        #nc = item.split("|")
        print item
        for axe in ["X", "Y", "Z"]:
            mc.setAttr(item + ".translate" + axe, lock=True)
                       
import maya.cmds as cmds

print(cmds.objectTypeUI( 'viewPanes' ))
import sys
for c,e in enumerate(cmds.objectTypeUI(listAll=True)):
    c += 1
    sys.stdout.write(e + " ")
    if c % 3 == 0:
        sys.stdout.write('\n')

channelWindow = mc.layout('MayaWindow|MainChannelsLayersLayout', parent=True, q=1)
mc.window(channelWindow, active=True, q=1)

## probleme bounding box infini
mc.exactWorldBoundingBox(mc.ls(sl=True))

listBad = []
selectionList = mc.ls(sl=1)
Esempio n. 33
0
 def get(cls, editor_string):
     ptype = cmds.objectTypeUI(str(editor_string))
     pfclass = cls.TYPES.get(ptype, None)
     if not pfclass:
         raise RuntimeError("Unknown editor type: {}".format(ptype))
     return pfclass.wrap(editor_string)
Esempio n. 34
0
def override_toolbox_ui():
    """Add custom buttons in Toolbox as replacement for Maya web help icon."""
    inventory = None
    loader = None
    launch_workfiles_app = None
    mayalookassigner = None
    try:
        import avalon.tools.sceneinventory as inventory
    except Exception:
        log.warning("Could not import SceneInventory tool")

    try:
        import avalon.tools.loader as loader
    except Exception:
        log.warning("Could not import Loader tool")

    try:
        from avalon.maya.pipeline import launch_workfiles_app
    except Exception:
        log.warning("Could not import Workfiles tool")

    try:
        from openpype.tools import mayalookassigner
    except Exception:
        log.warning("Could not import Maya Look assigner tool")

    from openpype.api import resources

    icons = resources.get_resource("icons")

    if not any((
        mayalookassigner, launch_workfiles_app, loader, inventory
    )):
        return

    # Ensure the maya web icon on toolbox exists
    web_button = "ToolBox|MainToolboxLayout|mayaWebButton"
    if not mc.iconTextButton(web_button, query=True, exists=True):
        return

    mc.iconTextButton(web_button, edit=True, visible=False)

    # real = 32, but 36 with padding - according to toolbox mel script
    icon_size = 36
    parent = web_button.rsplit("|", 1)[0]

    # Ensure the parent is a formLayout
    if not mc.objectTypeUI(parent) == "formLayout":
        return

    # Create our controls
    background_color = (0.267, 0.267, 0.267)
    controls = []
    if mayalookassigner:
        controls.append(
            mc.iconTextButton(
                "pype_toolbox_lookmanager",
                annotation="Look Manager",
                label="Look Manager",
                image=os.path.join(icons, "lookmanager.png"),
                command=lambda: mayalookassigner.show(),
                bgc=background_color,
                width=icon_size,
                height=icon_size,
                parent=parent
            )
        )

    if launch_workfiles_app:
        controls.append(
            mc.iconTextButton(
                "pype_toolbox_workfiles",
                annotation="Work Files",
                label="Work Files",
                image=os.path.join(icons, "workfiles.png"),
                command=lambda: launch_workfiles_app(),
                bgc=background_color,
                width=icon_size,
                height=icon_size,
                parent=parent
            )
        )

    if loader:
        controls.append(
            mc.iconTextButton(
                "pype_toolbox_loader",
                annotation="Loader",
                label="Loader",
                image=os.path.join(icons, "loader.png"),
                command=lambda: loader.show(use_context=True),
                bgc=background_color,
                width=icon_size,
                height=icon_size,
                parent=parent
            )
        )

    if inventory:
        controls.append(
            mc.iconTextButton(
                "pype_toolbox_manager",
                annotation="Inventory",
                label="Inventory",
                image=os.path.join(icons, "inventory.png"),
                command=lambda: inventory.show(),
                bgc=background_color,
                width=icon_size,
                height=icon_size,
                parent=parent
            )
        )

    # Add the buttons on the bottom and stack
    # them above each other with side padding
    controls.reverse()
    for i, control in enumerate(controls):
        previous = controls[i - 1] if i > 0 else web_button

        mc.formLayout(parent, edit=True,
                      attachControl=[control, "bottom", 0, previous],
                      attachForm=([control, "left", 1],
                                  [control, "right", 1]))
Esempio n. 35
0
def getUIType( uiname ):
	"""
	:return: uitype string having a corresponding mel command - some types returned do not correspond
		to the actual name of the command used to manipulate the type """
	uitype = cmds.objectTypeUI( uiname )
	return typ._typemap.get( uitype, uitype )