def toggle_server(self, arg=None): if self.ServerStarted: self.ServerStarted = False self.timer.stop() del self.timer del self.receiver if cmds.window(self.winName, exists=True): cmds.intField(self.ui_oscport, edit=True, enable=True) cmds.button(self.receiveButton, edit=True, label='Start Receiving') for name in cmds.lsUI(type='shelfButton'): if cmds.shelfButton(name, query=True, label=True) == 'NI mate receiver': cmds.setParent('MayaWindow') cmds.shelfButton(name, edit=True, enableBackground=False) else: self.receiver = NImateReceiver(self.osc_port) self.timer = TimerObj(self.timer_exec) self.ServerStarted = True if cmds.window(self.winName, exists=True): cmds.intField(self.ui_oscport, edit=True, enable=False) cmds.button(self.receiveButton, edit=True, label='Stop Receiving') for name in cmds.lsUI(type='shelfButton'): if cmds.shelfButton(name, query=True, label=True) == 'NI mate receiver': cmds.setParent('MayaWindow') if self.record: cmds.shelfButton(name, edit=True, enableBackground=True, backgroundColor=(1,0,0)) else: cmds.shelfButton(name, edit=True, enableBackground=True, backgroundColor=(0,0.667,1))
def mouseMoveEvent(self, event): #print 'Mouse Move' if event.buttons() == QtCore.Qt.MiddleButton: if not self.rect().contains(event.pos()): #self.hide() #self.parent().layout().removeWidget(self) drag = QtGui.QDrag(self) data = QtCore.QMimeData() data.setText(self.text()) data.setImageData(self.icon().pixmap(32, 32, self.icon().Normal, self.icon().On)) drag.setMimeData(data) drag.setPixmap(QtGui.QPixmap.grabWidget(self)) #drag.setPixmap(self.icon().pixmap(32, 32, self.icon().Normal, self.icon().On)) drag.setHotSpot(QtCore.QPoint(22, 22)) shelfButtons = set(cmds.lsUI(typ='shelfButton')) dropAction = drag.exec_( QtCore.Qt.MoveAction | QtCore.Qt.CopyAction, QtCore.Qt.CopyAction) new_buttons = list( set(cmds.lsUI(typ='shelfButton')).difference(shelfButtons)) if len(new_buttons) == 1: button = new_buttons.pop() print 'Dropped button!', button else: print 'Dropped', dropAction #print dropAction #print drag.target() #print drag.target().objectName() super(ShelfButton, self).mouseMoveEvent(event)
def get_scripts_tab_lay(): """ Returns: (str or None) : tabLayout Get Script Editor's tabLayout that is holding script tabs (not the "Quick Help" one). """ # get scriptEditor panel if exists try: panels = mc.lsUI(panels=True) except: return None script_editor = [p for p in panels if 'scriptEditor' in p] if not script_editor: return None # get all tablayouts that have scriptEditor as parent se_tabs = [lay for lay in mc.lsUI(type='tabLayout') \ if script_editor[0] in mc.layout(lay, q=True, p=True)] # get the tablayout that have only MEL and /or Python tabs # (there may be also the 'Quick Help' tablayout) for lay in se_tabs or (): tabs = mc.tabLayout(lay, q=True, tabLabel=True) if all(is_valid_tab_name(x) for x in tabs): return lay
def mouseMoveEvent(self, event): #print 'Mouse Move' if event.buttons() == QtCore.Qt.MiddleButton: if not self.rect().contains(event.pos()): #self.hide() #self.parent().layout().removeWidget(self) drag = QtGui.QDrag(self) data = QtCore.QMimeData() data.setText(self.text()) data.setImageData(self.icon().pixmap(32, 32, self.icon().Normal, self.icon().On)) drag.setMimeData(data) drag.setPixmap(QtGui.QPixmap.grabWidget(self)) #drag.setPixmap(self.icon().pixmap(32, 32, self.icon().Normal, self.icon().On)) drag.setHotSpot(QtCore.QPoint(22, 22)) shelfButtons = set(cmds.lsUI(typ='shelfButton')) dropAction = drag.exec_(QtCore.Qt.MoveAction|QtCore.Qt.CopyAction, QtCore.Qt.CopyAction) new_buttons = list(set(cmds.lsUI(typ='shelfButton')).difference(shelfButtons)) if len(new_buttons) == 1: button = new_buttons.pop() print 'Dropped button!', button else: print 'Dropped', dropAction #print dropAction #print drag.target() #print drag.target().objectName() super(ShelfButton, self).mouseMoveEvent(event)
def CloseAllPBWin(self, *args): AllWindows = mc.lsUI(windows=True) for win in AllWindows: # win = str(win) if win.find('OCT_QuickPBWin_') >= 0: self.closeWin(win) AllPlanes = mc.lsUI(p=True) for plane in AllPlanes: if plane.find('OCT_QuickPBWin_') >= 0: mc.deleteUI(plane, panel=True)
def _test_for_hik_issues(ref_): """Fix any human ik issues. Some MotionBurner files have been delivered with human ik left driving the MotionBurner skeleton. This will check for any human ik driver and disable it if it is found. Args: ref_ (FileRef): reference to update """ _hip_rx = ref_.get_plug('Hip_L.rx') if _hip_rx.list_incoming(type='animCurve'): print 'NO HIK ISSUES' return print 'HIK ISSUES DETECTED' # Find source option menu mel.eval('HIKCharacterControlsTool') _hik_src_opt = None for _grp in cmds.lsUI(long=True, type='optionMenuGrp'): if _grp.endswith('|hikSourceList'): _hik_src_opt = _grp.split('|')[-1] break assert _hik_src_opt print 'HIK SOURCE OPTION', _hik_src_opt # Apply None cmds.optionMenuGrp(_hik_src_opt, edit=True, value=" None") mel.eval("hikUpdateCurrentSourceFromUI()") mel.eval("hikUpdateContextualUI()") # assert _hip_rx.list_incoming(type='animCurve') print 'DISABLED HUMAN IK'
def fixUiElementsInfosToHaveFullPath(self, uiElementsInfos, windowName): """ Get the full ui name of an element where elements is a dict of mel uiName/uiType pairs returns a new elements dict with full ui paths """ allUiNames = cmds.lsUI(dumpWidgets=True) inWindowUiNames = [nm for nm in allUiNames if windowName in nm] cleaned = {} for nm in inWindowUiNames: while nm.endswith('|'): nm = nm[:-1] cleaned[nm] = 1 inWindowUiNames = cleaned.keys() #print( 'inWindowUiNames is:') #print( inWindowUiNames ) fullPathUiElementsInfos = {} for nm in inWindowUiNames: #print( uiElementsInfos ) for elName, el in uiElementsInfos.items(): if nm.endswith(el.nameShort): newEl = UiElementInfo(nameFull=nm, nameShort=el.nameShort, typ=el.typ, parentWindow=el.parentWindow) fullPathUiElementsInfos[nm] = newEl return fullPathUiElementsInfos
def removeUiSeparateView( cam ): import sgBFunction_attribute import sgBFunction_dag uiPrefix = 'separatedViewCam_' uis = cmds.lsUI( wnd=1 ) for ui in uis: if not len( ui ) > len( uiPrefix ): continue if ui[ : len( uiPrefix ) ] != uiPrefix: continue cmds.deleteUI( ui, wnd=1 ) if not cmds.objExists( cam ): return None for cam in cmds.ls( type='camera' ): if not cmds.objExists( cam ): continue cam = sgBFunction_dag.getTransform( cam ) sgBFunction_attribute.addAttr( cam, ln='filmTranslateCams', at='message' ) sgBFunction_attribute.addAttr( cam, ln='aniamtionCam', at='message' ) cons1 = cmds.listConnections( cam+'.filmTranslateCams', d=1, s=0 ) cons2 = cmds.listConnections( cam+'.aniamtionCam', d=1, s=0 ) if cons1: cmds.delete( cons1 ) if cons2: cmds.delete( cons2 )
def _script_editor_save_to_project(*xargs): """Execute save to project.""" del xargs # Maya callbacks require args # Get current editor _cur_editor = [ _ui for _ui in cmds.lsUI(dumpWidgets=True, long=False) if cmds.cmdScrollFieldExecuter(_ui, query=True, exists=True) and not cmds.cmdScrollFieldExecuter(_ui, query=True, isObscured=True) ][0] # Get file path _src_type = cmds.cmdScrollFieldExecuter(_cur_editor, query=True, sourceType=True) _extn = {'mel': 'mel', 'python': 'py'}[_src_type] _text = cmds.cmdScrollFieldExecuter(_cur_editor, query=True, text=True) _file = get_single( cmds.fileDialog2( fileMode=0, # Single file doesn't need to exist caption="Save Script", okCaption='Save', startingDirectory=pipe.cur_project().maya_scripts_path, fileFilter='{} Files (*.{})'.format(_extn.upper(), _extn)), catch=True) # Write file to disk if _file: write_file(file_=_file, text=_text)
def uninstallCAS(): CasShelf = [ cas for cas in cm.lsUI(type='shelfLayout') if cas.split('|')[-1] == "NCGTool" ] if CasShelf: cm.deleteUI(CasShelf[-1])
def refresh_graph(): """ Opens and then closes the graph editor to help with stability when creting nodes """ mel.eval('pgYetiTearOffGraphPanel') if YETI_WIN in cmds.lsUI(type='window'): cmds.deleteUI(YETI_WIN)
def lsUI(**kwargs): """ List UI elements as python wrapped types :param kwargs: flags from the respective maya command are valid If no special type keyword is specified, all item types will be returned :return: list of NamedUI instances of respective UI elements """ long = kwargs.pop('long', kwargs.pop('l', True)) head = kwargs.pop('head', kwargs.pop('hd', None)) tail = kwargs.pop('tail', kwargs.pop('tl', None)) if not kwargs: kwargs = { 'windows': 1, 'panels': 1, 'editors': 1, 'controls': 1, 'controlLayouts': 1, 'collection': 1, 'radioMenuItemCollections': 1, 'menus': 1, 'menuItems': 1, 'contexts': 1, 'cmdTemplates': 1 } # END kwargs handling kwargs['long'] = long if head is not None: kwargs['head'] = head if tail is not None: kwargs['tail'] = tail # NOTE: controls and controlLayout will remove duplcate entries - we have to # prune them ! Unfortunately, you need both flags to get all items, even layouts # NOTE: have to ignore errors as there are still plenty of items that we cannot # wrap return wrapUI(set(cmds.lsUI(**kwargs)), ignore_errors=True)
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)
def __icon(*arg): if "file" not in CACHE.viewkeys(): return mc.select(cl=True) for e in mc.lsUI(ed=True): try: mc.viewFit(p=e) except: pass f = CACHE["file"][:-3] + ".png" if os.path.isfile(f): os.remove(f) fmt = mc.getAttr("defaultRenderGlobals.imageFormat") mc.setAttr("defaultRenderGlobals.imageFormat", 32) i = mc.playblast(cf=f, fmt="image", cc=False, fr=1, v=False, orn=False, os=True, p=100, wh=[200, 200], qlt=100) mc.setAttr("defaultRenderGlobals.imageFormat", fmt) mc.image("img_FRW", e=True, i=f)
def lsUI( **kwargs ): """ List UI elements as python wrapped types :param kwargs: flags from the respective maya command are valid If no special type keyword is specified, all item types will be returned :return: list of NamedUI instances of respective UI elements """ long = kwargs.pop( 'long', kwargs.pop( 'l', True ) ) head = kwargs.pop( 'head', kwargs.pop( 'hd', None ) ) tail = kwargs.pop( 'tail', kwargs.pop( 'tl', None) ) if not kwargs: kwargs = { 'windows': 1, 'panels' : 1, 'editors' : 1, 'controls' : 1, 'controlLayouts' : 1,'collection' : 1, 'radioMenuItemCollections' : 1, 'menus' : 1, 'menuItems' : 1, 'contexts' : 1, 'cmdTemplates' : 1 } # END kwargs handling kwargs['long'] = long if head is not None: kwargs['head'] = head if tail is not None: kwargs['tail'] = tail # NOTE: controls and controlLayout will remove duplcate entries - we have to # prune them ! Unfortunately, you need both flags to get all items, even layouts # NOTE: have to ignore errors as there are still plenty of items that we cannot # wrap return wrapUI( set( cmds.lsUI( **kwargs ) ), ignore_errors = True )
def sliderReset(self, model): #print self.camWH allWindow = list( set(mc.lsUI(wnd=True)) - set(['scriptEditorPanel1Window', 'MayaWindow'])) #判断字典中是否保存的显示相机窗口,若没有保存在字典中 for win in allWindow: if 'Model_Win' in win: if win not in self.camWH.keys(): win_H = mc.window(win, q=True, h=True) win_W = mc.window(win, q=True, w=True) self.camWH.update({win: [win_W, win_H]}) field = mc.floatSliderButtonGrp('Scale', q=True, v=True) for key in self.camWH.keys(): if mc.window(key, ex=True): #根据滑调设置窗口大小 if model == 1: newWin_W = field * self.camWH[key][0] newWin_H = field * self.camWH[key][1] mc.window(key, e=True, wh=[newWin_W, newWin_H]) #根据按钮重置窗口 elif model == 0: mc.window(key, e=True, wh=[self.camWH[key][0], self.camWH[key][1]]) #print self.camWH mc.floatSliderButtonGrp('Scale', e=True, v=1.0) else: del self.camWH[key]
def set_and_export(filepath): pathField = None fileField = None filepath = uf.fix_path(filepath) path = "/".join(filepath.split("/")[:-1]) file = os.path.basename(filepath).split(".")[0] # open the exporter mel.eval("gameFbxExporter;") # get the exporter nodes (I'm still not sure which one, so we'll use the last later) nodes = mel.eval("gameExp_GetGameFbxExporterNodeList()") # preset = "X:/Production/Code/Maya/Tools/PipelineTools/Python/Publishing/assetAnimGameExpPreset.mel" # can we get the whole frame range? # set it to the correct tab tab = "gameExporterWindow|gameExporterTabFormLayout|gameExporterTabLayout" cmds.tabLayout(tab, e=True, st="gameExporterAnimationTab") # assign preset (on the last node?) # hold = mel.eval('gameExp_ApplyPresetOnNode("{0}", "{1}");'.format(nodes[-1], preset)) # find the text fields for ctrl in cmds.lsUI(ctl=True, l=True): if ctrl.startswith("gameExporterWindow") and ctrl.split("|")[-1]=="anim_gameExporterExportFilename": fileField = ctrl if ctrl.startswith("gameExporterWindow") and ctrl.split("|")[-1]=="anim_gameExporterExportPath": pathField = ctrl mel.eval('gameExp_BrowseFolder')
def shelfQuery(): form = cmds.setParent(query=True) cmds.formLayout(form, edit=True, width=300) t = cmds.text(label="Select the shelf for NI mate receiver") m = cmds.optionMenu(label="Shelf", changeCommand=setShelf) for name in cmds.lsUI(type='shelfLayout'): cmds.menuItem(label=name) cr = cmds.button( label="Create", command='import maya.cmds as cmds\ncmds.layoutDialog(dismiss="Create")' ) ca = cmds.button( label="Cancel", command='import maya.cmds as cmds\ncmds.layoutDialog(dismiss="Cancel")' ) spacer = 5 top = 5 edge = 5 cmds.formLayout(form, edit=True, attachForm=[(t, 'top', top), (t, 'left', edge), (t, 'right', edge), (m, 'left', edge), (m, 'right', edge), (cr, 'left', edge), (ca, 'right', edge)], attachNone=[(t, 'bottom'), (m, 'bottom'), (cr, 'bottom'), (ca, 'bottom')], attachControl=[(m, 'top', spacer, t), (cr, 'top', spacer, m), (ca, 'top', spacer, m)], attachPosition=[(cr, 'right', spacer, 50), (ca, 'left', spacer, 50)])
def get_main_window(): from maya import cmds maya_windows = [ each_win for each_win in cmds.lsUI(wnd=True) if cmds.window(each_win, q=True, mw=True) ] return maya_windows[0]
def add_menu_to_all(window='all'): if window != 'all': controls = get_window_controls(window) else: controls = mc.lsUI(long=1, controls=1) _logger.info('in add_menu_to_all') # should check if menu exists before adding menus # or one could end up adding menu two times, and the full path becomes xxx||guiHelperMenu all_controls_with_menu = get_all_control_with_menu() all_controls = [ re.search('^.*[^\|](?=\|)', c).group() for c in all_controls_with_menu ] add_count = 0 for c in controls: # _logger.info('add menu to: %s' % c) # check if menu exists already # it may still add redundant menus, because of || # but we will take care of them in the remove function # _logger.info('checking if menu exists: %s|guiHelperMenu' % c ) if c in all_controls: # if mc.menu('%s|guiHelperMenu' % c, q=1, ex=1): # _logger.info('menu exists skipped') continue else: gui_helper(c) add_count += 1 print '\nAdded ', add_count, ' menus to ', window
def get_windows(self): u"""Maya標準のものを除くウィンドウのリストを返す""" windows = cmds.lsUI(windows=True) return [ x for x in windows if not any(y for y in self._EXCLUDE_WINDOWS if x.startswith(y)) ]
def on_actionLoadAttributes_triggered(self, clicked=None): if clicked==None:return mainChannelBox = 'mainChannelBox' ChannelBoxs = mc.lsUI(typ='channelBox') ChannelBoxs.remove(mainChannelBox) if len(ChannelBoxs) == 0:return DriverOBJ = mc.channelBox(mainChannelBox, q=True, mol=True) DriverAttr = mc.channelBox(mainChannelBox, q=True, sma=True) if not DriverOBJ or not DriverAttr:return self.driverAttributelineEdit.setText('%s.%s'%(DriverOBJ[0], DriverAttr[0])) DrivenOBJ = mc.channelBox(ChannelBoxs[0], q=True, mol=True) DrivenAttr = mc.channelBox(ChannelBoxs[0], q=True, sma=True) DrivenAttrList = [] for attribute in DrivenAttr: DrivenAttrList.append('%s.%s'%(DrivenOBJ[0], attribute)) self.drivenAttributelineEdit.clear() self.drivenAttributelineEdit.addItems(DrivenAttrList)
def main(log=None): if not log: import logging log = logging.getLogger() # use ' ' as a fill char and center aligned log.debug('{0:-<40}'.format('remove_open_windows')) wins = cmds.lsUI(wnd=True) if wins: for x in wins : if ( cmds.window(x,q=True,vis=True) and x != 'MayaWindow' ) : #print x # remove scriptEditor will cause maya crash ,so set scriptEditorPanel1Window vis to false if x != 'scriptEditorPanel1Window' : try: cmds.deleteUI(x,window=True) except: log.error('delete window %s error' % x) log.error(traceback.format_exc()) else: log.debug('delete window %s success' % x) else: # close scriptEditor cmds.window(x,e=True,vis=False) log.warning('close window %s' % x)
def uiCloseSceneUpdate( *args ): existingWindows = cmds.lsUI( windows=1 ) for ui in sgBModel_editUi.targetWindowsClose_whenSceneUpdate: if ui in existingWindows: cmds.deleteUI( ui )
def _script_editor_find_file_menu(verbose=0): """Find script editor file menu. Args: verbose (int): print process data Returns: (str): script editor file menu name """ # Find script editor file menu _menus = [] for _menu in cmds.lsUI(menus=True): if cmds.menu(_menu, query=True, label=True) != 'File': continue lprint('TESTING', _menu, verbose=verbose) _post_cmd = cmds.menu(_menu, query=True, postMenuCommand=True) lprint(' - POST CMD', _post_cmd, verbose=verbose) if not _post_cmd or 'ScriptEditor' not in _post_cmd: continue lprint(' - MATCHED', verbose=verbose) _menus.append(_menu) _menu = get_single(_menus, catch=True) if not _menu: print ' - PSYHIVE FAILED TO FIND SCRIPT EDITOR MENU' return None # Init menu if it has no children if not cmds.menu(_menu, query=True, itemArray=True): _init_cmd = cmds.menu(_menu, query=True, postMenuCommand=True) mel.eval(_init_cmd) assert cmds.menu(_menu, query=True, itemArray=True) return _menu
def removeUiSeparateView(cam): import sgBFunction_attribute import sgBFunction_dag uiPrefix = 'separatedViewCam_' uis = cmds.lsUI(wnd=1) for ui in uis: if not len(ui) > len(uiPrefix): continue if ui[:len(uiPrefix)] != uiPrefix: continue cmds.deleteUI(ui, wnd=1) if not cmds.objExists(cam): return None for cam in cmds.ls(type='camera'): if not cmds.objExists(cam): continue cam = sgBFunction_dag.getTransform(cam) sgBFunction_attribute.addAttr(cam, ln='filmTranslateCams', at='message') sgBFunction_attribute.addAttr(cam, ln='aniamtionCam', at='message') cons1 = cmds.listConnections(cam + '.filmTranslateCams', d=1, s=0) cons2 = cmds.listConnections(cam + '.aniamtionCam', d=1, s=0) if cons1: cmds.delete(cons1) if cons2: cmds.delete(cons2)
def get_all_control_with_menu(): all_menu = mc.lsUI(l=1, type='menu') or [] controls = [] for m in all_menu: if m.endswith('guiHelperMenu'): controls.append(m) return controls
def getEditorFromPanel(panel, editorCommand): '''Finds the editor associated with the given panel. editorCommand must be the editor's function e.g. maya.cmds.nodeEditor''' editors = cmd.lsUI(editors=1) for editor in editors: if editorCommand(editor, ex=1): if editorCommand(editor, q=1, pnl=1) == panel: return editor
def clear_superflous_windows(self, arg=None): '''---------------------------------------------------------------------------------- This clears the interface of window clutter and puts display in wire to lower file load time ----------------------------------------------------------------------------------''' windows = cmds.lsUI(wnd=1) for eachWindow in closeWindow: if eachWindow in windows: windows.remove(eachWindow) cmds.deleteUI(windows, window=1)
def get_window_controls(window): all_controls = mc.lsUI(long=1, controls=1) win_controls = [] for c in all_controls: if '%s|' % window in c: win_controls.append(c) print win_controls return win_controls
def outliner_focus(): outliner = [i for i in cmds.lsUI(editors=1) if 'outliner' in i] if outliner: outliner = outliner[0] else: return cmds.outlinerEditor(outliner, edit=1, showSelected=1) cmds.setFocus(outliner)
def highlightCmdReporter(): '''find cmdScrollFieldReporter and highlight it''' mwin = getMayaWindowWidget() cmdReporters = cmds.lsUI(type='cmdScrollFieldReporter') if not cmdReporters: return # only setup for the first one cmdReporter = mwin.findChild(QTextEdit, cmdReporters[0]) highlighter = Highlighter(parent=mwin) highlighter.setDocument(cmdReporter.document())
def deleteNoneUI(): u''' {'load':'maya_clean','defaultOption':1,'CNname':'关闭所有窗口'} ''' allUI = lsUI(wnd=1) for w in allUI: if w == "MayaWindow" or w == "nexFloatWindow": continue deleteUI(w)
def set_dock_raise(dock_name): all_dock = mc.lsUI(type="dockControl") if not all_dock: return for dock in all_dock: dock_label = mc.dockControl(dock, q=1, l=1) if dock_label == dock_name: mc.dockControl(dock, e=1, r=1) break
def highlightCmdReporter(): '''find cmdScrollFieldReporter and highlight it''' mwin = getMayaWindowWidget() cmdReporters = cmds.lsUI(type='cmdScrollFieldReporter') if not cmdReporters: return # only setup for the first one cmdReporter = mwin.findChild(QtGui.QTextEdit, cmdReporters[0]) highlighter = Highlighter(parent=mwin) highlighter.setDocument(cmdReporter.document())
def getUI(self,name): items = cmds.lsUI(dumpWidgets=True) for item in items: if self._windowName in item: self._objectList.append(item) for item in self._objectList: if item.endswith(name): return item print self._objectList
def createMenu(CUSTOMMENU): menus = mc.lsUI(menus=True) for i in range(len(menus)-1, -1, -1): menu = menus[i] if mc.menu(menu, q=True, label=True) == PROJECTNAME: mc.deleteUI(menu, menu=True) mainWindow = mm.eval('$null = $gMainWindow') mc.menu(p=mainWindow, to=True, l=PROJECTNAME) # main menu mc.menuItem(subMenu=True, l='Animation Tool', to=True) # mc.menuItem(l='Bake Keyframe', c=__bakeKeyframe) mc.menuItem(l='Create Reference', c=__createReference) mc.menuItem(l='Create Locator Constraint', c=__createLocatorConstraint) mc.menuItem(l='Batch Retarget', c=__batchRetarget) mc.menuItem(l='Export Animation', c=__exportAnimation) mc.menuItem(l='Procedural Animation', c=__proceduralAnimation) mc.menuItem(l='Align Object', c=__alignObject) mc.menuItem(l='Mirror Pose', c=__mirrorPose) mc.setParent('..', menu=True) mc.menuItem(d=True) # -------------------------------- mc.menuItem(subMenu=True, l='Rig Tool', to=True) mc.menuItem(l='Update Bind File', c=__updateBindFile) mc.menuItem(l='Custom Rig Tool', c=__customRigTool) mc.menuItem(l='Generate Hit Box Model', c=__generateHitBox) mc.menuItem(l='Setup Leg', c=__setupLeg) mc.menuItem(l='Import Marker Preset', c=__prefMarker) mc.setParent('..', menu=True) mc.menuItem(d=True) # -------------------------------- mc.menuItem(subMenu=True, l='Validation Tool', to=True) mc.menuItem(l='Check Skin Influences', c=__checkSkinInfluences) mc.setParent('..', menu=True) mc.menuItem(d=True) # -------------------------------- # mc.menuItem(subMenu=True, l='Export Tool', to=True) # mc.menuItem(l='Export 2 Unity', c=__exporter) # mc.setParent('..', menu=True) # mc.menuItem(d=True) # # -------------------------------- mc.menuItem(subMenu=True, l='Ucheck Tool', to=True) mc.menuItem(l='Ucheck Tool', c=__ucheck_tool) mc.setParent('..', menu=True) mc.menuItem(d=True) # -------------------------------- mc.menuItem(subMenu=True, l='Common Tool', to=True) mc.menuItem(l='Setup Environment', c=__setupEnvironment) mc.menuItem(l='Open Config Path', c=__openConfigPath) mc.menuItem(l='Ragdoll Tool', c=__ragdollTool) mc.setParent('..', menu=True)
def toggle_server(self, arg=None): if self.ServerStarted: self.ServerStarted = False self.timer.stop() del self.timer del self.receiver if cmds.window(self.winName, exists=True): cmds.intField(self.ui_oscport, edit=True, enable=True) cmds.button(self.receiveButton, edit=True, label='Start Receiving') for name in cmds.lsUI(type='shelfButton'): if cmds.shelfButton(name, query=True, label=True) == 'NI mate receiver': cmds.setParent('MayaWindow') cmds.shelfButton(name, edit=True, enableBackground=False) else: self.receiver = NImateReceiver(self.osc_port) self.timer = TimerObj(self.timer_exec) self.ServerStarted = True if cmds.window(self.winName, exists=True): cmds.intField(self.ui_oscport, edit=True, enable=False) cmds.button(self.receiveButton, edit=True, label='Stop Receiving') for name in cmds.lsUI(type='shelfButton'): if cmds.shelfButton(name, query=True, label=True) == 'NI mate receiver': cmds.setParent('MayaWindow') if self.record: cmds.shelfButton(name, edit=True, enableBackground=True, backgroundColor=(1, 0, 0)) else: cmds.shelfButton(name, edit=True, enableBackground=True, backgroundColor=(0, 0.667, 1))
def hideUIElements(): global hiddenElements global elementsToHide for i in cmds.lsUI(ctl=True): for e in elementsToHide: if i.find(e) != -1 and cmds.control(i, q=True, visible=True): hiddenElements.append(i) #print "hiding... " + i cmds.control(i, e=True, visible=False) break
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
def clearDock(dockName): """ Clear given dock layout :param dockName: Dock layout name :type dockName: str """ if dockName in mc.lsUI(type='dockControl'): try: mc.deleteUI(dockName) except: pass
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 clear_superflous_windows(self, arg=None): '''---------------------------------------------------------------------------------- This clears the interface of window clutter and puts display in wire to lower file load time ----------------------------------------------------------------------------------''' windows = cmds.lsUI(wnd=1) getDeleteWindows=((each) for each in windows if each not in closeWindow) for each in getDeleteWindows: try: print each cmds.deleteUI(each, window=1) except: pass
def removeOpenWindows(): ''' hide open windows, ignore MayaWindow and nexFloatWindow ''' ignore = ['MayaWindow', 'nexFloatWindow'] windows = mc.lsUI(wnd=True) toRemove = [win for win in windows if win not in ignore] for eachWin in toRemove: if mc.window(eachWin, q=True, vis=True): mc.window(eachWin, e=True, vis=False)
def toggleIcon(off=False): p = Get() # List shelf buttons buttons = cmds.lsUI(type='shelfButton') # interate through buttons to find one using appropriate images for btn in buttons: img = cmds.shelfButton(btn, q=1, image=1) # toggle icon if img in p.iconOff or img in p.iconOn: if not off: cmds.shelfButton(btn, edit=True, image=p.iconOff) else: cmds.shelfButton(btn, edit=True, image=p.iconOn)
def getShelfButtonsWithTag( tag ): buttons = [] shelves = cmd.lsUI( cl=True, type='shelfLayout' ) or [] for shelf in shelves: if not cmd.shelfLayout( shelf, ex=True ): continue shelfButtons = cmd.shelfLayout( shelf, q=True, ca=True ) or [] for button in shelfButtons: if cmd.control( button , ex=True ): if control( button, q=True, docTag=True ) == buttonTag: buttons.append( button ) return buttons
def p4ProjectMenu(*args): #clear any projects that are in the collection first items = cmds.lsUI(menuItems = True) for i in items: data = cmds.menuItem(i, q = True, docTag = True) if data == "P4Proj": cmds.deleteUI(i) #find projects toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt" if os.path.exists(toolsPath): f = open(toolsPath, 'r') mayaToolsDir = f.readline() f.close() projects = os.listdir(mayaToolsDir + "/General/Scripts/") p4Projects = [] #Test_Project_Settings for proj in projects: if proj.rpartition(".")[2] == "txt": if proj.partition("_")[2].partition("_")[0] == "Project": p4Projects.append(proj) #set the current project try: f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'r') settings = cPickle.load(f) f.close() currentProj = settings.get("CurrentProject") except: pass #add the projects to the menu for proj in p4Projects: projectName = proj.partition("_")[0] if projectName == currentProj: val = True else: val = False menuItem = cmds.menuItem(label = projectName, parent = "perforceProjectList", cl = "perforceProjectRadioMenuCollection", rb = val, docTag = "P4Proj", c = partial(setProj, projectName)) cmds.menuItem(parent = "perforceProjectList", optionBox = True, c = partial(editProj, projectName))
def setViewportQuality(): global modelEditors global backgroundColors backgroundColors.append(cmds.displayRGBColor('background',q=True)) backgroundColors.append(cmds.displayRGBColor('backgroundTop',q=True)) backgroundColors.append(cmds.displayRGBColor('backgroundBottom',q=True)) cmds.displayRGBColor('background', 1, 1, 1) cmds.displayRGBColor('backgroundTop', 0.762112, 0.87892, 1) cmds.displayRGBColor('backgroundBottom', 1, 1, 1) for i in cmds.lsUI(panels=True): if cmds.modelEditor(i, query=True, exists=True): sts = cmds.modelEditor(i, query=True, stateString=True) sts = sts.replace("$editorName", i) modelEditors.append(sts) cmds.modelEditor(i, edit=True, displayAppearance="smoothShaded", lineWidth=2)
def hash(*args): global projEnvi #delete all previous menu #menu indicated by prefix m_ for chk in cmds.lsUI(menus=True): if chk.startswith('m_'):cmds.deleteUI(chk, menu=True) #get project path root=ET.parse('startup.xml').getroot() selItem=projEnvi for chk in root[1]: if str(chk.tag)==str(selItem):projPath=str(chk.text) #add general python path to system genPyLis=[] for chk in root[0][0]:genPyLis.append(chk.text) for chk in genPyLis: os.makedirs(chk) if os.path.isdir(chk)==False else None for chk in genPyLis: try: sys.path.remove(chk) except: pass sys.path.append(chk) #add projects python path to system if os.path.isdir(projPath)==False: os.makedirs(projPath) try: sys.path.remove(projPath) except: pass sys.path.append(projPath) #generating menu based on collected python path for sourcePath in sys.path: if os.path.isdir(sourcePath): if sourcePath.endswith('/')==True:sourcePath=sourcePath[:sourcePath.rfind('/')] if os.path.isfile(sourcePath+'/asiistMenu.py'): sourceName=sourcePath[sourcePath.rfind('/')+1:] imp.load_source(sourceName,sourcePath+'/asiistMenu.py') #setup data information to maya for chk in getEnvi(): if chk[0]=='unit': cmds.currentUnit(time=str(chk[1])) return
def findControl(ann='', panelTyp='', split=3): # split = which parent in full path to return cntrls = cmds.lsUI(controls=True, long=1) qualified = [] result = [] for con in cntrls: string = cmds.control(con, q=1, ann=1) if ann in string: qualified.append(con) for item in qualified: path = cmds.control(item, q=1, fpn=1) if panelTyp in path: stf = path.split('|') tmp = stf[len(stf) - split] result.append(cmds.control(tmp, q=1, fpn=1)) else: print '______searching ', path return result
def create_model_panel(self,width,height): '''create one tear off model panel for playblast ''' # create tear off model panel self.Panel_Current = cmds.modelPanel(tearOff=True) # max model panel windows = set( cmds.lsUI( windows=True ) ) - set(u'MayaWindow') for win in windows: cmds.window( win, edit=True, widthHeight=(width+100, height+100) ) cmds.modelEditor(self.Panel_Current,e=1,udm=0) cmds.modelEditor(self.Panel_Current,e=1,allObjects=0) cmds.modelEditor(self.Panel_Current,e=1,polymeshes=1,nurbsSurfaces=1) cmds.modelEditor(self.Panel_Current,e=1,cameraName=self.Camera) # #cmds.setFocus(self.Panel_Current) cmds.setFocus(self.Panel_Current)
def shelfQuery(): form = cmds.setParent(query=True) cmds.formLayout(form, edit=True, width=300) t = cmds.text(label="Select the shelf for NI mate receiver") m = cmds.optionMenu(label="Shelf", changeCommand=setShelf) for name in cmds.lsUI(type='shelfLayout'): cmds.menuItem(label=name) cr = cmds.button(label="Create", command='import maya.cmds as cmds\ncmds.layoutDialog(dismiss="Create")') ca = cmds.button(label="Cancel", command='import maya.cmds as cmds\ncmds.layoutDialog(dismiss="Cancel")') spacer = 5 top = 5 edge = 5 cmds.formLayout(form, edit=True, attachForm=[(t, 'top', top), (t, 'left', edge), (t, 'right', edge), (m, 'left', edge), (m, 'right', edge), (cr, 'left', edge), (ca, 'right', edge)], attachNone=[(t, 'bottom'), (m, 'bottom'), (cr, 'bottom'), (ca, 'bottom')], attachControl=[(m, 'top', spacer, t), (cr, 'top', spacer, m), (ca, 'top', spacer, m)], attachPosition=[(cr, 'right', spacer, 50), (ca, 'left', spacer, 50)])
def toggleButton(*args): ds = web.mod('display_lib') ui = ds.GraphEditorButtonNames() # sftSel global idB # List shelf buttons buttons = cmds.lsUI(type='button') # iterate through buttons to find one using appropriate images for btn in buttons: if ui.sftSel in btn: if idB: # turn off cmds.button(btn, edit=True, bgc=[0.38, 0.38, 0.38]) idB = False else: # turn on cmds.button(btn, edit=True, bgc=[0.3, 0.35, 0.5]) idB = True
def buildMenu(): import maya.cmds as cmds mayaMain.addToolsMenu('Plugins') allMenus = cmds.lsUI( type='menu' ) pluginMenu = None i = 0 while pluginMenu == None and i < len(systems): if systems[i] in allMenus: pluginMenu = systems[i] i += 1 if pluginMenu: cmds.menuItem( 'jb_motionDataMenu', label='Motion Data', subMenu=True, parent=pluginMenu ) cmds.menuItem( 'jb_motionDataApply', label='Apply motion node', parent='jb_motionDataMenu', c=cmds.jb_applyMotReader ) cmds.menuItem( 'jb_motionDataBake', label='Bake motion data', parent='jb_motionDataMenu', c=cmds.jb_exportMotionData ) cmds.setParent( 'MayaWindow' )
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 buildMenu(): import maya.cmds as cmds mayaMain.addToolsMenu('Plugins') allMenus = cmds.lsUI( type='menu' ) pluginMenu = None i = 0 while pluginMenu == None and i < len(systems): if systems[i] in allMenus: pluginMenu = systems[i] i += 1 if pluginMenu: cmds.menuItem( 'jb_fakeDynamicsMenu', label='Faked Dynamics', subMenu=True, parent=pluginMenu ) cmds.menuItem( 'jb_fakeDynamicsAdd', label='Add to object', parent='jb_fakeDynamicsMenu', c=cmds.jb_applyFakeDynamics ) cmds.menuItem( 'jb_fakeDynamicsRemove', label='Remove from object', parent='jb_fakeDynamicsMenu', c=cmds.jb_removeFakeDynamics ) cmds.menuItem( 'jb_fakeDynamicsSetActive', label='Make Dynamic On Frame', parent='jb_fakeDynamicsMenu', c=cmds.jb_setFakeDynamics ) cmds.setParent( 'MayaWindow' )
def uiEnable(controls='modelPanel'): model = cmds.lsUI(panels=True, l=True) ed = [] for m in model: # print m if controls in m: ed.append(m) # ed sometimes contains modelPanels that arent attached to anything, use # loop with try to filter them out state = False for item in ed: try: state = cmds.control(item, q=1, m=1) # print item break except: pass for p in ed: if cmds.modelPanel(p, q=1, ex=1): r = cmds.modelEditor(p, q=1, p=1) if r: cmds.control(p, e=1, m=not state)