Flynny85

ScriptLoaderSystem

Jul 15th, 2016
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 29.57 KB | None | 0 0
  1. """ Version: 0.1 Alpha , July 2016:
  2.     Maya Script Loader , Kevin Flynn, [email protected]
  3.     Features:
  4.         - Simple Install + Setup
  5.         - Mac / PC in-dependant.
  6.         - Flexible, 1)Button text, 2)Icon, or 3)dock-able , 4)mini mode.
  7.         - Will display the icon for a script if its named the same.
  8.         - Alternate r-click command if a script doesnt work.
  9. """
  10. ##################################################################################################
  11. #       To run me, edit the below path to the location of this script, then copy and paste the below 2 lines
  12. #       into a Maya python command window.
  13. """
  14. filepath = "C:\Users\kflynn\Documents\maya\scripts\MayaPythonTools\ScriptLoaderSystem" ## << change this path.
  15. paths = sys.path ; sys.path.append(filepath) ; exec 'import ' + 'ScriptLoaderSystem' in globals(); exec( 'reload( ' + 'ScriptLoaderSystem' + ' )' ) in globals();
  16.  
  17. """
  18. ##################################################################################################
  19. #
  20. #
  21. ##################################################################################################
  22. ## proc imports here: ##     
  23. import maya.cmds as cmds
  24. import maya.mel as mel
  25. import os
  26. import posixpath
  27. import shutil
  28. import sys
  29. ## proc imports here: ##
  30. ##################################################################################################
  31. _scriptLoader_window_Icons = [None , None] ## ui elements: iconmode icon and dockmode icon.
  32. ## Global Values here: ##
  33. _ignoredFiles = ['init' , 'hidden' , 'ignore' , 'hide' , '.git' , '.pyc' ] ## Keep lower case:
  34. _iconTypes = ['.bmp' , '.icon' , '.png' , '.jpg' , '.tiff' , '.tga' ] ## Keep lower case:
  35. ## Global Values here: ##
  36. Scrpt_Ldr_Win_W_H = [190 , 180]     # Window UI Settings
  37. ## Global Values here: ##
  38.  
  39. def variables( varType ):
  40.     scriptPrefsPathFolder = cmds.internalVar(uad=True) ## will always be this location, dynamic for each machine but should never change internal to Maya
  41.     scriptPrefsPath = cmds.internalVar(uad=True) + 'ScriptLoader.path' ## will always be this location, dynamic for each machine but should never change internal to Maya
  42.     toolID = __name__   # if loaded from a script, will be that name else "__main__"
  43.     userID = os.environ['USER'] # returns username, works mac 2013+ and PC 2015+
  44.     # fileID = __file__ # file location including name if loaded via import* doesnt play nicely if script wasnt from file
  45.     docID = __doc__     # returns any documentation or docs on objects.. doc strings are """ text lines text """
  46.     if toolID in globals(): ## is imported or copied into script window?
  47.         ## also check out sys.modules??
  48.         importID = True
  49.     else:
  50.         importID = False   
  51.     platformID = sys.platform ## on mac or pc? (win32 = pc , posix maybe for mac?)
  52.     returnData = eval(varType)
  53.     return returnData
  54.  
  55.  
  56. def cmdMessage( _textToSay ): # message printer for Maya warning tab. #
  57.     if _textToSay:
  58.         sys.stdout.write('# ' + ' - ' + _textToSay + ' - ' + ' #\n')
  59.  
  60. class ScriptClass_FileScript:
  61.     """ Class object for a Maya script to be loaded in. """
  62.     def __init__(self,ScriptName,ScriptPath,ScriptType,ScriptCategory,ScriptIcon,ScriptCommandString):
  63.         self.Name = ScriptName
  64.         self.Path = ScriptPath
  65.         self.Type = ScriptType
  66.         self.Category = ScriptCategory
  67.         self.Icon = ScriptIcon
  68.         self.Command = [ScriptCommandString[0] , ScriptCommandString[1]]
  69.  
  70.  
  71. class ScriptClass_ScriptLoaderGlobalSettings:
  72.     """ Class object detailing the info needed by scriptloader and current states """
  73.     def __init__(self):
  74.         ## everything below to be saved to prefs file
  75.         self._ScriptsPath = None
  76.         self._UI_Position  = [10,10]    ## Last known actual window position (edited at docking/undocking)
  77.         self._UI_WidthHeight  = Scrpt_Ldr_Win_W_H ## users prefs [190 - 180] by default
  78.         self._IsIconMode  = 'False' ## is in Icon state?
  79.         self._UI_MelColour = [.56 , .33 , .33] ## base color for all scripts
  80.         self._UI_PyColour = [.33 , .56 , .33] ## base color for all scripts
  81.  
  82.         ## everything below wont be saved to file
  83.         self.window_UI_Name = None 
  84.         self.window_UI_PathBtn = None
  85.         self.window_UI_PaneAttach = None ## the Ui element the Scrollattach is a child of.
  86.         self.window_UI_ScrollAttach = None ## direct name for attaching?
  87.         self.window_UI_DockedMode  = False ## true or false on current state, either False or DockLocation     
  88.         self.window_UI_DockUI = None ## Docked UI element the script is a child of.
  89.         self.window_UI_CategoryOpen = []
  90.         self.window_UI_ScrollBarLocation = [0,0]
  91.         self.AllScriptClasses = []
  92.         self.AllScriptCategorySize = []
  93.  
  94.  
  95. def WriteToPrefsFile():
  96.     ScriptLoaderPrefs_Text = ["SCRIPTSPATH=" , "UI_POSITION=" , "UI_WIDTHHEIGHT=" , "IS_ICONMODE=" , "MEL_COLOUR=" , "PY_COLOUR=" ]
  97.     f = open( variables("scriptPrefsPath") , 'w')
  98.  
  99.     if( ScriptLoader_GlobalSettings.window_UI_Name is not None):
  100.         if( ScriptLoader_GlobalSettings.window_UI_DockedMode is False):
  101.             ScriptLoader_GlobalSettings._UI_Position = cmds.window( ScriptLoader_GlobalSettings.window_UI_Name , query = True , tlc = True )
  102.             ScriptLoader_GlobalSettings._UI_WidthHeight = cmds.window( ScriptLoader_GlobalSettings.window_UI_Name , query = True , widthHeight = True )
  103.  
  104.     filetext = [
  105.     (ScriptLoaderPrefs_Text[0] + str(ScriptLoader_GlobalSettings._ScriptsPath) +'\n'),
  106.     (ScriptLoaderPrefs_Text[1] + str(ScriptLoader_GlobalSettings._UI_Position) +'\n'),
  107.     (ScriptLoaderPrefs_Text[2] + str(ScriptLoader_GlobalSettings._UI_WidthHeight) +'\n'),  
  108.     (ScriptLoaderPrefs_Text[3] + str(ScriptLoader_GlobalSettings._IsIconMode) +'\n'),
  109.     (ScriptLoaderPrefs_Text[4] + str(ScriptLoader_GlobalSettings._UI_MelColour) +'\n'),
  110.     (ScriptLoaderPrefs_Text[5] + str(ScriptLoader_GlobalSettings._UI_PyColour) +'\n'),
  111.  
  112.     ]
  113.     for x in filetext: 
  114.         f.write( str(x) )
  115.     f.close()
  116.  
  117.  
  118. def LoadPrefsFile():
  119.     def GetValidScriptPath():
  120.         newPath = cmds.fileDialog2( dialogStyle = 1 , fm = 3 )
  121.         if newPath is None:
  122.             cmdMessage("User cancelled script path. \n User preference file will not be created.")
  123.         else:
  124.             return newPath[0]
  125.  
  126.     def GetLineValue(_line):
  127.         tmp = _line.split('=')
  128.         if("UI_" in _line): ## these are meant to be numerics, cleanup
  129.             tmpCleanup = tmp[1].replace("[" , "")
  130.             tmpCleanup = tmpCleanup.replace("]" , "")
  131.             return map(int, tmpCleanup.split(',') )
  132.         if("_COLOUR" in _line): ## these are meant to be numerics, cleanup
  133.             tmpCleanup = tmp[1].replace("[" , "")
  134.             tmpCleanup = tmpCleanup.replace("]" , "")
  135.             return map(float, tmpCleanup.split(',') )
  136.         else:  
  137.             return tmp[1]
  138.  
  139.     if os.access( variables("scriptPrefsPath") ,os.R_OK): ## If file exists, read in variables!    
  140.         f = open( variables("scriptPrefsPath") , 'r')
  141.         lines = [x.strip() for x in f.readlines()]
  142.         f.close()
  143.  
  144.         ScriptLoader_GlobalSettings._ScriptsPath = GetLineValue(lines[0])
  145.         ScriptLoader_GlobalSettings._UI_Position = GetLineValue(lines[1])
  146.         ScriptLoader_GlobalSettings._UI_WidthHeight = GetLineValue(lines[2])
  147.         ScriptLoader_GlobalSettings._IsIconMode = GetLineValue(lines[3])
  148.         ScriptLoader_GlobalSettings._UI_MelColour = GetLineValue(lines[4])
  149.         ScriptLoader_GlobalSettings._UI_PyColour = GetLineValue(lines[5])  
  150.  
  151.     else: ## file doesnt exist / create new default
  152.         tmp = GetValidScriptPath() ## basic vanilla setup
  153.         if (tmp is not None):
  154.             ScriptLoader_GlobalSettings._ScriptsPath = tmp
  155.             WriteToPrefsFile()
  156.  
  157.  
  158. def PopulateScriptClasses():
  159.     _filesFound = []    ## all files
  160.     _filesFoundClean = []   ## files found , duplicates removed
  161.     _scriptsClasses = [] ## class holder
  162.  
  163.     def splitNice(_filelocation):
  164.         tmp = _filelocation.split(".")
  165.         tmp2 = tmp[0].split("/")
  166.         return tmp2[-1].lower()
  167.  
  168.     def getIcon( _filelocation ):
  169.         tmpLocation = _filelocation.split('/')
  170.         _filename = tmpLocation[-1].split('.')
  171.         del tmpLocation[-1]
  172.         tmpLocation2 = '/'.join(tmpLocation)
  173.         tmpFileInArea = getFiles(tmpLocation2)
  174.  
  175.         for tempFile in tmpFileInArea:
  176.             for _type in _iconTypes:
  177.                 if( (_filename[0] + _type) in tempFile ):
  178.                     return tempFile
  179.  
  180.     ## grab all the script files found! ##
  181.     def getFiles(_FileLocation):
  182.         _tmp_filesFound = []
  183.         for root, directories, filenames in os.walk(_FileLocation):
  184.             for filename in filenames:
  185.                 nameCleaned = os.path.join(root,filename).replace("\\","/")
  186.                 _tmp_filesFound.append(nameCleaned)
  187.         return _tmp_filesFound
  188.  
  189.     _filesFound = getFiles( ScriptLoader_GlobalSettings._ScriptsPath )
  190.     ## clean up process on folders ##      
  191.     for fileclean in _filesFound:
  192.         stringTest = False
  193.         for ignoredType in _ignoredFiles:
  194.             if ignoredType in fileclean.lower():
  195.                 stringTest = True
  196.                 break
  197.         if stringTest is False:    
  198.             _filesFoundClean.append(fileclean) 
  199.  
  200.     tempListCategory = []      
  201.  
  202.     ## begin populating script classes!  ##    
  203.     for x in _filesFoundClean:
  204.         if (".mel" in x or ".py" in x):
  205.             name = splitNice(x)
  206.             location = x
  207.             tmpType = x.split('.')
  208.             scriptType = tmpType[1]
  209.             tmpCategory = x.split('/')
  210.             scriptCategory = tmpCategory[-2]
  211.             tempListCategory.append( scriptCategory )
  212.             scriptIcon = getIcon(x)
  213.             scriptCommand = ScriptLoaderSystem_btn_command(location)
  214.             tmpClass = ScriptClass_FileScript( name , location , scriptType , scriptCategory, scriptIcon, scriptCommand )
  215.             _scriptsClasses.append(tmpClass)
  216.  
  217.     ## sort list by category: ##
  218.     _scriptsClasses.sort(key=lambda x: x.Category, reverse=False)
  219.     ScriptLoader_GlobalSettings.AllScriptClasses = _scriptsClasses
  220.     ScriptLoader_GlobalSettings.AllScriptCategorySize = dict((i, tempListCategory.count(i)) for i in tempListCategory)
  221.  
  222. def ScriptLoaderSystem_Refresh():
  223.     WriteToPrefsFile()
  224.     ScriptLoader_GlobalSettings.window_UI_ScrollBarLocation = cmds.scrollLayout( ScriptLoader_GlobalSettings.window_UI_ScrollAttach , query=True, scrollAreaValue=True)
  225.     PopulateScriptClasses()  ## find all scripts and setup the list of classes/container
  226.     cmdMessage("Refreshing scripts loaded from disk: " + str(len(ScriptLoader_GlobalSettings.AllScriptClasses)) + " Scripts found." )
  227.     ScriptLoaderSystem_UI_PopulateScripts() ## use created classes to create the buttons on window
  228.  
  229. def ScriptLoaderSystem_UI_newFilePath():    #edits the path button
  230.     if(ScriptLoader_GlobalSettings._ScriptsPath is not None):
  231.         newPath = cmds.fileDialog2( dialogStyle = 1 , fm = 3 , dir = ScriptLoader_GlobalSettings._ScriptsPath)
  232.     else:
  233.         newPath = cmds.fileDialog2( dialogStyle = 1 , fm = 3 )
  234.     if newPath is None:
  235.         cmdMessage("User cancelled script path")
  236.     else:
  237.         ScriptLoader_GlobalSettings._ScriptsPath = newPath[0]
  238.         cmds.button( ScriptLoader_GlobalSettings.window_UI_PathBtn , parent = 'master_Scrpt_Ldr_Win_ColsHeader_Left' , edit = True , label = ScriptLoader_GlobalSettings._ScriptsPath[0:15] , width = ( 190 / 2 ) , ann = ScriptLoader_GlobalSettings._ScriptsPath )
  239.         print ( 'User chosen Path: \n' + ScriptLoader_GlobalSettings._ScriptsPath + '\n' )
  240.         ScriptLoaderSystem_Refresh()
  241.  
  242.  
  243. def ScriptLoaderSystem_btn_command( script_path ): # given a location will feed back the command string to use to initialise.  
  244.     testNetwork = script_path.startswith('\\')
  245.     paths = sys.path
  246.     Additional = ''
  247.     if testNetwork is True:
  248.         Additional = ( '//' ) # adding network prefix..
  249.            
  250.     tmp = script_path.split( '\\' )
  251.     tmp2 = posixpath.join( *tmp ) # using the Unix style pathing that's what Maya uses, even on windows..
  252.  
  253.     Command_String = []
  254.     if '.mel' in script_path:
  255.         Command_String.append ( 'mel.eval(\'source \"' + Additional + tmp2 + '\" ;\')' )
  256.         Command_String.append ( 'mel.eval(\'source \"' + Additional + tmp2 + '\" ;\')' )
  257.  
  258.     else:
  259.         tmp3 = tmp2.split( '.')
  260.         tmp4 = os.path.split(tmp3[0])
  261.         sys.path.append( os.path.dirname( tmp3[0] ) )
  262.         Command_String.append ( "exec ('import ' + '$module$') in globals() ;exec( 'reload( ' + '$module$' + ' )' ) in globals()".replace( "$module$" , tmp4[1] ) )
  263.         Command_String.append ( 'execfile( (\'' + Additional + tmp2 + '\'))' ) ## old way of forcing a script load..
  264.  
  265.     return Command_String
  266.  
  267. def ScriptLoaderSystem_UI_PopulateScripts(): ## deletes the Ui shelf and re-populates note: this doesnt refresh the scripts class or relook at the files on disk.
  268.     tmp_WindowWidth = 190
  269.     if(ScriptLoader_GlobalSettings.window_UI_Name is not None):
  270.         if cmds.window(ScriptLoader_GlobalSettings.window_UI_Name, exists = True ):
  271.             tmp_WindowWidth =  cmds.window( ScriptLoader_GlobalSettings.window_UI_Name , w = True , query = True ) # grab current width of control to judge character limit.
  272.        
  273.     tmp_Category = ''
  274.     tmp_Name = ''
  275.     tmp_Count = 0
  276.  
  277.     def DeleteOldUi():
  278.         cmds.deleteUI( ScriptLoader_GlobalSettings.window_UI_ScrollAttach )
  279.         ScriptLoader_GlobalSettings.window_UI_ScrollAttach = cmds.scrollLayout( parent = ScriptLoader_GlobalSettings.window_UI_PaneAttach , cr = True , vst = 10 )  #all script catogories nested to this
  280.         if ScriptLoader_GlobalSettings._IsIconMode == 'True': # Make Icon Only :
  281.             cmds.button( _scriptLoader_window_Icons[0] , edit = True , label = '#' )
  282.         else: # Make Text Only :     
  283.             cmds.button( _scriptLoader_window_Icons[0] , edit = True , label = '=' )
  284.  
  285.         if ScriptLoader_GlobalSettings.window_UI_DockedMode is True: # Make Icon Only :
  286.             cmds.button( _scriptLoader_window_Icons[1] , edit = True , label = '||' )
  287.         else:
  288.             cmds.button( _scriptLoader_window_Icons[1] , edit = True , label = '[]' )
  289.  
  290.     def NiceName( nameString , columns ): # given a string, will return a version that should just fit the current window layout
  291.         character_WindowLength = 4 # amount of pixels a character takes avg.
  292.         frameLayoutIcon = 15 ; scrollBarLayoutIcon = 6 # size in characters, avg.
  293.         charMaxLength = ( ( ( tmp_WindowWidth  ) / character_WindowLength) - ( frameLayoutIcon + scrollBarLayoutIcon ) ) # area to play with after removing scrollbars width, icons from windows total width.
  294.         if charMaxLength < len( nameString ):
  295.             newCleanName = ( nameString[0: ( charMaxLength -3 )] + '..' )
  296.         else:
  297.             newCleanName = nameString[0:int(charMaxLength)]    
  298.         if columns > 1:
  299.             newCleanName = newCleanName[0:( int( charMaxLength * .9) / columns )]
  300.         return newCleanName    
  301.  
  302.     def NiceColor( scriptType , scriptNumber): # given a list of files/scripts, and a number feeds back a colour array.. colour[x ,x ,x]
  303.         tmpBtn_Color = None ; tmpBtn_Color = [0,0,0]
  304.         if 'mel' in scriptType:
  305.             btn_scriptType = ScriptLoader_GlobalSettings._UI_MelColour
  306.         else:
  307.             btn_scriptType = ScriptLoader_GlobalSettings._UI_PyColour      
  308.  
  309.         divisable = .9
  310.         if scriptNumber%2==0:
  311.             divisable = .966   
  312.  
  313.         scriptNumber = scriptNumber/10.0 ## staggering color gradient here..
  314.         if(scriptNumber > 0.1):
  315.             scriptNumber = scriptNumber/10.0
  316.             if(scriptNumber > 0.1):
  317.                 scriptNumber = scriptNumber/10.0
  318.  
  319.         tmpBtn_Color[0] = btn_scriptType[0] * divisable - scriptNumber
  320.         tmpBtn_Color[1] = btn_scriptType[1] * divisable - scriptNumber
  321.         tmpBtn_Color[2] = btn_scriptType[2] * divisable - scriptNumber
  322.         return tmpBtn_Color
  323.  
  324.     def AddPopUpMenu_GoToFolder(_button , _path):
  325.         tmp_Path = _path.split('/')
  326.         tmp_Path.remove(tmp_Path[-1])
  327.         _R_ClickOpts = cmds.popupMenu( parent = _button , button = 3 )
  328.         cmds.menuItem( label = 'Goto Folder' , parent = _R_ClickOpts , command = ( variables('toolID') + '.gotoFolder("' + str('/'.join(tmp_Path)) + '")' ) )
  329.  
  330.     def AddPopUpMenu_TryOldCommand(_button , _command):
  331.         _R_ClickOpts = cmds.popupMenu( parent = _button , button = 3 )
  332.         cmds.menuItem( label = "Doesn't work? \nTry alternate command?" , parent = _R_ClickOpts , command = _command[1] )
  333.  
  334.     DeleteOldUi()
  335.     if(ScriptLoader_GlobalSettings._IsIconMode == 'True'): ## icon mode..                  
  336.         for x in ScriptLoader_GlobalSettings.AllScriptClasses:
  337.             if(tmp_Category != x.Category):
  338.                 tmp_Count = 0
  339.                 tmp_Category = x.Category
  340.                 tmpLayout = cmds.frameLayout( label = str(tmp_Category) , cll = True , cl = True , parent = ScriptLoader_GlobalSettings.window_UI_ScrollAttach ,
  341.                 ec = ( variables('toolID') + '.ScriptLoaderSystem_UI_expandedFrame("' + str(x.Category) + '")') ,
  342.                 cc = ( variables('toolID') + '.ScriptLoaderSystem_UI_closedFrame("' + str(x.Category) + '")') )
  343.                 cmds.columnLayout( tmpLayout , adj=True)
  344.                 AddPopUpMenu_GoToFolder(tmpLayout , x.Path) ## adding goto folder option               
  345.  
  346.                 tmpColumns = 1
  347.                 if( ScriptLoader_GlobalSettings.AllScriptCategorySize[ x.Category ] > 1):
  348.                     tmpColumns = 2
  349.                     if( ScriptLoader_GlobalSettings.AllScriptCategorySize[ x.Category ] > 2):
  350.                         tmpColumns = 3
  351.                         if( ScriptLoader_GlobalSettings.AllScriptCategorySize[ x.Category ] > 3 and tmp_WindowWidth > (Scrpt_Ldr_Win_W_H[0]+30) ):
  352.                             tmpColumns = 4
  353.                             if( ScriptLoader_GlobalSettings.AllScriptCategorySize[ x.Category ] > 4 and tmp_WindowWidth > (Scrpt_Ldr_Win_W_H[0]+60) ):
  354.                                 tmpColumns = 5
  355.                                 if( ScriptLoader_GlobalSettings.AllScriptCategorySize[ x.Category ] > 5 and tmp_WindowWidth > (Scrpt_Ldr_Win_W_H[0]+90) ):
  356.                                     tmpColumns = 6
  357.                         ## should involve script width here?! for if greater than?
  358.                 tmpRow = cmds.rowColumnLayout( numberOfColumns = tmpColumns )
  359.                 if(tmp_Category in ScriptLoader_GlobalSettings.window_UI_CategoryOpen ): ## opening frames from last save..
  360.                     cmds.frameLayout( tmpLayout , edit = True , cl = False )   
  361.  
  362.             else:
  363.                 tmp_Count = tmp_Count + 1
  364.  
  365.             if(x.Icon == None):
  366.                 tmpBtn = cmds.iconTextButton( style = 'textOnly' , bgc = NiceColor(x.Type , tmp_Count) , label = NiceName(x.Name,tmpColumns) , align = 'left' , width = ( (tmp_WindowWidth - 20) / tmpColumns ) , parent = tmpRow , command = x.Command[0] , ann = (x.Name + '.' + x.Type) )
  367.             else:
  368.                 tmpBtn = cmds.iconTextButton( style = 'iconOnly' , image1 = x.Icon ,label = x.Name , align = 'left' , parent = tmpRow , command = x.Command[0] , ann = (x.Name + '.' + x.Type) )
  369.             AddPopUpMenu_TryOldCommand(tmpBtn, x.Command ) ## adds the older command to try directly execute a command!
  370.    
  371.     if(ScriptLoader_GlobalSettings._IsIconMode == 'False'): ## text only mode..
  372.         for x in ScriptLoader_GlobalSettings.AllScriptClasses:
  373.             if(tmp_Category != x.Category):
  374.                 tmp_Count = 0
  375.                 tmp_Category = x.Category
  376.                 tmpLayout = cmds.frameLayout( label = str(tmp_Category) , cll = True , cl = True , parent = ScriptLoader_GlobalSettings.window_UI_ScrollAttach ,
  377.                 ec = ( variables('toolID') + '.ScriptLoaderSystem_UI_expandedFrame("' + str(x.Category) + '")') ,
  378.                 cc = ( variables('toolID') + '.ScriptLoaderSystem_UI_closedFrame("' + str(x.Category) + '")') )
  379.                 AddPopUpMenu_GoToFolder(tmpLayout , x.Path) ## adding goto folder option
  380.  
  381.                 if(x.Category in ScriptLoader_GlobalSettings.window_UI_CategoryOpen ): ## opening frames from last save..
  382.                     cmds.frameLayout( tmpLayout , edit = True , cl = False )
  383.                 tmpColumn = cmds.columnLayout( tmpLayout , adj=True)
  384.             else:
  385.                 tmp_Count = tmp_Count + 1
  386.             tmpBtn = cmds.iconTextButton( style = 'textOnly' , bgc = NiceColor(x.Type , tmp_Count) , label = x.Name , align = 'left' , parent = tmpColumn , command = x.Command[0] , ann = (x.Name + '.' + x.Type) )
  387.             AddPopUpMenu_TryOldCommand(tmpBtn, x.Command ) ## adds the older command to try directly execute a command!
  388.  
  389.  
  390. def ScriptLoaderSystem_UI_expandedFrame(_frameName): ## command triggered by opening of frame, will remember this so its open upon refrshing
  391.     if(_frameName in ScriptLoader_GlobalSettings.window_UI_CategoryOpen):
  392.         pass
  393.     else:
  394.         ScriptLoader_GlobalSettings.window_UI_CategoryOpen.append(_frameName)
  395.  
  396. def ScriptLoaderSystem_UI_closedFrame(_frameName): ## command triggered by closing of frame, will remember this so its closed upon refrshing
  397.     if(_frameName in ScriptLoader_GlobalSettings.window_UI_CategoryOpen):
  398.         ScriptLoader_GlobalSettings.window_UI_CategoryOpen.remove(_frameName)
  399.  
  400. def ScriptLoaderSystem_UI_scrollToPreviousPosition():
  401.     cmds.scrollLayout( ScriptLoader_GlobalSettings.window_UI_ScrollAttach , edit=True, sbp= ["down" , int(ScriptLoader_GlobalSettings.window_UI_ScrollBarLocation[0]) ])
  402.  
  403.  
  404. def ScriptLoaderSystem_UI_IconTextMode(): ## changes mode of script from icon to text or vice versa.
  405.     if ScriptLoader_GlobalSettings._IsIconMode == 'True': # Make Icon Only :
  406.         ScriptLoader_GlobalSettings._IsIconMode = 'False'
  407.         cmdMessage("ScriptLoader: TextMode" )
  408.     else:  
  409.         ScriptLoader_GlobalSettings._IsIconMode = 'True'
  410.         cmdMessage("ScriptLoader: IconMode" )
  411.  
  412.     ScriptLoaderSystem_UI_PopulateScripts()
  413.     WriteToPrefsFile()
  414.  
  415.  
  416. def ScriptLoaderSystem_UI_DockMode(): ## changes mode of script from Docked to Un-Docked or vice versa.
  417.     WriteToPrefsFile() 
  418.     if ScriptLoader_GlobalSettings.window_UI_DockedMode is True:
  419.         ScriptLoader_GlobalSettings.window_UI_DockedMode = False   
  420.         cmdMessage("ScriptLoader: Un-Docking " )
  421.     else:                      
  422.         ScriptLoader_GlobalSettings.window_UI_DockedMode = True
  423.         cmdMessage("ScriptLoader: Docking "  )
  424.  
  425.     ScriptLoaderSystem_UI_DockModeUpdate()
  426.     ScriptLoaderSystem_UI_PopulateScripts()
  427.  
  428. def deleteOldDockUiByName():
  429.     Scrpt_Ldr_DockUI_test = cmds.dockControl( 'ScriptLoader_Dock' , query = True , exists = True )
  430.     if Scrpt_Ldr_DockUI_test is True:
  431.         cmds.deleteUI( 'ScriptLoader_Dock' )
  432.     deleteOldDockUiByVar() 
  433.  
  434. def deleteOldDockUiByVar():
  435.     if(ScriptLoader_GlobalSettings.window_UI_DockUI is not None):
  436.         Scrpt_Ldr_DockUI_test = cmds.dockControl( ScriptLoader_GlobalSettings.window_UI_DockUI , query = True , exists = True )
  437.         if Scrpt_Ldr_DockUI_test is True:
  438.             cmds.deleteUI( ScriptLoader_GlobalSettings.window_UI_DockUI )
  439.  
  440. def ScriptLoaderSystem_UI_DockModeUpdate(): ## changes mode of script from Docked to Un-Docked or vice versa.
  441.     if ScriptLoader_GlobalSettings.window_UI_DockedMode is True:
  442.         cmds.button( _scriptLoader_window_Icons[1] , edit = True , label = '||' )
  443.         deleteOldDockUiByName()
  444.         ScriptLoader_GlobalSettings.window_UI_DockUI = cmds.dockControl( 'ScriptLoader_Dock' , fl = False , epo = False , r = False , area = 'left', aa = 'all' , content = ScriptLoader_GlobalSettings.window_UI_Name )
  445.     else:      
  446.         cmds.button( _scriptLoader_window_Icons[1] , edit = True , label = '[]' )
  447.         deleteOldDockUiByName()
  448.         ScriptLoaderSystem_UI() ## main window, only open this one time a session ..
  449.     ScriptLoaderSystem_UI_PopulateScripts() ## use created classes to create the buttons in the window
  450.  
  451.  
  452. def gotoFolder(_filePath):
  453.     try:
  454.         os.startfile( _filePath )
  455.     except AttributeError:
  456.         subprocess.call(['open', _filePath ])
  457.  
  458. def gotoPrefsFile(): ## opens the prefs file folder..
  459.     try:
  460.         os.startfile( variables("scriptPrefsPathFolder") )
  461.     except AttributeError:
  462.         subprocess.call(['open', variables("scriptPrefsPathFolder") ])
  463.  
  464. def resetPrefsFile(): ## deletes old prefs file..
  465.     # try:
  466.     #   os.remove( variables("scriptPrefsPath"))
  467.     # except AttributeError:
  468.     #   pass
  469.     cmdMessage("Resetting ScriptLoader settings: " )
  470.     ScriptLoader_GlobalSettings._UI_Position  = [10,10] ## Last known actual window position (edited at docking/undocking)
  471.     ScriptLoader_GlobalSettings._UI_WidthHeight  = Scrpt_Ldr_Win_W_H ## users prefs [190 - 180] by default
  472.     ScriptLoader_GlobalSettings._IsIconMode  = 'False' ## is in Icon state?
  473.     ScriptLoader_GlobalSettings._UI_MelColour = [.56 , .33 , .33] ## base color for all scripts
  474.     ScriptLoader_GlobalSettings._UI_PyColour = [.33 , .56 , .33] ## base color for all scripts
  475.     WriteToPrefsFile()
  476.     # print "cmds.deleteUI('Scrpt_Ldr_Win')"
  477.     # cmds.evalDeferred( ( "cmds.deleteUI('Scrpt_Ldr_Win')" ) ) # defer the delete so it doesnt crash Maya!
  478.     # # cmds.deleteUI('Scrpt_Ldr_Win', window = True )
  479.     # ScriptLoaderSystem_UI() ## main window, only open this one time a session ..
  480.     ScriptLoaderSystem_UI_PopulateScripts() ## use created classes to create the buttons in the window
  481.  
  482.  
  483. def ChangeColourBtn( _type):
  484.     if( _type == 'mel'):
  485.         cmds.colorEditor( rgb = ScriptLoader_GlobalSettings._UI_MelColour)     
  486.     if( _type == 'py'):
  487.         cmds.colorEditor( rgb = ScriptLoader_GlobalSettings._UI_PyColour)
  488.    
  489.     if cmds.colorEditor(query=True, result=True):
  490.         _result = cmds.colorEditor(query=True, rgb=True)
  491.         if( _type == 'mel'):
  492.             cmds.button('melBtn_Colour' , edit = True , bgc = _result )
  493.  
  494.         if( _type == 'py'):
  495.             cmds.button('pyBtn_Colour' , edit = True , bgc = _result )
  496.     else:
  497.         print 'Editor was dismissed'
  498.  
  499. def ResetColourBtn():
  500.     cmds.button('melBtn_Colour' , edit = True , bgc = ScriptLoader_GlobalSettings._UI_MelColour )
  501.     cmds.button('pyBtn_Colour' , edit = True , bgc = ScriptLoader_GlobalSettings._UI_PyColour )
  502.  
  503. def DefaultColourBtn():
  504.     cmds.button('melBtn_Colour' , edit = True , bgc = [.56 , .33 , .33] )
  505.     cmds.button('pyBtn_Colour' , edit = True , bgc = [.33 , .56 , .33] )
  506.  
  507. def ApplyColourBtn():
  508.     ScriptLoader_GlobalSettings._UI_MelColour = cmds.button('melBtn_Colour' , query = True , bgc = True )
  509.     ScriptLoader_GlobalSettings._UI_PyColour = cmds.button('pyBtn_Colour' , query = True , bgc = True )
  510.     WriteToPrefsFile()
  511.     if cmds.window('ColourWin', exists = True ):
  512.         cmds.deleteUI('ColourWin', window = True )
  513.     ScriptLoaderSystem_UI_PopulateScripts()
  514.  
  515.  
  516. def ScriptLoaderSystem_UI_ColourSettings():
  517.     ## add option here for prefs instead of on main..
  518.     ## need to display both the current version, and the new colours side by side also the actual float numbers!?
  519.     Scrpt_ColourWin = "ColourWin"
  520.     if cmds.window('ColourWin', exists = True ):
  521.         cmds.deleteUI('ColourWin', window = True )
  522.     if cmds.windowPref('ColourWin', exists = True ):   
  523.         cmds.windowPref( 'ColourWin', remove = True )
  524.  
  525.     Scrpt_Ldr_ColourWin = cmds.window( Scrpt_ColourWin , title=".: Script Loader Colour Settings :.", widthHeight=(351, 61) , toolbox = True )
  526.     cmds.rowColumnLayout( numberOfColumns=4 )
  527.     cmds.button(label = "Mel" , width = 100 , bgc =  ScriptLoader_GlobalSettings._UI_MelColour )
  528.     cmds.button(label = "Python" , width = 100 , bgc = ScriptLoader_GlobalSettings._UI_PyColour )
  529.     cmds.button(label = "Reset" , width = 75 , command = ( variables('toolID') + '.ResetColourBtn()'))
  530.     cmds.button(label = "Default" , width = 75 , command = ( variables('toolID') + '.DefaultColourBtn()'))
  531.  
  532.     cmds.button('melBtn_Colour' , label = "Change?" , bgc = ScriptLoader_GlobalSettings._UI_MelColour , command = ( variables('toolID') + '.ChangeColourBtn("mel")'))
  533.     cmds.button('pyBtn_Colour' , label = "Change?" , bgc = ScriptLoader_GlobalSettings._UI_PyColour , command = ( variables('toolID') + '.ChangeColourBtn("py")'))
  534.     cmds.button(label = "Apply \nNew" , command = ( variables('toolID') + '.ApplyColourBtn()'))
  535.     cmds.showWindow( Scrpt_Ldr_ColourWin)
  536.  
  537.  
  538. def ScriptLoaderSystem_UI():
  539.     deleteOldDockUiByName()
  540.     Scrpt_Ldr_Win = "Scrpt_Ldr_Win"
  541.     if cmds.window('Scrpt_Ldr_Win', exists = True ):
  542.         cmds.deleteUI('Scrpt_Ldr_Win', window = True )
  543.     if cmds.windowPref('Scrpt_Ldr_Win', exists = True ):   
  544.         cmds.windowPref( 'Scrpt_Ldr_Win', remove = True )
  545.        
  546.     ScriptLoader_GlobalSettings.window_UI_Name = cmds.window( Scrpt_Ldr_Win , widthHeight = ScriptLoader_GlobalSettings._UI_WidthHeight ,  
  547.         tlc = ScriptLoader_GlobalSettings._UI_Position ,  
  548.         rtf = True , toolbox = True )
  549.  
  550.     ScriptLoader_GlobalSettings.window_UI_PaneAttach = cmds.paneLayout( 'master_Scrpt_Ldr_Win' , parent = 'Scrpt_Ldr_Win' , shp = True , configuration='horizontal2' )
  551.     cmds.paneLayout( ScriptLoader_GlobalSettings.window_UI_PaneAttach , edit = True , ps = [ 1 , 0 , 1 ] )
  552.     cmds.rowColumnLayout( 'master_Scrpt_Ldr_Win_ColsHeader' , numberOfColumns = 2 ,  parent = ScriptLoader_GlobalSettings.window_UI_PaneAttach )       
  553.     cmds.rowColumnLayout( 'master_Scrpt_Ldr_Win_ColsHeader_Left' , numberOfColumns = 1 ,  parent = 'master_Scrpt_Ldr_Win_ColsHeader' )     
  554.     cmds.button( 'Script_Loader_WinUI_Btn_Rfrsh' , label = ( 'Script Loader' ) , align = 'left' , ann = ( 'Click to refresh scripts shown.' ) , width = ( ( 190 / 10 ) * 8 ) , parent = 'master_Scrpt_Ldr_Win_ColsHeader_Left' , command = ( variables('toolID') + '.ScriptLoaderSystem_Refresh()') )
  555.        
  556.     cmds.rowColumnLayout( 'master_Scrpt_Ldr_Win_ColsHeader_Right' , numberOfColumns = 2 ,  parent = 'master_Scrpt_Ldr_Win_ColsHeader' )        
  557.     _scriptLoader_window_Icons[0] = cmds.button( 'Script_Loader_WinUI_Btn_Icon' , label = '=' , ann = 'Icon or Text only mode button.' , width = ( 190 / 10 ) , parent = 'master_Scrpt_Ldr_Win_ColsHeader_Right' , command = ( variables('toolID') + '.ScriptLoaderSystem_UI_IconTextMode()') )
  558.     _scriptLoader_window_Icons[1] = cmds.button( 'Script_Loader_WinUI_Btn_Dock' , label = '[]' , ann = 'Docking or UnDocking mode button.' , width = ( 190 / 10 ) , parent = 'master_Scrpt_Ldr_Win_ColsHeader_Right' , command = ( variables('toolID') + '.ScriptLoaderSystem_UI_DockMode()') )
  559.  
  560.     _R_ClickOpts = cmds.popupMenu( parent = 'master_Scrpt_Ldr_Win' , button = 3 )
  561.     cmds.menuItem( label = 'Goto preference file' , parent = _R_ClickOpts , command = ( variables('toolID') + '.gotoPrefsFile()' ) )
  562.     cmds.menuItem( label = 'Reset preference file' , parent = _R_ClickOpts , command = ( variables('toolID') + '.resetPrefsFile()' ) )
  563.     # cmds.menuItem( label = 'Add me to shelf?' , parent = _R_ClickOpts , command = ( variables('toolID') + '.()' ) )
  564.     cmds.menuItem( label = 'Change Colourscheme?' , parent = _R_ClickOpts , command = ( variables('toolID') + '.ScriptLoaderSystem_UI_ColourSettings()' ) )
  565.     #opts
  566.     ScriptLoader_GlobalSettings.window_UI_PathBtn = cmds.button( label = ScriptLoader_GlobalSettings._ScriptsPath[0:15] , ann = ScriptLoader_GlobalSettings._ScriptsPath , parent = 'master_Scrpt_Ldr_Win_ColsHeader_Left' , command = ( variables('toolID') + '.ScriptLoaderSystem_UI_newFilePath()') )
  567.  
  568.     ## main header done, all scripts go below!
  569.     ScriptLoader_GlobalSettings.window_UI_ScrollAttach = cmds.scrollLayout( parent = ScriptLoader_GlobalSettings.window_UI_PaneAttach , cr = True , vst = 10 )  #all script catogories nested to this
  570.     cmds.showWindow( ScriptLoader_GlobalSettings.window_UI_Name )
  571.  
  572. ScriptLoader_GlobalSettings = ScriptClass_ScriptLoaderGlobalSettings()
  573.  
  574. def init():
  575.     LoadPrefsFile() ## getting local info or creating setup file ..
  576.     PopulateScriptClasses()  ## find all scripts and setup the list of classes/container
  577.     cmdMessage("Scripts loaded from disk: " + str(len(ScriptLoader_GlobalSettings.AllScriptClasses)) + " Scripts found." )
  578.     ScriptLoaderSystem_UI() ## main window, only open this one time a session ..
  579.     ScriptLoaderSystem_UI_PopulateScripts() ## use created classes to create the buttons in the window
  580.  
  581. init()
Advertisement
Add Comment
Please, Sign In to add comment