def Renameanim(posefile,*args): filename = os.path.basename(posefile).split('.')[0] dirname = os.path.dirname(posefile) seltab = mc.shelfTabLayout('Animation',q=1,st=1) AnimRename = mc.promptDialog( title='AnimRename', message='AnimRename:', text = filename, button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if AnimRename=='OK': newanimname = mc.promptDialog (query=True, text=True) renamanim= dirname+'/'+ newanimname+'.anim' renamimag= dirname+'/'+ newanimname+'.bmp' animimg = posefile.replace('.anim','.bmp') print animimg mc.sysFile(posefile,rename= renamanim) mc.sysFile(animimg,rename= renamimag) Refresh_UI(savepathini) print'Anim name changed succesfully' else: return mc.shelfTabLayout('Animation',e=1,st=seltab)
def Newtab(*args): sel_tab = mc.shelfTabLayout('tabs',q=1,st=1) crnt_tab= mc.shelfTabLayout(sel_tab,q=1,ca=1) Newtab = mc.promptDialog( title='Create New Tab', message='New Tab Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if Newtab == 'OK': n_text = mc.promptDialog(query=True, text=True) if n_text == '': mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is not valid', button=['OK'] ,defaultButton='Yes') else: if crnt_tab: for each in crnt_tab: if each == n_text: mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is already exists', button=['OK'] ,defaultButton='Yes') return #else: if sel_tab == 'Animation': Nw_tab=savepathini+'Savepose/Animation/'+n_text+'/' mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Animation) mc.sysFile(Nw_tab, makeDir=True ) else: mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Poses) Nw_tab=savepathini+'Savepose/Poses/'+n_text+'/' mc.sysFile(Nw_tab, makeDir=True ) mc.shelfTabLayout(sel_tab,e=1,st=n_text)
def collectShelfData(): # NOTE 加载所有的工具架 - 默认不加载全部 参考 commandLuancher 插件 loadShelves() # NOTE 获取工具架名称 gShelfTopLevel = mel.eval("$temp = $gShelfTopLevel") shelves = cmds.shelfTabLayout(gShelfTopLevel,query=1,ca=1) labels = cmds.shelfTabLayout(gShelfTopLevel,query=1,tl=1) # NOTE 获取所有的工具架分隔符的信息 for i,[shelf,label] in enumerate(zip(shelves,labels),1): # NOTE 获取完整组件名称 shelf = cmds.shelfLayout(shelf,query=1,fpn=1) if not cmds.shelfLayout(shelf,query=1,ca=1): print "[collapsibleShelf] %s empty child" % shelf continue separator = "" for item in cmds.shelfLayout(shelf,query=1,ca=1): if cmds.separator(item,query=1,ex=1): separator = item if shelf not in shelf_data: shelf_data[shelf] = {} shelf_data[shelf][separator] = [] elif cmds.shelfButton(item,query=1,ex=1): print item,mayaToQT(item) DraggableHandler(mayaToQT(item)) if not separator : continue shelf_data[shelf][separator].append(item)
def updateData(self, data, *args): # From Dict for lay in data: # Create Tab layoutLabel = lay.split('_')[0] cmds.gridLayout(lay, cellWidthHeight=(self.cel, self.cel), ag=True, cr=True, p=self.tab) cmds.setParent('..') cmds.shelfTabLayout(self.tab, e=True, tabLabel=(lay, layoutLabel)) for ctl in data[lay]: # Create Object annot = data[lay][ctl]['annotation'] bgc = data[lay][ctl]['color'] buttonCtl = cmds.button(ctl, l=ctl.split('_')[0], rs=True, p=lay, annotation=annot, c=partial(self.selectObjects, annot), bgc=bgc) self.pickerPopupMenu(buttonCtl)
def Renamepose(read1,*args): filename = os.path.basename(read1).split('.')[0] print filename dirname = os.path.dirname(read1) seltab = mc.shelfTabLayout('Poses',q=1,st=1) PoseRename = mc.promptDialog( title='PoseRename', message='PoseRename:', text = filename, button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if PoseRename=='OK': newposename = mc.promptDialog (query=True, text=True) renampose= dirname+'/'+ newposename+'.anim' renameimg= dirname+'/'+ newposename+'.bmp' read2=read1.replace('.anim','.bmp') mc.sysFile(read1,rename= renampose) mc.sysFile(read2,rename= renameimg) Refresh_UI(savepathini) print'Pose name changed successfully' else: return mc.shelfTabLayout('Poses',e=1,st=seltab)
def getShelfButton(): """getShelfButton Get Command data from Maya Shelf """ # NOTE 获取工具架名称 gShelfTopLevel = mel.eval("$temp = $gShelfTopLevel") shelves = cmds.shelfTabLayout(gShelfTopLevel, query=1, ca=1) labels = cmds.shelfTabLayout(gShelfTopLevel, query=1, tl=1) for i, [shelf, label] in enumerate(zip(shelves, labels), 1): # NOTE 获取完整组件名称 shelf = cmds.shelfLayout(shelf, query=1, fpn=1) if not cmds.shelfLayout(shelf, query=1, ca=1): print "%s empty child" % shelf continue for btn in cmds.shelfLayout(shelf, query=1, ca=1): if cmds.shelfButton(btn, query=1, ex=1): name = cmds.shelfButton(btn, query=1, label=1) icon = cmds.shelfButton(btn, query=1, i=1) # tooltip = cmds.shelfButton(btn,query=1,ann=1) COMMANDS[name] = dict() COMMANDS[name]["name"] = name COMMANDS[name]["pin"] = False if os.path.exists(icon): COMMANDS[name]["icon"] = utils.QIcon(icon) else: COMMANDS[name]["icon"] = utils.QIcon(":/{0}".format(icon)) COMMANDS[name]["group"] = "Shelf: %s" % label COMMANDS[name]["search"] = "%s%s" % (label, name) COMMANDS[name]["hierarchy"] = "%s > %s" % (label, name) COMMANDS[name]["category"] = "shelf" # COMMANDS[name]["menu"] = menu_list[-1] # NOTE 点击运行的代码 command = cmds.shelfButton(btn, query=1, c=1) command_type = cmds.shelfButton(btn, query=1, c=1, stp=1) if command_type.lower() == "mel": # Note 运行双击的 mel 代码 COMMANDS[name]["cmd"] = partial(mel.eval, command) else: # Note 运行双击的 python 代码 COMMANDS[name]["cmd"] = partial( lambda command: eval( compile(command, '<string>', 'exec')), command) # NOTE 查询双击 shelf 状态 options = cmds.shelfButton(btn, query=1, dcc=1) if options: options_type = cmds.shelfButton(btn, query=1, dcc=1, stp=1) if options_type.lower() == "mel": # Note 运行双击的 mel 代码 COMMANDS[name]["cmdOption"] = partial( mel.eval, options) else: # Note 运行双击的 python 代码 COMMANDS[name]["cmdOption"] = partial( lambda x: eval(compile(x, '<string>', 'exec')), options)
def cycleThroughShelves(): shelfTopLevel = getShelfTopLevel() currentTabIndex = m.shelfTabLayout(shelfTopLevel, q=True, selectTabIndex=True) shelves = getShelves() for i in range(1, len(shelves) + 1): m.shelfTabLayout(shelfTopLevel, e=True, selectTabIndex=i) m.shelfTabLayout(shelfTopLevel, e=True, selectTabIndex=currentTabIndex)
def set_current_tab(tab, ignore_case=True): if ignore_case: tab = [ t for t in get_existing_shelf_tabs() if t.lower() == tab.lower() ] if not tab: return tab = tab[0] mc.shelfTabLayout(SHELF_LAYOUT, edit=True, selectTab=tab)
def Deleteanim(posefile,*args): confirm=mc.confirmDialog (title='Confirm Delete pose',message=' Are you sure......?',ma='right',button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No') if confirm=='Yes': seltab = mc.shelfTabLayout('Animation',q=1,st=1) imgpose = posefile.replace('.anim','.bmp') mc.sysFile(posefile,delete=1) mc.sysFile(imgpose,delete=1) filename = os.path.basename(posefile).split('.')[0] Refresh_UI(savepathini) print filename + ' anim deleted..' mc.shelfTabLayout('Animation',e=1,st=seltab)
def build(self): if cmds.window( 'speedWin', ex=1 ): cmds.deleteUI( 'speedWin' ) if cmds.windowPref( 'speedWin', ex=1 ): cmds.windowPref( 'speedWin', remove=1 ) cmds.window( 'speedWin', t='SpeedTool', wh=(350, 260)) cmds.shelfTabLayout( 'mainShelfTab', image='smallTrash.png', imageVisible=True ) self.shelf = cmds.shelfLayout( 'Tools', cwh=(35, 35) ) cmds.shelfButton('save',imageOverlayLabel="save", i1='menuIconWindow.png', c=self.writeShelf) self.updateShelf() cmds.setParent( '..' ) cmds.setParent( '..' ) cmds.showWindow()
def to( self, null, shelf, pos, *args ): # delete from MM when CTRL is pressed if m.getModifiers() == 4 and pos: m.optionVar( rm=mmName + pos ) return # remember recenctly pressed from non radial list if not shelf in self.inRadial: if shelf in self.recent: self.recent.remove(shelf) self.recent.append(shelf) m.optionVar( sv=[mmName + 'Recent', ','.join(self.recent)] ) m.shelfTabLayout( mayaShelf, edit=1, selectTab=shelf )
def speedWindow(self): if mc.windowPref('facialWin', exists=1): mc.windowPref('facialWin', remove=1) if mc.window('facialWin', exists=1): mc.deleteUI('facialWin') mc.window('facialWin', t='Mudan_FacialPanel', w=960, h=430) mc.shelfTabLayout('mainShelfTab', image='smallTrash.png', imageVisible=1) mc.shelfLayout('Flower', cwh=(188, 196)) self.shelfButtonFlower() mc.setParent('..') mc.shelfLayout('Human', cwh=(188, 196)) self.shelfButtonHuman() mc.setParent('..') mc.showWindow()
def createShelf(): # delete the shelf is already exists if cmds.shelfLayout('dmptools', ex=True): fullname = cmds.shelfLayout('dmptools', fpn=True, q=True) cmds.deleteUI(fullname) # create the shelf shelfParent = cmds.shelfTabLayout('ShelfLayout', fpn=True, q=True) cmds.shelfLayout('dmptools', p=shelfParent) # create shelf buttons for button in BUTTONS: b = addButton(button) # select the last created shelf i = cmds.shelfTabLayout(shelfParent, numberOfChildren=True, q=True) cmds.shelfTabLayout(shelfParent, selectTabIndex=i, e=True)
def create(name, shelf_buttons): """ shelf_buttons: list of dicts with following keys: - icon: icon path - command: command to run. Optional if there is a menu on LMB. - double_click: command run on double click. - separator: optional, will ignore all other arguments and add a |. - label: optional, add a label to the shelf button. - source_type: optional, will be python by default - tooltip: optional tooltip string - repeatable: command repeatable (default Maya "G" hotkey). - menu: optional. Will create a right click menu. List of dict with: label, command, source_type, tooltip. """ # Delete and re-create delete(name) # mm.eval('addNewShelfTab2("%s")' % name) mc.shelfLayout(name, parent=SHELF_LAYOUT) # Fill the shelf for btn in shelf_buttons: if btn == SEPARATOR: mc.shelfButton(parent=name, image='shelf_separator.png', width=13) continue # Create the shelf button kwargs = dict(parent=name, image=btn['icon']) for kwarg, maya_kwarg in KWARGS_MATCHES.items(): if kwarg in btn: kwargs[maya_kwarg] = btn[kwarg] shelf_button = mc.shelfButton(**kwargs) # Create menu if there is one if 'menu' in btn: menu = btn['menu'] mouse_button = btn.get('menu_button') or 3 create_menu(menu, mouse_button, btn.get('command'), shelf_button) # Adapt shelves optionVar's shelf_index = mc.shelfTabLayout( SHELF_LAYOUT, query=True, numberOfChildren=True) + 1 mc.optionVar(stringValue=('shelfName%i' % shelf_index, name)) mc.optionVar(stringValue=('shelfFile%i' % shelf_index, 'shelf_' + name)) mc.optionVar(intValue=('shelfLoad%i' % shelf_index, 1)) mc.optionVar(intValue=('numShelves', shelf_index)) # Switch to shelf mc.shelfTabLayout('ShelfLayout', edit=True, selectTab=name)
def install_shelf(): """ checks if there's ngSkintTools shelf installed, and if not, creates one. this runs each time Maya starts (via Autoloader's ngSkinTools_load.mel) - avoid duplication, like creating things that already exist. """ maya_shelf = mel.eval("$tempngSkinToolsVar=$gShelfTopLevel") existing_shelves = cmds.shelfTabLayout(maya_shelf, q=True, tabLabel=True) parent_shelf = 'ngSkinTools' if parent_shelf in existing_shelves: return mel.eval('addNewShelfTab ' + parent_shelf) cmds.shelfButton( parent=parent_shelf, enable=1, visible=1, preventOverride=0, label="ngst", annotation="ngSkinTools UI", image="ngSkinToolsShelfIcon.png", style="iconOnly", noBackground=1, align="center", marginWidth=1, marginHeight=1, command= "from ngSkinTools.ui.mainwindow import MainWindow\nMainWindow.open()", sourceType="python", commandRepeatable=0, )
def startup(self, origin): if QApplication.instance() is None: return False if not hasattr(qApp, "topLevelWidgets"): return False for obj in qApp.topLevelWidgets(): if obj.objectName() == 'MayaWindow': mayaQtParent = obj break else: return False try: topLevelShelf = mel.eval('string $m = $gShelfTopLevel') except: return False if cmds.shelfTabLayout(topLevelShelf, query=True, tabLabelIndex=True) == None: return False origin.timer.stop() origin.messageParent = mayaQtParent
def create_shelf(): """ Create the OBB shelf Raises: None Returns: None """ tab_layout = mel.eval('$pytmp=$gShelfTopLevel') shelf_exists = cmds.shelfLayout('OBB', exists=True) if shelf_exists: cmds.deleteUI('OBB', layout=True) shelf = cmds.shelfLayout('OBB', parent=tab_layout) for button, kwargs in buttons.items(): img = QtGui.QImage(kwargs['image']) kwargs['width'] = img.width() kwargs['height'] = img.height() cmds.shelfButton(label=button, parent=shelf, **kwargs) # Fix object 0 error. shelves = cmds.shelfTabLayout(tab_layout, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=("shelfName%d" % (index + 1), str(shelf)))
def create_shelf(): """ Create the OBB shelf Raises: None Returns: None """ tab_layout = mel.eval('$pytmp=$gShelfTopLevel') shelf_exists = cmds.shelfLayout('OBB', exists=True) if shelf_exists: cmds.deleteUI('OBB', layout=True) shelf = cmds.shelfLayout('OBB', parent=tab_layout) for button, kwargs in buttons.items(): img = QtGui.QImage(kwargs['image']) kwargs['width'] = img.width() kwargs['height'] = img.height() cmds.shelfButton(label=button, parent=shelf, **kwargs) # Fix object 0 error. shelves = cmds.shelfTabLayout(tab_layout, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=("shelfName%d" % (index+1), str(shelf)))
def Pose_obj1(Animpose_name,currentImagePath): frameNumber = mc.currentTime(q=1) frameNumber =int(frameNumber) iconTmp = currentImagePath + "iconTmp." + str(frameNumber)+ ".bmp" print ("\niconTmp = " + iconTmp) Currnt_path=savepathini+'SavePose/' newposename=Animpose_name seltab1 = mc.shelfTabLayout('Poses',q=1,st=1) posefold=savepathini+'SavePose/Poses/'+seltab1+'/'+ newposename+'.anim' poseimg_path=savepathini+'SavePose/Poses/'+seltab1+'/' newPoseIconFile = poseimg_path + newposename +".bmp" if mc.file(posefold,q=1,ex=1): Overrite = mc.confirmDialog( title='Confirm Save Pose', message='Overwrite the existing pose: '+newposename+'?', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if Overrite =='No': return mc.sysFile(iconTmp,copy=newPoseIconFile) files=open(posefold,'w') sel_obj = mc.ls(sl=1) for each in sel_obj: splitter = each.split(':') attrs =mc.listAttr(each,k=1,u=1) if(len(attrs)>0): if len(splitter)==1: files.write('obj '+splitter[0]+'\n') else: files.write('obj '+splitter[1]+'\n') for eachattr in attrs: locked = mc.getAttr((each+'.'+eachattr),l=1) if not locked: valStr = mc.getAttr((each+'.'+eachattr)) files.write(eachattr + " " +str(valStr) + '\n') files.close() print "Pose Saved" mc.shelfButton(newposename,i=newPoseIconFile,w=110,h=80,l=newposename,bgc=(.6, .2, .2),st='iconAndTextVertical',p=(seltab1),c=partial(Pose_rtn,posefold)) Refresh_UI(savepathini) mc.shelfTabLayout('tabs',e=1,st=Poses) mc.shelfTabLayout('Poses',e=1,st=seltab1) animposewinclose()
def createTab(self, *args): name = self.nameInput(layout=self.tab, title='Create Tab') if name: layoutName = '%s_%s' % (name, self.colSuffix) # cmds.columnLayout(layoutName, adj=True, ) cmds.gridLayout(layoutName, cellWidthHeight=(self.cel, self.cel), ag=True, cr=True, p=self.tab, aec=False) cmds.setParent('..') cmds.shelfTabLayout(self.tab, e=True, tabLabel=(layoutName, name))
def create(): global shelf if cmds.layoutDialog(ui=shelfQuery) == "Create": cmds.shelfTabLayout('ShelfLayout', edit=True, selectTab=shelf) cmds.shelfButton( label='NI mate receiver', parent=shelf, enableBackground=False, annotation= 'Start/Stop receiving data from NI mate, double click to access preferences.', image='NImateReceiverForMaya.ico', sourceType='python', command= 'import NImateReceiverForMaya\nNImateReceiverForMaya.toggleReceiver()', doubleClickCommand= 'import NImateReceiverForMaya\nNImateReceiverForMaya.showPreferences()' )
def __init__(self): current = m.shelfTabLayout( mayaShelf, q=1, selectTab=1 ) m.popupMenu( mmName, e=1, deleteAllItems=1 ) showEmpty = m.optionVar( q=mmName + 'displayEmpty' ) showSubmn = m.optionVar( q=mmName + 'showSubmn' ) sortRecnt = m.optionVar( q=mmName + 'sortRecnt' ) m.setParent( mmName, menu=1 ) # create a radial menu with your favorites self.inRadial = [] for pos in ['W', 'NW', 'N', 'NE', 'E', 'SE', 'S', 'SW']: item = m.optionVar( q=mmName + pos ) if item: self.inRadial.append(item) label = item if item == current: label = '## ' + label + '##' m.menuItem( label=label, radialPosition=pos, c=lambda null, i=item, p=pos: self.to(null, i, p) ) #italicized=1 ) elif showEmpty: m.menuItem( label='add current here', radialPosition=pos, c=lambda null, pos=pos:self.add(pos) ) # list all the other shelves all = m.shelfTabLayout( mayaShelf, q=1, ca=1 ) all = [i for i in all if i not in self.inRadial] if showSubmn: m.menuItem( label='all ...', subMenu=1 ) self.recent = [] if sortRecnt: if m.optionVar(ex=mmName + 'Recent'): self.recent = m.optionVar(q=mmName + 'Recent').split(',') for r in self.recent: if r in all: all.remove(r) all.insert(0,r) for item in all: label = item if item == current: label = '## ' + item + '##' m.menuItem( label=label, c=lambda null, i=item: self.to(null, i, None) ) if showSubmn: m.setParent( '..', menu=1 ) m.menuItem( divider=True ) m.menuItem( label='settings...', subMenu=1 ) m.menuItem( label='display empty', checkBox=showEmpty, c=lambda null, var='displayEmpty':self.checkVar(null,var) ) m.menuItem( label='submenu', checkBox=showSubmn, c=lambda null, var='showSubmn':self.checkVar(null,var) ) m.menuItem( label='sort by recent use', checkBox=sortRecnt, c=lambda null, var='sortRecnt':self.checkVar(null,var) )
def _shelf_error_fix(self): # FIXES error in shelf.mel. reassigns optionVars for this shelf shelves = cmds.shelfTabLayout( self.layout, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): if shelf == self.name: cmds.optionVar( stringValue=("shelfName{i}".format(i=index+1), str(shelf)) )
def getButtonMenu(buttonMenu, arg=None): #query active shelf and button names mShelf = mc.shelfTabLayout('ShelfLayout', q=1, st=1) buttons = mc.shelfLayout(mShelf, q=1, ca=1) buttonNames = {} if buttons: for bttn in buttons: name = mc.shelfButton(bttn, q=1, l=1) buttonNames[name] = bttn return mShelf, buttonNames
def writeAllTabShelf(self, *args): try: allShelf = [] allShelf = cmds.shelfTabLayout( 'mainShelfTab', q=1, ca=True ) for item in allShelf: self.writeShelf(item) self.saveShelfAll() mm.eval('print "%s";'%self.tip) except: pass
def createShelfButton( command, label, name=None, description='', image='render_useBackground', #this default image is a "!" labelColor=(1, 0.5, 0), labelBackgroundColor=(0, 0, 0, 0.5), backgroundColor=None): ''' Create a shelf button for the command on the current shelf ''' #some good default icons: #menuIconConstraints - ! #render_useBackground - circle #render_volumeShader - black dot #menuIconShow - eye gShelfTopLevel = mm.eval('$temp=$gShelfTopLevel') if not mc.tabLayout(gShelfTopLevel, exists=True): OpenMaya.MGlobal.displayWarning('Shelf not visbile.') return if not name: name = label shelfTab = mc.shelfTabLayout(gShelfTopLevel, query=True, selectTab=True) shelfTab = gShelfTopLevel + '|' + shelfTab #add additional args depending on what version of maya we're in kwargs = dict() if mm.eval('getApplicationVersionAsFloat') >= 2009: kwargs['commandRepeatable'] = True if mm.eval('getApplicationVersionAsFloat') >= 2011: kwargs['overlayLabelColor'] = labelColor kwargs['overlayLabelBackColor'] = labelBackgroundColor if backgroundColor: kwargs['enableBackground'] = bool(backgroundColor) kwargs['backgroundColor'] = backgroundColor image += '.png' else: image += '.xpm' return mc.shelfButton(parent=shelfTab, label=name, command=command, imageOverlayLabel=label, image=image, annotation=description, width=32, height=32, align='center', **kwargs)
def createShelf(): iconPath = os.path.abspath(os.path.join(os.path.dirname(CM_Tools.__file__),".."))+"/Icons/" gShelfTopLevel = maya.mel.eval('global string $gShelfTopLevel; $temp = $gShelfTopLevel;') cmShelf = gShelfTopLevel + '|TurboSquid' if cmds.shelfLayout(cmShelf, exists=True): cmds.deleteUI(cmShelf) if not cmds.shelfLayout(cmShelf, exists=True): cmds.setParent(gShelfTopLevel) cmds.shelfLayout('TurboSquid') else: cmds.setParent(cmShelf) if not cmds.shelfButton('CheckMate', exists=True): checkMateButton = cmds.shelfButton('CheckMate', label='CheckMate', parent = 'TurboSquid', annotation='Run the CheckMate tools on the current scene', image1 = iconPath + 'CheckMatePro.png', command='from CM_Tools import SystemFile;reload(SystemFile);SystemFile.SystemClass()' ) print checkMateButton cmds.shelfTabLayout(gShelfTopLevel, e=True, st='TurboSquid') cmds.saveAllShelves(gShelfTopLevel)
def create_shelf(): """ create the dmptools shelf """ # delete the shelf is already exists if cmds.shelfLayout(SHELF_NAME, ex=True): fullname = cmds.shelfLayout('dmptools', fpn=True, q=True) cmds.deleteUI(fullname) # create the shelf shelfParent = cmds.shelfTabLayout('ShelfLayout', fpn=True, q=True) shelf = cmds.shelfLayout(SHELF_NAME, p=shelfParent) # add shelf buttons for item in SHELF_ITEMS: if 'separator' in item['name']: # defaultPrint(__name__+' : creating button '+item['name']+'...') add_separator(item, shelf) else: # defaultPrint(__name__+' : creating button '+item['name']+'...') add_button(item, shelf) # select the last created shelf i = cmds.shelfTabLayout(shelfParent, numberOfChildren=True, q=True) cmds.shelfTabLayout(shelfParent, selectTabIndex=i, e=True) # save the shelf cmds.saveShelf(SHELF_NAME, SHELF_FILE)
def vis(*args): select_tab=mc.shelfTabLayout('tabs',q=1,sti=1) if select_tab==2: mc.text('ST',e=1,en=0) mc.text('ET',e=1,en=0) mc.floatField('Start_F',e=1,en=0) mc.floatField('End_F',e=1,en=0) else: mc.text('ST',e=1,en=1) mc.text('ET',e=1,en=1) mc.floatField('Start_F',e=1,en=1) mc.floatField('End_F',e=1,en=1)
def load_shelf(shelf_path): ''' load Maya shelf :param shelf_path: string: file path to maya shelf ''' if mayaIsBatch(): return # get current top shelf gShelfTopLevel = mel.eval("string $shelf_ly=$gShelfTopLevel") top=cmds.shelfTabLayout(gShelfTopLevel, q=True, st=True) if os.path.exists(shelf_path): print shelf_path mel.eval('source "%s"' % shelf_path) mel.eval('loadNewShelf("%s")' % shelf_path) log.info('Shelf loaded: % s' % shelf_path) return True else: log.error('Cant load shelf, file doesnt exist: %s' % shelf_path) # restore users top shelf cmds.shelfTabLayout(gShelfTopLevel, e=True, st=top)
def poseMangerWindow(self): import maya.cmds as mc if mc.windowPref('poseMangerWin', exists=1): mc.windowPref('poseMangerWin', remove=1) if mc.window('poseMangerWin', exists=1): mc.deleteUI('poseMangerWin') mc.window('poseMangerWin', t='PoseManger_Mudan', wh=(960, 430), menuBar=True) mc.menu( label=u'文件', tearOff=True ) mc.menuItem( label=u'新建通用pose文件', c=showUI ) self.mainShelf = cmds.shelfTabLayout( 'mainMeShelfTab', image='smallTrash.png', imageVisible=True ) self.shelfLayoutOnly() mc.setParent('..') mc.setParent('..') mc.showWindow()
def newScriptEditor(): """ simpler script editor test """ win = cmds.window(t='New Script Editor', menuBar= True, w = 650, h = 300) form = cmds.formLayout() pane = cmds.paneLayout(configuration='horizontal2', paneSize=[[1,100,40],[2,100,60]]) # top layout formTop = cmds.formLayout() reporter = cmds.cmdScrollFieldReporter('reporter') cmds.setParent('..') cmds.formLayout(formTop, e=True, attachForm=\ [ (reporter, "top", 5), (reporter, "bottom", 5), (reporter, "left", 5), (reporter, "right", 5), ] ) cmds.paneLayout(pane, edit=True, setPane = [formTop, 2]) # bottom layout formBottom = cmds.formLayout() shelf = cmds.shelfTabLayout() tab1 = cmds.cmdScrollFieldExecuter('python1', sourceType="python") cmds.setParent('..') cmds.formLayout(formBottom, e=True, attachForm=\ [ (shelf, "top", 5), (shelf, "bottom", 5), (shelf, "left", 5), (shelf, "right", 5), ] ) cmds.paneLayout(pane, edit=True, setPane = [formTop, 1]) cmds.formLayout(form, e=True, attachForm=\ [ (pane, "top", 5), (pane, "bottom", 5), (pane, "left", 5), (pane, "right", 5), ] ) cmds.showWindow()
def clear(*args): posesel=[] seltab = mc.shelfTabLayout('tabs',q=1,st=1) seltab1= mc.shelfTabLayout(seltab,q=1,st=1) seltab2= mc.shelfLayout(seltab1,q=1,ca=1) if seltab2==None : NoTab(seltab) else: confirm=mc.confirmDialog(message='Do you want to delete all '+seltab+' in the selected tab ?', ma='center', button=['Yes','No'] ,defaultButton='Yes',cancelButton='No',dismissString='No') if confirm=='Yes': seltab1= mc.shelfTabLayout(seltab,q=1,st=1) #seltab2= mc.shelfLayout(seltab1,q=1,ca=1) posesel= mc.shelfLayout(seltab1,q=1,ca=1) for i in range (len(posesel)): print posesel[i] mc.deleteUI(posesel[i]) #return deletefold=savepathini+'savepose/'+seltab+'/'+seltab1+'/' seltab1= mc.shelfTabLayout(seltab,q=1,st=1) list_in=mc.getFileList(fld=deletefold) for i in range(len(list_in)): mc.sysFile(deletefold+list_in[i],delete=1)
def poseMangerWindow(self): import maya.cmds as mc if mc.windowPref("poseMangerWin", exists=1): mc.windowPref("poseMangerWin", remove=1) if mc.window("poseMangerWin", exists=1): mc.deleteUI("poseMangerWin") mc.window("poseMangerWin", t="PoseManger_Mudan", wh=(960, 430), menuBar=True) mc.menu(label=u"文件", tearOff=True) mc.menuItem(label=u"新建通用pose文件", c=showUI) self.mainShelf = cmds.shelfTabLayout("mainMeShelfTab", image="smallTrash.png", imageVisible=True) self.shelfLayoutOnly() mc.setParent("..") mc.setParent("..") mc.showWindow()
def create(): if cmds.shelfLayout(shelf_name, exists=True, q=True): cmds.deleteUI(shelf_name) cmds.setParent(main_shelf_parent) cmds.shelfLayout(shelf_name) populate_shelf(shelf_name, button_list) # fix stupid maya error with shelves generated via python top_level_shelf = mel.eval('string $m = $gShelfTopLevel') shelves = cmds.shelfTabLayout(top_level_shelf, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=('shelfName%d' % (index+1), str(shelf)))
def load_shelf(shelf_path): ''' load Maya shelf :param shelf_path: string: file path to maya shelf ''' if mayaIsBatch(): return # get current top shelf gShelfTopLevel = mel.eval("string $shelf_ly=$gShelfTopLevel") top = cmds.shelfTabLayout(gShelfTopLevel, q=True, st=True) if os.path.exists(shelf_path): #print shelf_path delete_shelf(shelf_path) mel.eval('source "%s"' % shelf_path) mel.eval('loadNewShelf("%s")' % shelf_path) log.info('Shelf loaded: % s' % shelf_path) return True else: log.error('Cant load shelf, file doesnt exist: %s' % shelf_path) # restore users top shelf cmds.shelfTabLayout(gShelfTopLevel, e=True, st=top)
def detachShelf(): """ Detaches the current shelves IN PROGRESS """ shelfTopLevel = mel.eval('$tempMelVar=$gShelfTopLevel') shelfName = cmds.shelfTabLayout(shelfTopLevel, st=True, q=True) shelfPaths = os.path.abspath(cmds.internalVar(ush=True)).split(';') shelfFile = "shelf_{0}.mel".format(shelfName) shelfFilePath = "" for shelfPath in shelfPaths: files = os.listdir(shelfPath) if shelfFile in files: shelfFilePath = os.path.join(shelfPath, shelfFile) print(shelfFilePath)
def create(): if cmds.shelfLayout(shelf_name, exists=True, q=True): cmds.deleteUI(shelf_name) cmds.setParent(main_shelf_parent) cmds.shelfLayout(shelf_name) populate_shelf(shelf_name, button_list) # fix stupid maya error with shelves generated via python top_level_shelf = mel.eval('string $m = $gShelfTopLevel') shelves = cmds.shelfTabLayout(top_level_shelf, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=('shelfName%d' % (index + 1), str(shelf)))
def createShelfButton(command, label='', name=None, description='', image=None, #the default image is a circle labelColor=(1, 0.5, 0), labelBackgroundColor=(0, 0, 0, 0.5), backgroundColor=None ): ''' Create a shelf button for the command on the current shelf ''' #some good default icons: #menuIconConstraints - ! #render_useBackground - circle #render_volumeShader - black dot #menuIconShow - eye gShelfTopLevel = mm.eval('$temp=$gShelfTopLevel') if not mc.tabLayout(gShelfTopLevel, exists=True): OpenMaya.MGlobal.displayWarning('Shelf not visible.') return if not name: name = label if not image: image = getIcon(name) if not image: image = 'render_useBackground' shelfTab = mc.shelfTabLayout(gShelfTopLevel, query=True, selectTab=True) shelfTab = gShelfTopLevel+'|'+shelfTab #add additional args depending on what version of maya we're in kwargs = dict() if mm.eval('getApplicationVersionAsFloat') >= 2009: kwargs['commandRepeatable'] = True if mm.eval('getApplicationVersionAsFloat') >= 2011: kwargs['overlayLabelColor'] = labelColor kwargs['overlayLabelBackColor'] = labelBackgroundColor if backgroundColor: kwargs['enableBackground'] = bool(backgroundColor) kwargs['backgroundColor'] = backgroundColor return mc.shelfButton(parent=shelfTab, label=name, command=command, imageOverlayLabel=label, image=image, annotation=description, width=32, height=32, align='center', **kwargs)
def initializePlugin(mobject): """Initialization method for Maya Autodesk plugin system; creates new shelf and registers each command.""" # make sure the plug-in path is actually found by the python interpreter if (not len([p for p in sys.path if re.search('plug-ins', p)])): if (sys.platform == "linux" or sys.platform == "linux2"): sys.path.append([p for p in sys.path if re.search('bin$', p)][0] + '/plug-ins') else: sys.path.append([p for p in sys.path if re.search('bin$', p)][0] + '\\plug-ins') # import all sub-modules from directory 'pk_src' (print to console in case of error) for cmd in kPluginCmdName: try: exec('from pk_src import ' + cmd) except: sys.stderr.write("Could not find module 'pk_src.%s'\n" % cmd) # force reload of modules to avoid having maya to restart every time a class definition changes for cmd in kPluginCmdName: try: reload(sys.modules["pk_src." + cmd]) except: sys.stderr.write("Error reloading " + cmd) # get maya plugin module mplugin = OpenMayaMPx.MFnPlugin(mobject) mplugin.setVersion(pk_version) # get top level shelf to create new shelf layout where each command gets its own button to execute command topShelf = mel.eval('$nul = $gShelfTopLevel') # check if old reference still exists and delete it if (cmds.shelfLayout("ProKlaue", exists = 1)): cmds.deleteUI("ProKlaue", lay = 1) # create new shelf layout proKlaue proKlaue = cmds.shelfLayout("ProKlaue", parent = topShelf) # maya messes up the shelf optionVars shelfName1 --> recreate shelf names shelves = cmds.shelfTabLayout(topShelf, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=("shelfName%d" % (index+1), str(shelf))) # register commands and add buttons to shelf for cmd in kPluginCmdName: try: mplugin.registerCommand( cmd, eval(cmd + "." + cmd + "Creator"), eval(cmd + "." + cmd + "SyntaxCreator") ) exec(cmd + ".addButton('%s')" %(proKlaue)) except: sys.stderr.write("Failed to register command or to add shelf button: %s\n" % cmd)
def build(self): self.loadShelfAll() if cmds.window( 'speedWin', ex=1 ): cmds.deleteUI( 'speedWin' ) if cmds.windowPref( 'speedWin', ex=1 ): cmds.windowPref( 'speedWin', remove=1 ) cmds.window( 'speedWin', t='SpeedTool', wh=(350, 260), menuBar=True) cmds.menu( label=u'文件', tearOff=True ) cmds.menuItem( label=u'新建', c=self.newTab ) cmds.menuItem( label=u'删除', c=self.deleteTabShelf ) cmds.menuItem( label=u'保存' ,c=self.writeAllTabShelf) #cmds.menuItem( label=u'保存工具架' ,c=self.saveShelfAll) #cmds.menuItem( label='Save' ) self.mainShelf = cmds.shelfTabLayout( 'mainShelfTab', image='smallTrash.png', imageVisible=True ) #self.shelf = cmds.shelfLayout( 'Tools', cwh=(35, 35) ) #self.newTab() #cmds.shelfButton('save',imageOverlayLabel="save", i1='menuIconWindow.png', c=self.writeShelf) self.updateShelf() cmds.setParent( '..' ) cmds.setParent( '..' ) cmds.showWindow('speedWin')
def export_active_shelf(): ''' Export the currently active shelf as a yaml file ''' shelf_top_level = mel.eval('$temp_mel_var = $gShelfTopLevel;') active_shelf = cmds.shelfTabLayout(shelf_top_level, query=True, selectTab=True) active_shelf_buttons = cmds.shelfLayout(active_shelf, query=True, childArray=True) shelf_data = list() for button in active_shelf_buttons: shelf_data.append(_get_shelf_item_data(button)) yaml_file = cmds.fileDialog2(fileFilter='YAML Shelves(*.yaml *.yml)', fileMode=0) if not yaml_file: return yaml_file = _sanitize_path(yaml_file[0]) with codecs.open(yaml_file, 'w', encoding='utf-8') as f_out: yaml.safe_dump(shelf_data, f_out)
def createShelf(shelfFileName): """Create a shelf""" # pylint: disable=undefined-loop-variable shortFileName = os.path.basename(shelfFileName) shortName = shortFileName.replace(".mel", "") shelfName = shortName.replace("shelf_", "") # Find if a copy of gfTools shelf is in prefs folder shelfDirs = cmds.internalVar(ush=True).split(os.pathsep) for shelfDir in shelfDirs: if (shelfDir.startswith(cmds.internalVar(upd=True)) and shelfDir.endswith("prefs/shelves/")): # We have found the shelves directory break if not os.path.isfile(os.path.join(shelfDir, "%s.deleted" % shortFileName)): mel.eval('source "%s";' % shelfFileName) gShelfForm = mel.eval("$tmpVar = $gShelfForm") gShelfTopLevel = mel.eval("$tmpVar = $gShelfTopLevel") cmds.setParent(gShelfTopLevel) shelfHeight = cmds.tabLayout(gShelfTopLevel, q=True, h=True) cmds.tabLayout(gShelfTopLevel, e=True, vis=False) cmds.setParent(gShelfForm) spacingSeparator = cmds.separator(h=shelfHeight, st="single") cmds.formLayout(gShelfForm, e=True, af=[(spacingSeparator, "top", 0), (spacingSeparator, "left", 0), (spacingSeparator, "bottom", 0), (spacingSeparator, "right", 0)]) cmds.tabLayout(gShelfTopLevel, e=True, m=False) cmds.setParent(gShelfTopLevel) newShelfName = cmds.shelfLayout(shelfName) # Match the style of the other tabs kids = cmds.tabLayout(gShelfTopLevel, q=True, ca=True) if len(kids) > 0: style = cmds.shelfLayout("%s|%s" % (gShelfTopLevel, kids[0]), q=True, style=True) else: style = cmds.optionVar(q="shelfItemStyle") mel.eval('shelfStyle %s "Small" %s' % (style, newShelfName)) cmds.tabLayout(gShelfTopLevel, e=True, m=True, vis=True) shelves = cmds.tabLayout(gShelfTopLevel, q=True, ca=True) curShelfName = shelves[len(shelves) - 1] cmds.deleteUI(spacingSeparator) # Do that preferences thing nShelves = cmds.shelfTabLayout(gShelfTopLevel, q=True, nch=True) cmds.optionVar(iv=("shelfLoad%s" % nShelves, 0), sv=[("shelfName%s" % nShelves, curShelfName), ("shelfAlign%s" % nShelves, "left"), ("shelfFile%s" % nShelves, "shelf_%s" % curShelfName)]) # Save shelf file to shelves directory saveCmd = 'import maya.cmds as cmds; cmds.saveShelf("%s", "%sshelf_%s")' % ( newShelfName, shelfDir, curShelfName) cmds.evalDeferred(saveCmd) cmds.tabLayout(gShelfTopLevel, e=True, st=curShelfName) # Set the current shelf option var shelfNum = cmds.tabLayout(gShelfTopLevel, q=True, sti=True) cmds.optionVar(iv=["selectedShelf", shelfNum]) return curShelfName
def load(shelf_path=None): # Default to the Maya shelf path. if shelf_path is None: shelf_path = os.environ.get('MAYA_SHELF_PATH') shelf_path = shelf_path.split(':') if shelf_path else [] # Single strings should be a list. if isinstance(shelf_path, basestring): shelf_path = [shelf_path] # Clear out the button memory. _uuid_to_buttons.clear() # Lookup the tab shelf that we will attach to. layout = mel.eval('$tmp=$gShelfTopLevel') # Store shelf options for restoring later. existing_options = {} for i, name in enumerate( cmds.shelfTabLayout(layout, q=True, childArray=True)): if name in existing_options: cmds.warning( 'Multiple shelves with name "%s"? This may cause problems.' % name) existing_options[name] = opts = {} for key in 'Name', 'File', 'Load': opts[key] = cmds.optionVar(q="shelf%s%d" % (key, i + 1)) new_shelves = set() for shelf_dir in shelf_path: try: file_names = sorted(os.listdir(shelf_dir)) except IOError: continue for file_name in file_names: if file_name.startswith('.') or file_name.startswith( '_') or not file_name.endswith('.yml'): continue shelf_name = file_name[:-4] new_shelves.add(shelf_name) print '# %s: %s' % (__name__, shelf_name) # Delete buttons on existing shelves, and create shelves that don't # already exist. if cmds.shelfLayout(shelf_name, q=True, exists=True): # Returns None if not loaded yet, so be careful. for existing_button in cmds.shelfLayout( shelf_name, q=True, childArray=True) or []: cmds.deleteUI(existing_button) cmds.setParent(layout + '|' + shelf_name) else: cmds.setParent(layout) cmds.shelfLayout(shelf_name) for b_i, button in enumerate( _iter_buttons(os.path.join(shelf_dir, file_name))): button_definition = copy.deepcopy(button) # Defaults and basic setup. button.setdefault('width', 34) button.setdefault('height', 34) # Extract keys to remember buttons. uuids = [button.get('entrypoint'), button.pop('uuid', None)] # Extract other commands. doubleclick = button.pop('doubleclick', None) popup_menu = button.pop('popup_menu', None) context_menu = button.pop('context_menu', None) convert_entrypoints(button) # Create the button! try: button_definition['name'] = button_name = cmds.shelfButton( **button) except TypeError: print button raise # Save the button for later. for uuid in uuids: if uuid: _uuid_to_buttons.setdefault( uuid, []).append(button_definition) # Add a doubleclick action if requested. if doubleclick: convert_entrypoints(doubleclick) # Only pass through the two keywords that are allowed. doubleclick = dict((k, v) for k, v in doubleclick.iteritems() if k in ('command', 'sourceType')) # Adapt to a doubleclick. doubleclick['doubleClickCommand'] = doubleclick.pop( 'command') cmds.shelfButton(button_name, edit=True, **doubleclick) # Add a popup menu if requested. if popup_menu: setup_menu(shelf_button=button_name, button=1, **popup_menu) if context_menu: setup_menu(shelf_button=button_name, button=3, **context_menu) # Clean up persistant shelf options; Maya (and plugins) will freak out at us if we don't. for i, name in enumerate( cmds.shelfTabLayout(layout, q=True, childArray=True)): if name in new_shelves: cmds.optionVar(stringValue=(("shelfName%d" % (i + 1)), name)) cmds.optionVar(stringValue=(("shelfFile%d" % (i + 1)), '')) cmds.optionVar(intValue=(("shelfLoad%d" % (i + 1)), 1)) # Signal that it is loaded. continue opts = existing_options.get(name) if opts: cmds.optionVar(stringValue=(("shelfName%d" % (i + 1)), opts['Name'])) cmds.optionVar(stringValue=(("shelfFile%d" % (i + 1)), opts['File'])) cmds.optionVar(intValue=(("shelfLoad%d" % (i + 1)), opts['Load'])) continue cmds.warning('New shelf "%s" appeared.' % name) cmds.optionVar(intValue=('numShelves', i + 1)) # Finally, we need to save them all to the users' home. If we don't, and # another plugin (e.g. RenderMan) saves its own shelf, then on reload that # will be the only shelf which exists. cmds.saveAllShelves(layout)
def dump(shelves=None, shelf_dir=None, image_dir=None): if shelf_dir is None: shelf_dir = os.path.abspath(os.path.join(__file__, '..', '..', 'shelf')) if image_dir is None: image_dir = os.path.abspath(os.path.join(__file__, '..', '..', 'icons')) attributes = dict( imageOverlayLabel='', annotation='', enableCommandRepeat=True, enable=True, width=set((32, 34, 35)), height=set((32, 34, 35)), manage=True, visible=True, preventOverride=False, align='center', label='', labelOffset=0, font='plainLabelFont', image='', style='iconOnly', marginWidth=1, marginHeight=1, command='', sourceType='', actionIsSubstitute=False, ) layout = mel.eval('$tmp=$gShelfTopLevel') if shelves is None: shelves = cmds.shelfTabLayout(layout, q=True, childArray=True) elif isinstance(shelves, basestring): shelves = [shelves] for shelf in shelves: buttons = cmds.shelfLayout(shelf, q=True, childArray=True) if not buttons: print '# Shelf not loaded:', shelf continue path = os.path.join(shelf_dir, shelf) + '.yml' with open(path, 'w') as file: for button in buttons: print shelf, button data = dict() for attr, default in attributes.iteritems(): value = cmds.shelfButton(button, q=True, **{attr: True}) if isinstance(value, basestring): value = str(value) if value != default and not (isinstance(default, set) and value in default): data[attr] = value # Convert images to icon names. image = data.pop('image', '') if image: if image.startswith(image_dir): image = image[len(image_dir):].strip('/') data['image'] = image type_ = data.pop('sourceType') data[type_] = data.pop('command', None) if type_ == 'python': source = data.pop('python') # from key_core import key_ui;reload(key_ui);key_ui.saveSelectedWin() if source: m = re.match( r'^from ([\w.]+) import (\w+) (?:;|,|\n) (?:reload\(\2\) (?:;|,|\n))? \2.(\w+)\(\) ;?$' .replace(' ', r'\s*'), source) if m: data['entrypoint'] = '%s.%s:%s' % m.groups() if 'reload(' in source: data['reload'] = True source = None if source: m = re.match( r'^from ([\w.]+) import (\w+) as \w+ (?:;|,|\n) (?:reload\(\w+\) (?:;|,|\n))? \w+.(\w+)\(\) ;?$' .replace(' ', r'\s*'), source) if m: data['entrypoint'] = '%s.%s:%s' % m.groups() if 'reload(' in source: data['reload'] = True source = None if source: data['python'] = source file.write( yaml.dump( data, explicit_start=True, indent=4, default_flow_style=False, ))
def get_existing_shelf_tabs(): return mc.shelfTabLayout(SHELF_LAYOUT, query=True, childArray=True) or []
def load(shelf_path=None): # Default to the Maya shelf path. if shelf_path is None: shelf_path = os.environ.get('MAYA_SHELF_PATH') shelf_path = shelf_path.split(':') if shelf_path else [] # Single strings should be a list. if isinstance(shelf_path, basestring): shelf_path = [shelf_path] # Clear out the button memory. _uuid_to_buttons.clear() # Lookup the tab shelf that we will attach to. layout = mel.eval('$tmp=$gShelfTopLevel') shelf_names = set() for shelf_dir in shelf_path: try: file_names = sorted(os.listdir(shelf_dir)) except IOError: continue for file_name in file_names: if file_name.startswith('.') or file_name.startswith('_') or not file_name.endswith('.yml'): continue shelf_name = file_name[:-4] shelf_names.add(shelf_name) print '# %s: %s' % (__name__, shelf_name) # Delete buttons on existing shelves, and create shelves that don't # already exist. if cmds.shelfLayout(shelf_name, q=True, exists=True): # Returns None if not loaded yet, so be careful. for existing_button in cmds.shelfLayout(shelf_name, q=True, childArray=True) or []: cmds.deleteUI(existing_button) cmds.setParent(layout + '|' + shelf_name) else: cmds.setParent(layout) cmds.shelfLayout(shelf_name) for b_i, button in enumerate(_iter_buttons(os.path.join(shelf_dir, file_name))): button_definition = copy.deepcopy(button) # Defaults and basic setup. button.setdefault('width', 34) button.setdefault('height', 34) button.setdefault('image1', 'pythonFamily.png') # Extract keys to remember buttons. uuids = [button.get('entrypoint'), button.pop('uuid', None)] # Extract other commands. doubleclick = button.pop('doubleclick', None) popup_menu = button.pop('popup_menu', None) context_menu = button.pop('context_menu', None) convert_entrypoints(button) # Create the button! try: button_definition['name'] = button_name = cmds.shelfButton(**button) except TypeError: print button raise # Save the button for later. for uuid in uuids: if uuid: _uuid_to_buttons.setdefault(uuid, []).append(button_definition) # Add a doubleclick action if requested. if doubleclick: convert_entrypoints(doubleclick) # Only pass through the two keywords that are allowed. doubleclick = dict((k, v) for k, v in doubleclick.iteritems() if k in ('command', 'sourceType')) # Adapt to a doubleclick. doubleclick['doubleClickCommand'] = doubleclick.pop('command') cmds.shelfButton(button_name, edit=True, **doubleclick) # Add a popup menu if requested. if popup_menu: setup_menu(shelf_button=button_name, button=1, **popup_menu) if context_menu: setup_menu(shelf_button=button_name, button=3, **context_menu) # Reset all shelf "options"; Maya will freak out at us if we don't. for i, name in enumerate(cmds.shelfTabLayout(layout, q=True, childArray=True)): if name in shelf_names: cmds.optionVar(stringValue=(("shelfName%d" % (i + 1)), shelf_name))
def dump(shelves=None, shelf_dir=None, image_dir=None): if shelf_dir is None: shelf_dir = os.path.abspath(os.path.join(__file__, '..', '..', 'shelf')) if image_dir is None: image_dir = os.path.abspath(os.path.join(__file__, '..', '..', 'icons')) attributes = dict( imageOverlayLabel='', annotation='', enableCommandRepeat=True, enable=True, width=set((32, 34, 35)), height=set((32, 34, 35)), manage=True, visible=True, preventOverride=False, align='center', label='', labelOffset=0, font='plainLabelFont', image='', style='iconOnly', marginWidth=1, marginHeight=1, command='', sourceType='', actionIsSubstitute=False, ) layout = mel.eval('$tmp=$gShelfTopLevel') if shelves is None: shelves = cmds.shelfTabLayout(layout, q=True, childArray=True) elif isinstance(shelves, basestring): shelves = [shelves] for shelf in shelves: buttons = cmds.shelfLayout(shelf, q=True, childArray=True) if not buttons: print '# Shelf not loaded:', shelf continue path = os.path.join(shelf_dir, shelf) + '.yml' with open(path, 'w') as file: for button in buttons: print shelf, button data = dict() for attr, default in attributes.iteritems(): value = cmds.shelfButton(button, q=True, **{attr: True}) if isinstance(value, basestring): value = str(value) if value != default and not (isinstance(default, set) and value in default): data[attr] = value # Convert images to icon names. image = data.pop('image', '') if image: if image.startswith(image_dir): image = image[len(image_dir):].strip('/') data['image'] = image type_ = data.pop('sourceType') data[type_] = data.pop('command', None) if type_ == 'python': source = data.pop('python') # from key_core import key_ui;reload(key_ui);key_ui.saveSelectedWin() if source: m = re.match(r'^from ([\w.]+) import (\w+) (?:;|,|\n) (?:reload\(\2\) (?:;|,|\n))? \2.(\w+)\(\) ;?$'.replace(' ', r'\s*'), source) if m: data['entrypoint'] = '%s.%s:%s' % m.groups() if 'reload(' in source: data['reload'] = True source = None if source: m = re.match(r'^from ([\w.]+) import (\w+) as \w+ (?:;|,|\n) (?:reload\(\w+\) (?:;|,|\n))? \w+.(\w+)\(\) ;?$'.replace(' ', r'\s*'), source) if m: data['entrypoint'] = '%s.%s:%s' % m.groups() if 'reload(' in source: data['reload'] = True source = None if source: data['python'] = source file.write(yaml.dump(data, explicit_start=True, indent=4, default_flow_style=False, ))
def installToolboxWindow(): installForm = cmds.formLayout() textLabel = cmds.text(label='Shelf') nameText = cmds.textField('nameText', width=200, tx='Custom') scriptsMenu = cmds.optionMenu('scriptsMenu') jsonPathText = cmds.textField('jsonPathText', ed=False, pht='path to json') jsonPathBtn = cmds.button('jsonPathBtn', width=50, label='...', c='browseForFile()') separator = ';' if cmds.about(nt=True) else ':' scriptsPaths = os.getenv('MAYA_SCRIPT_PATH') allparts = scriptsPaths.split(separator) for i, part in enumerate(allparts): if (i == 0): cmds.menuItem(label='Manually install scripts') if (i < 7): isSystemPath = FilterOutSystemPaths(part) if (isSystemPath == 0): cmds.menuItem(label=part) iconsMenu = cmds.optionMenu('iconsMenu') iconsPaths = os.getenv('XBMLANGPATH') iconsParts = iconsPaths.split(separator) for i, part in enumerate(iconsParts): if (i < 6): isSystemPath = FilterOutSystemPaths(part) if (isSystemPath == 0): cmds.menuItem(label=part) progressControl = cmds.progressBar('progressControl', maxValue=10, vis=False, width=250) btn1 = cmds.button(height=50, label='Install', c='CheckText()') btn2 = cmds.button(height=50, label='Close', c='cmds.deleteUI(\'Install Toolbox\')') listLayout = cmds.columnLayout('listLayout', adjustableColumn=True) try: dirname = os.path.dirname(__file__) except: print 'running in test environment' dirname = 'C:/Users/Admin/Documents/Toolbox' JSONPath = dirname + '/toolboxShelf.json' try: data = json.load(open(JSONPath), object_pairs_hook=OrderedDict) cmds.textField('jsonPathText', e=True, text=JSONPath) for k in data: cb = cmds.checkBox(h=20, label=k, v=1) try: if data[k]["checkStatus"] == 0: cmds.checkBox(cb, e=True, v=0) if data[k]["checkStatus"] == 2: cmds.checkBox(cb, e=True, v=1, ed=0) except: pass except: pass cmds.formLayout(installForm, edit=True, attachForm=[(textLabel, 'top', 15), (textLabel, 'left', 10), (nameText, 'top', 10), (nameText, 'right', 10), (scriptsMenu, 'right', 10), (iconsMenu, 'right', 10), (jsonPathBtn, 'right', 10), (progressControl, 'left', 10), (progressControl, 'right', 10), (btn1, 'bottom', 0), (btn1, 'left', 0), (btn2, 'bottom', 0), (btn2, 'right', 0)], attachControl=[(nameText, 'left', 10, textLabel), (scriptsMenu, 'top', 10, textLabel), (scriptsMenu, 'left', 10, textLabel), (iconsMenu, 'top', 10, scriptsMenu), (iconsMenu, 'left', 10, textLabel), (jsonPathText, 'top', 10, iconsMenu), (jsonPathBtn, 'top', 10, iconsMenu), (jsonPathText, 'left', 10, textLabel), (jsonPathText, 'right', 10, jsonPathBtn), (progressControl, 'top', 20, jsonPathText), (progressControl, 'left', 10, textLabel), (listLayout, 'top', 20, jsonPathText), (listLayout, 'left', 10, textLabel), (btn2, 'left', 0, btn1)], attachPosition=[(btn1, 'right', 0, 50)]) shelfName = '' #get current tab names = cmds.layout('ShelfLayout', q=True, ca=True) shelfIndex = cmds.shelfTabLayout('ShelfLayout', query=True, selectTabIndex=True) #set text selectionString = (names[shelfIndex - 1]) cmds.textField(nameText, edit=True, tx=selectionString)
def AnimPoseLib(): global tabs,Animation,Poses,pathfolders,pathfolder,savepathini,User_Name,tmpfile,seltabs,seltab if mc.window ('MainWin',q=True,exists =1): mc.deleteUI ('MainWin') if mc.windowPref ('MainWin',q=True,exists = 1): mc.windowPref ('MainWin',remove = 1) posewin=mc.window('MainWin',menuBar=True, title="SR_AnimPoseLib",width=400,mxb=0) User_Name = os.getenv('USERNAME') savepathini='C:/Documents and Settings/'+ User_Name + '/My Documents/' mc.menu( label='File', tearOff=True ) mc.menuItem( label='Open Savepose Folder',c=lambda event:openfolder(savepathini)) mc.menuItem( label='Refresh',c=lambda event:Refresh_UI(savepathini)) mc.menu( label='Tabs', tearOff=True ) mc.menuItem( label='New Tab',c=partial(Newtab)) mc.menuItem( label='Delete Tab',c=partial(deletetab)) mc.menuItem( label='Rename Tab',c=partial(renametab)) mc.menuItem( label='Clear All ',c=partial(clear)) mc.menu('chgFld',label='Folder',tearOff=True) mc.menuItem(label='Change Savepose Folder ',c=lambda event:savefolder(savepathini)) mc.menuItem(d=True) newpath=[savepathini] mc.menuItem( label='My Douments ',c=partial(changepath,newpath)) mc.menu( label='Help', helpMenu=True,tearOff=True ) mc.menuItem( label='About..!' ,c=partial(About)) mc.frameLayout( label='',fn='boldLabelFont', borderStyle='etchedIn') mc.separator(style='none',height = 2 ) mc.rowColumnLayout(numberOfColumns=5,cw=[(1,70),(2,60),(3,70),(4,40),(5,125)],cs=[(1,30),(5,40)]) mc.text('ST',label='Start frame:') Start_F = mc.floatField('Start_F',precision=2) mc.text( 'ET',label='End frame:') End_F = mc.floatField('End_F',precision=2) mc.floatField('Start_F', edit=True, enterCommand=('mc.setFocus(\"' + End_F + '\")') ) mc.floatField('End_F', edit=True, enterCommand=('mc.setFocus(\"' + Start_F + '\")') ) mc.button(label='Save (Anim/Pose)',c=partial(savepose),h=35 ) mc.setParent( '..' ) mc.rowColumnLayout(numberOfColumns=2,cw=[(1,130)]) mc.text(label='Location : ',align='right',fn='boldLabelFont') mc.text('Path',label=' Local Folder',align='left',fn='smallFixedWidthFont') mc.setParent( '..' ) form = mc.formLayout() tabs = mc.shelfTabLayout('tabs',innerMarginWidth=5, innerMarginHeight=5,cc=partial(vis)) mc.formLayout(form,edit=True, attachForm=((tabs, 'top', 0), (tabs, 'left', 15), (tabs, 'bottom', 15), (tabs, 'right', 15)) ) Animation = mc.shelfTabLayout('Animation',innerMarginWidth=5, innerMarginHeight=5,bgc=(0.3,0.3,0.3),h=237) mc.setParent('..') Poses = mc.shelfTabLayout('Poses',innerMarginWidth=5, innerMarginHeight=5,bgc=(0.3,0.3,0.3),h=237,p=tabs) mc.setParent('..') mc.setParent('..') mc.setParent('..') mc.text(l='Sreekanth.S.R ',fn="smallBoldLabelFont",al='right') mc.window (posewin,e=1,wh=(500,410)) mc.showWindow() shelfpath=[] posepath=[] savepath =(savepathini + 'SavePose/') mc.sysFile(savepath, makeDir=True ) shelfpath= mc.getFileList (folder=savepath) Anim_count=shelfpath.count('Animation') Pose_count=shelfpath.count('Poses') Tmp_count =shelfpath.count('tmp.anim') if not Tmp_count: tmpfile=savepath+'tmp.anim' field=open(tmpfile,'w') field.write('Currnt dir \n'+savepathini) field.close() if Tmp_count: tmpfile=savepath+'tmp.anim' field=open(tmpfile,'r+') line=field.readline() if line[0:3]=='Cur' : line=field.readline() savepathini=line.strip() line=field.readline() if line[0:3]=='Run': line=field.readline() while(line != '}'): mc.menuItem(label=line.strip(),p='chgFld',c=partial(savedpath,line)) line=field.readline() field.close() Refresh_UI(savepathini)
def Refresh_UI(savepathini,*args): mc.text('Path',e=1,l=savepathini) S_val=mc.playbackOptions(q=1,min=1) E_val=mc.playbackOptions(q=1,max=1) mc.floatField('End_F',e=1,v=E_val) mc.floatField('Start_F',e=1,v=S_val) savepath =(savepathini + 'SavePose/') #imgpath = savepath + 'tmp_images/' mc.sysFile(savepath, makeDir=True ) posepath = (savepath + 'Animation/') posepath1= (savepath + 'Poses/') shelfpath= mc.getFileList (folder=savepath) Anim_count=shelfpath.count('Animation') Pose_count=shelfpath.count('Poses') if Anim_count==0 or Pose_count==0: mc.confirmDialog (title='Warning',message='No saved poses exist. A Default folders will\n be created when you save for the first time', button='OK',defaultButton='Yes') tabsanim,tabsanim1=[],[] tabsanim=mc.getFileList(folder=posepath) tabsanim1=mc.getFileList(folder=posepath1) Anim_tabs=mc.shelfTabLayout('Animation',q=1,ca=1) Pose_tabs=mc.shelfTabLayout('Poses',q=1,ca=1) if Anim_tabs or Pose_tabs : mc.deleteUI(Anim_tabs,Pose_tabs) if tabsanim: for each in tabsanim: sh=mc.shelfLayout(each,p=Animation,st="iconAndTextVertical") mc.setParent('..') posetabs=(posepath + each + "/") poses = mc.getFileList (fld =posetabs,fs="*.anim") # imges = mc.getFileList (fld =posetabs,fs="*.bmp") icon_name='ghost.xpm' for j in range(len(poses)): butname = poses[j].replace(".anim","") img_name=poses[j].replace(".anim",".bmp") icon_name=posetabs + img_name posefile = posetabs + poses[j] mc.setParent() mc.shelfButton(i1=icon_name,w=110,h=80,l=butname,bgc=(.2,.6,.3),st='iconAndTextVertical',p=each,c=partial(Importanim,posefile)) mc.popupMenu() mc.menuItem(l='Import anim',en=1,c=partial(Importanim,posefile)) mc.menuItem(d=True) mc.menuItem(l='Rename anim',en=1,c=partial(Renameanim,posefile)) mc.menuItem(d=True) mc.menuItem(l='Delete anim',en=1,c=partial(Deleteanim,posefile)) mc.setParent('..') else: if mc.shelfLayout('Default',q=True,exists=True): mc.deleteUI ('Default') shelftmp = mc.shelfLayout('Default',w=450,h=200,bgc=(0.3,0.3,0.3),p=Animation) mc.sysFile(posepath+'Default/', makeDir=True ) if tabsanim1: for each in tabsanim1: sh=mc.shelfLayout(each,p=Poses,st="iconAndTextVertical") mc.setParent('..') posetabs1 = (posepath1 + each + "/") poses1 = mc.getFileList (fld =posetabs1,fs="*.anim") icon_name1='ghostOff.xpm' for j in range(len(poses1)): butname1 = poses1[j].replace(".anim","") img_name1= poses1[j].replace(".anim",".bmp") icon_name1=posetabs1 + img_name1 posefile1 = posetabs1 + poses1[j] mc.setParent() mc.shelfButton(i1=icon_name1,w=110,h=80,l=butname1,fn= "fixedWidthFont" ,bgc=(.9, .4, .0),st='iconAndTextVertical',p=each,c=partial(Pose_rtn,posefile1)) mc.popupMenu() mc.menuItem(l='Import Pose',en=1,c=partial(Pose_rtn,posefile1)) mc.menuItem(d=True) mc.menuItem(l='Rename Pose',en=1,c=partial(Renamepose,posefile1)) mc.menuItem(d=True) mc.menuItem(l='Delete Pose',en=1,c=partial(Deletepose,posefile1)) mc.setParent('..') else: if mc.shelfLayout('Default1',q=True,exists=True): mc.deleteUI ('Default1') shelftmp1 = mc.shelfLayout('Default1',w=450,h=200,bgc=(0.3,0.3,0.3),p=Poses) mc.sysFile(posepath1+'Default1/', makeDir=True )