home *** CD-ROM | disk | FTP | other *** search
/ Windows News 2005 November / WNnov2005.iso / Windows / Equipement / Blender / blender-2.37a-windows.exe / $_5_ / .blender / scripts / console.py < prev    next >
Text File  |  2005-06-13  |  21KB  |  588 lines

  1. #!BPY
  2.  
  3. """
  4. Name: 'Interactive Console'
  5. Blender: 237
  6. Group: 'System'
  7. Tooltip: 'Interactive Python Console'
  8. """
  9.  
  10. __author__ = "Campbell Barton AKA Ideasman"
  11. __url__ = ["Author's homepage, http://members.iinet.net.au/~cpbarton/ideasman/", "blender", "elysiun", "Official Python site, http://www.python.org"]
  12. __bpydoc__ = """\
  13. This is an interactive console, similar to Python's own command line interpreter.  Since it is embedded in Blender, it has access to all Blender Python modules.
  14.  
  15. Those completely new to Python are recommended to check the link button above
  16. that points to its official homepage, with news, downloads and documentation.
  17.  
  18. Usage:<br>
  19.   Type your code and hit "Enter" to get it executed.<br>
  20.   - Right mouse click: Console Menu (Save output, etc);<br>
  21.   - Arrow keys: command history and cursor;<br>
  22.   - Shift + arrow keys: jump words;<br>
  23.   - Ctrl + Tab: auto compleate based on variable names and modules loaded -- multiple choices popup a menu;<br>
  24.   - Ctrl + Enter: multiline functions -- delays executing code until only Enter is pressed.
  25. """
  26.  
  27. import Blender
  28. from Blender import *
  29. import sys as python_sys
  30. import StringIO
  31. import types
  32.  
  33. # Constants
  34. __DELIMETERS__ = '. ,=+-*/%<>&~][{}():'
  35. __LINE_HISTORY__ = 200
  36.  
  37. global __LINE_HEIGHT__
  38. __LINE_HEIGHT__ = 14
  39. global __FONT_SIZE__
  40. __FONT_SIZE__ = "normal"
  41.  
  42.  
  43. '''
  44. # Generic Blender functions
  45. def getActScriptWinRect():
  46.     area = Window.GetAreaSize()
  47.     area = (area[0]-1, area[1]-1)
  48.     for scrInfo in Window.GetScreenInfo(Window.Types['SCRIPT'], 'win', ''):
  49.         if scrInfo['vertices'][2]-scrInfo['vertices'][0] == area[0]:
  50.             if scrInfo['vertices'][3]-scrInfo['vertices'][1] == area[1]:
  51.                 return scrInfo['vertices']
  52.     return None
  53. '''
  54.  
  55. class cmdLine:
  56.     # cmd: is the command string, or any other message
  57.     # type: 0:user input  1:program feedback  2:error message.  3:option feedback
  58.     # exe; 0- not yet executed   1:executed
  59.     def __init__(self, cmd, type, exe):
  60.         self.cmd = cmd
  61.         self.type = type
  62.         self.exe = exe
  63.  
  64. # Include external file with internal namespace
  65. def include(filename):
  66.     file = open(filename, 'r')
  67.     filedata = file.read()
  68.     file.close()
  69.     return compile(filedata, filename, 'exec')
  70.  
  71. # Writes command line data to a blender text file.
  72. def writeCmdData(cmdLineList, type):
  73.     if type == 3:
  74.         typeList = [0,1,2, 3, None] # all
  75.     else:
  76.         typeList = [type] # so we can use athe lists 'in' methiod
  77.     
  78.     newText = Text.New('command_output.py', 1)
  79.     for myCmd in cmdLineList:
  80.         if myCmd.type in typeList: # user input
  81.             newText.write('%s\n' % myCmd.cmd)
  82.     Draw.PupMenu('%s written' % newText.name)
  83.  
  84. def insertCmdData(cmdBuffer):
  85.     textNames = [tex.name for tex in Text.Get()]
  86.     if textNames:
  87.         choice = Draw.PupMenu('|'.join(textNames))
  88.         if choice != -1:
  89.             text = Text.Get()[choice-1]
  90.             
  91.             # Add the text!
  92.             for l in text.asLines():
  93.                 cmdBuffer.append(cmdLine('%s ' % l, 0, 0))
  94.             Draw.Redraw()
  95.     
  96.  
  97. COLLECTED_VAR_NAMES = {} # a list of keys, each key has a list of absolute paths
  98.  
  99. # Pain and simple recursice dir(), accepts a string
  100. def rdir(dirString):
  101.     global COLLECTED_VAR_NAMES
  102.     dirStringSplit = dirString.split('.')
  103.     
  104.     exec('dirList = dir(%s)' % dirString) 
  105.     for dirItem in dirList:
  106.         if not dirItem.startswith('_'):
  107.             if dirItem not in COLLECTED_VAR_NAMES.keys():
  108.                 COLLECTED_VAR_NAMES[dirItem] = []
  109.             
  110.             # Add the string
  111.             splitD = dirString.split('"')[-2]
  112.             if splitD not in COLLECTED_VAR_NAMES[dirItem]:
  113.                 COLLECTED_VAR_NAMES[dirItem].append(splitD)
  114.             
  115.             
  116.                 
  117.             # Stops recursice stuff, overlooping
  118.             if type(dirItem) == types.ClassType or \
  119.                  type(dirItem) == types.ModuleType:
  120.                 
  121.                 print dirString, splitD, dirItem
  122.                 
  123.                 # Dont loop up dirs for strings ints etc.
  124.                 if d not in dirStringSplit:
  125.                     rdir( '%s.%s' % (dirString, d)) 
  126.  
  127. def recursive_dir():
  128.     global COLLECTED_VAR_NAMES
  129.     
  130.     for name in __CONSOLE_VAR_DICT__.keys():
  131.         if not name.startswith('_'): # Dont pick names like __name__
  132.             rdir('__CONSOLE_VAR_DICT__["%s"]' % name)
  133.             #print COLLECTED_VAR_NAMES
  134.             COLLECTED_VAR_NAMES[name] = [''] 
  135.     return COLLECTED_VAR_NAMES
  136.  
  137. # Runs the code line(s) the user has entered and handle errors
  138. # As well as feeding back the output into the blender window.
  139. def runUserCode(__USER_CODE_STRING__):
  140.     global __CONSOLE_VAR_DICT__ # We manipulate the variables here. loading and saving from localspace to this global var.
  141.     
  142.     # Open A File like object to write all output to, that would useually be printed. 
  143.     python_sys.stdout.flush() # Get rid of whatever came before
  144.     __FILE_LIKE_STRING__ = StringIO.StringIO() # make a new file like string, this saves up from making a file.
  145.     __STD_OUTPUT__ = python_sys.stdout # we need to store the normal output.
  146.     python_sys.stdout=__FILE_LIKE_STRING__ # Now anything printed will be written to the file like string.
  147.     
  148.     # Try and run the user entered line(s)
  149.     try:
  150.         # Load all variabls from global dict to local space.
  151.         for __TMP_VAR_NAME__ in __CONSOLE_VAR_DICT__.keys():
  152.             exec('%s%s%s%s' % (__TMP_VAR_NAME__,'=__CONSOLE_VAR_DICT__["', __TMP_VAR_NAME__, '"]'))
  153.         del __TMP_VAR_NAME__
  154.         
  155.         # Now all the vars are loaded, execute the code. # Newline thanks to phillip,
  156.         exec(compile(__USER_CODE_STRING__, 'blender_cmd.py', 'single')) #exec(compile(__USER_CODE_STRING__, 'blender_cmd.py', 'exec'))
  157.         
  158.         # Write local veriables to global __CONSOLE_VAR_DICT__
  159.         for __TMP_VAR_NAME__ in dir():
  160.             if    __TMP_VAR_NAME__ != '__FILE_LIKE_STRING__' and\
  161.                     __TMP_VAR_NAME__ != '__STD_OUTPUT__' and\
  162.                     __TMP_VAR_NAME__ != '__TMP_VAR_NAME__' and\
  163.                     __TMP_VAR_NAME__ != '__USER_CODE_STRING__':
  164.                 
  165.                 # Execute the local > global coversion.
  166.                 exec('%s%s' % ('__CONSOLE_VAR_DICT__[__TMP_VAR_NAME__]=', __TMP_VAR_NAME__))
  167.         del __TMP_VAR_NAME__
  168.     
  169.     except: # Prints the REAL exception.
  170.         error = str(python_sys.exc_value)
  171.         for errorLine in error.split('\n'):
  172.             cmdBuffer.append(cmdLine(errorLine, 2, None)) # new line to type into
  173.     
  174.     python_sys.stdout = __STD_OUTPUT__ # Go back to output to the normal blender console
  175.     
  176.     # Copy all new output to cmdBuffer
  177.     __FILE_LIKE_STRING__.seek(0) # the readline function requires that we go back to the start of the file.
  178.     for line in __FILE_LIKE_STRING__.readlines():
  179.         cmdBuffer.append(cmdLine(line, 1, None))
  180.         
  181.     cmdBuffer.append(cmdLine(' ', 0, 0)) # new line to type into
  182.     python_sys.stdout=__STD_OUTPUT__
  183.     __FILE_LIKE_STRING__.close()
  184.  
  185.  
  186.  
  187.  
  188.  
  189. #------------------------------------------------------------------------------#
  190. #                             event handling code                              #
  191. #------------------------------------------------------------------------------#
  192. def handle_event(evt, val):
  193.     
  194.     # Insert Char into the cammand line
  195.     def insCh(ch): # Instert a char
  196.         global cmdBuffer
  197.         global cursor
  198.         # Later account for a cursor variable
  199.         cmdBuffer[-1].cmd = ('%s%s%s' % ( cmdBuffer[-1].cmd[:cursor], ch, cmdBuffer[-1].cmd[cursor:]))
  200.     
  201.     #------------------------------------------------------------------------------#
  202.     #                        Define Complex Key Actions                            #
  203.     #------------------------------------------------------------------------------#
  204.     def actionEnterKey():
  205.         global histIndex, cursor, cmdBuffer
  206.         # Check for the neter kay hit
  207.         if Window.GetKeyQualifiers() & Window.Qual.CTRL: # HOLDING DOWN SHIFT, GO TO NEXT LINE.
  208.             cmdBuffer.append(cmdLine(' ', 0, 0))
  209.         else:
  210.             # Multiline code will still run with 1 line,
  211.             multiLineCode = ['if 1:'] 
  212.             if cmdBuffer[-1].cmd != ' ':
  213.                 multiLineCode = ['%s%s' % (' ', cmdBuffer[-1].cmd)] # added space for fake if.
  214.             else:
  215.                 cmdBuffer[-1].type = 1
  216.                 multiLineCode = []
  217.             cmdBuffer[-1].exe = 1
  218.             i = 2
  219.             while cmdBuffer[-i].exe == 0:
  220.                 if cmdBuffer[-i].cmd == ' ':# Tag as an output type so its not used in the key history
  221.                     cmdBuffer[-i].type = 1
  222.                 else: # space added at the start for added if 1: statement
  223.                     multiLineCode.append('%s%s' % (' ', cmdBuffer[-i].cmd) )
  224.                 
  225.                 # Mark as executed
  226.                 cmdBuffer[-i].exe = 1
  227.                 i+=1
  228.             
  229.             # add if to the end, reverse will make it the start.
  230.             multiLineCode.append('if 1:')
  231.             multiLineCode.reverse()
  232.             multiLineCode.append(' pass') # Now this is the end
  233.             
  234.             
  235.             runUserCode('\n'.join(multiLineCode))
  236.             
  237.             # Clear the output based on __LINE_HISTORY__
  238.             if len(cmdBuffer) > __LINE_HISTORY__:
  239.                 cmdBuffer = cmdBuffer[-__LINE_HISTORY__:]
  240.         
  241.         histIndex = cursor = -1 # Reset cursor and history
  242.     
  243.     def actionUpKey():
  244.         global histIndex, cmdBuffer
  245.         if abs(histIndex)+1 >= len(cmdBuffer):
  246.             histIndex = -1
  247.         histIndex -= 1
  248.         while cmdBuffer[histIndex].type != 0 and abs(histIndex) < len(cmdBuffer):
  249.             histIndex -= 1
  250.         if cmdBuffer[histIndex].type == 0: # we found one
  251.             cmdBuffer[-1].cmd = cmdBuffer[histIndex].cmd            
  252.     
  253.     def actionDownKey():
  254.         global histIndex, cmdBuffer
  255.         if histIndex >= -2:
  256.             histIndex = -len(cmdBuffer)
  257.         histIndex += 1
  258.         while cmdBuffer[histIndex].type != 0 and histIndex != -2:
  259.             histIndex += 1
  260.         if cmdBuffer[histIndex].type == 0: # we found one
  261.             cmdBuffer[-1].cmd = cmdBuffer[histIndex].cmd
  262.     
  263.     def actionRightMouse():
  264.         global __FONT_SIZE__
  265.         global __LINE_HEIGHT__
  266.         choice = Draw.PupMenu('Console Menu%t|Write Input Data (white)|Write Output Data (blue)|Write Error Data (red)|Write All Text|%l|Insert Blender text|%l|Font Size|%l|Help|%l|Quit')
  267.         # print choice
  268.         if choice == 1:
  269.             writeCmdData(cmdBuffer, 0) # type 0 user
  270.         elif choice == 2:
  271.             writeCmdData(cmdBuffer, 1) # type 1 user output
  272.         elif choice == 3:
  273.             writeCmdData(cmdBuffer, 2) # type 2 errors
  274.         elif choice == 4:
  275.             writeCmdData(cmdBuffer, 3) # All
  276.         elif choice == 6:
  277.             insertCmdData(cmdBuffer) # All
  278.         elif choice == 8:
  279.             # Fontsize.
  280.             font_choice = Draw.PupMenu('Font Size%t|Large|Normal|Small|Tiny')
  281.             if font_choice != -1:
  282.                 if font_choice == 1:
  283.                     __FONT_SIZE__ = 'large'
  284.                     __LINE_HEIGHT__ = 16
  285.                 elif font_choice == 2:
  286.                     __FONT_SIZE__ = 'normal'
  287.                     __LINE_HEIGHT__ = 14
  288.                 elif font_choice == 3:
  289.                     __FONT_SIZE__ = 'small'
  290.                     __LINE_HEIGHT__ = 12
  291.                 elif font_choice == 4:
  292.                     __FONT_SIZE__ = 'tiny'
  293.                     __LINE_HEIGHT__ = 10
  294.                 Draw.Redraw()
  295.         elif choice == 10:
  296.             Blender.ShowHelp('console.py')
  297.         elif choice == 12: # Exit
  298.             Draw.Exit()
  299.     
  300.     
  301.     # Auto compleating, quite complex- use recutsice dir for the moment.
  302.     def actionAutoCompleate(): # Ctrl + Tab
  303.         RECURSIVE_DIR = recursive_dir()
  304.         
  305.         # get last name of user input
  306.         editVar = cmdBuffer[-1].cmd[:cursor]
  307.         
  308.         # Split off spaces operators etc from the staryt of the command so we can use the startswith function.
  309.         for splitChar in __DELIMETERS__:
  310.             editVar = editVar.split(splitChar)[-1]
  311.         
  312.         # Now we should have the var by its self
  313.         if editVar:
  314.             
  315.             possibilities = []
  316.             
  317.             print editVar, 'editVar'
  318.             for __TMP_VAR_NAME__ in RECURSIVE_DIR.keys():
  319.                 if __TMP_VAR_NAME__ == editVar:
  320.                     # print 'ADITVAR IS A VAR'
  321.                     continue
  322.                 elif __TMP_VAR_NAME__.startswith( editVar ):
  323.                     possibilities.append( __TMP_VAR_NAME__ )
  324.                     
  325.                     
  326.             if len(possibilities) == 1:
  327.                 cmdBuffer[-1].cmd = ('%s%s%s' % (cmdBuffer[-1].cmd[:cursor - len(editVar)], possibilities[0], cmdBuffer[-1].cmd[cursor:]))    
  328.             
  329.             elif possibilities: # If its not just []
  330.                 # -1 with insert is the second last.
  331.                 
  332.                 # Text choice
  333.                 #cmdBuffer.insert(-1, cmdLine('options: %s' % ' '.join(possibilities), 3, None))
  334.                 
  335.                 menuText = 'Choices (hold shift for whole name)%t|' 
  336.                 menuList = []
  337.                 menuListAbs = []
  338.                 possibilities.sort() # make nice :)
  339.                 for __TMP_VAR_NAME__ in possibilities:
  340.                     for usage in RECURSIVE_DIR[__TMP_VAR_NAME__]:
  341.                         # Account for non absolute (variables for eg.)
  342.                         if usage: # not ''
  343.                             menuListAbs.append('%s.%s' % (usage, __TMP_VAR_NAME__)) # Used for names and can be entered when pressing shift.
  344.                         else:
  345.                             menuListAbs.append(__TMP_VAR_NAME__) # Used for names and can be entered when pressing shift.
  346.                             
  347.                         menuList.append(__TMP_VAR_NAME__) # Used for non Shift
  348.                 
  349.                 
  350.                 #choice = Draw.PupMenu('Select Variabe name%t|' + '|'.join(possibilities)  )
  351.                 choice = Draw.PupMenu(menuText + '|'.join(menuListAbs))
  352.                 if choice != -1:
  353.                     
  354.                     if not Window.GetKeyQualifiers() & Window.Qual.SHIFT: # Only paste in the Short name
  355.                         cmdBuffer[-1].cmd = ('%s%s%s' % (cmdBuffer[-1].cmd[:cursor - len(editVar)], menuList[choice-1], cmdBuffer[-1].cmd[cursor:]))    
  356.                     else: # Put in the long name
  357.                         cmdBuffer[-1].cmd = ('%s%s%s' % (cmdBuffer[-1].cmd[:cursor - len(editVar)], menuListAbs[choice-1], cmdBuffer[-1].cmd[cursor:]))    
  358.         else:
  359.             # print 'NO EDITVAR'
  360.             return
  361.         
  362.     # ------------------end------------------# 
  363.     
  364.     
  365.     #if (evt == Draw.ESCKEY and not val):
  366.     #    Draw.Exit()
  367.     if evt == Draw.MOUSEX: # AVOID TOO MANY REDRAWS.
  368.         return
  369.     elif evt == Draw.MOUSEY:
  370.         return
  371.     
  372.     
  373.     global cursor
  374.     global histIndex    
  375.     
  376.     ascii = Blender.event
  377.     
  378.     #------------------------------------------------------------------------------#
  379.     #                             key codes and key handling                       #
  380.     #------------------------------------------------------------------------------#
  381.  
  382.     # UP DOWN ARROW KEYS, TO TRAVERSE HISTORY
  383.     if (evt == Draw.UPARROWKEY and val): actionUpKey()
  384.     elif (evt == Draw.DOWNARROWKEY and val): actionDownKey()
  385.     
  386.     elif (evt == Draw.RIGHTARROWKEY and val):
  387.         if Window.GetKeyQualifiers() & Window.Qual.SHIFT:
  388.             wordJump = False
  389.             newCursor = cursor+1
  390.             while newCursor<0:
  391.                 
  392.                 if cmdBuffer[-1].cmd[newCursor] not in __DELIMETERS__:
  393.                     newCursor+=1
  394.                 else:
  395.                     wordJump = True
  396.                     break
  397.             if wordJump: # Did we find a new cursor pos?
  398.                 cursor = newCursor
  399.             else:
  400.                 cursor = -1 # end of line
  401.         else:
  402.             cursor +=1
  403.             if cursor > -1:
  404.                 cursor = -1
  405.     
  406.     elif (evt == Draw.LEFTARROWKEY and val):
  407.         if Window.GetKeyQualifiers() & Window.Qual.SHIFT:
  408.             wordJump = False
  409.             newCursor = cursor-1
  410.             while abs(newCursor) < len(cmdBuffer[-1].cmd):
  411.                 
  412.                 if cmdBuffer[-1].cmd[newCursor] not in __DELIMETERS__ or\
  413.                 newCursor == cursor:
  414.                     newCursor-=1
  415.                 else:
  416.                     wordJump = True
  417.                     break
  418.             if wordJump: # Did we find a new cursor pos?
  419.                 cursor = newCursor
  420.             else: 
  421.                 cursor = -len(cmdBuffer[-1].cmd) # Start of line
  422.             
  423.         else:
  424.             if len(cmdBuffer[-1].cmd) > abs(cursor):
  425.                 cursor -=1
  426.     
  427.     elif (evt == Draw.HOMEKEY and val):
  428.         cursor  = -len(cmdBuffer[-1].cmd)
  429.     
  430.     elif (evt == Draw.ENDKEY and val):
  431.         cursor = -1
  432.     
  433.     elif (evt == Draw.TABKEY and val):
  434.         if Window.GetKeyQualifiers() & Window.Qual.CTRL:
  435.             actionAutoCompleate()
  436.         else:
  437.             insCh('\t')    
  438.     
  439.     elif (evt == Draw.BACKSPACEKEY and val): cmdBuffer[-1].cmd = ('%s%s' % (cmdBuffer[-1].cmd[:cursor-1] , cmdBuffer[-1].cmd[cursor:]))
  440.     elif (evt == Draw.DELKEY and val) and cursor < -1:
  441.         cmdBuffer[-1].cmd = cmdBuffer[-1].cmd[:cursor] + cmdBuffer[-1].cmd[cursor+1:]
  442.         cursor +=1
  443.         
  444.     elif ((evt == Draw.RETKEY or evt == Draw.PADENTER) and val): actionEnterKey()
  445.     elif (evt == Draw.RIGHTMOUSE and not val):actionRightMouse(); return
  446.     
  447.     elif ascii:
  448.         insCh(chr(ascii))
  449.     else:
  450.         return # dont redraw.
  451.     Draw.Redraw()
  452.  
  453.  
  454. def draw_gui():
  455.     
  456.     # Get the bounds from ObleGL directly
  457.     __CONSOLE_RECT__ = BGL.Buffer(BGL.GL_FLOAT, 4)
  458.     BGL.glGetFloatv(BGL.GL_SCISSOR_BOX, __CONSOLE_RECT__) 
  459.     __CONSOLE_RECT__= __CONSOLE_RECT__.list
  460.     
  461.     # Clear the screen
  462.     BGL.glClearColor(0.0, 0.0, 0.0, 1.0)
  463.     BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)         # use it to clear the color buffer
  464.     
  465.     # Draw cursor location colour
  466.     cmd2curWidth = Draw.GetStringWidth(cmdBuffer[-1].cmd[:cursor], __FONT_SIZE__)
  467.     BGL.glColor3f(0.8, 0.2, 0.2)
  468.     if cmd2curWidth == 0:
  469.         BGL.glRecti(0,2,2, __LINE_HEIGHT__+2)
  470.     else:
  471.         BGL.glRecti(cmd2curWidth-2,2,cmd2curWidth, __LINE_HEIGHT__+2)
  472.     
  473.     BGL.glColor3f(1,1,1)
  474.     # Draw the set of cammands to the buffer
  475.     
  476.     consoleLineIdx = 1
  477.     wrapLineIndex = 0
  478.     while consoleLineIdx < len(cmdBuffer) and  __CONSOLE_RECT__[3] > consoleLineIdx*__LINE_HEIGHT__ :
  479.         if cmdBuffer[-consoleLineIdx].type == 0:
  480.             BGL.glColor3f(1, 1, 1)
  481.         elif cmdBuffer[-consoleLineIdx].type == 1:
  482.             BGL.glColor3f(.3, .3, 1)
  483.         elif cmdBuffer[-consoleLineIdx].type == 2:
  484.             BGL.glColor3f(1.0, 0, 0)
  485.         elif cmdBuffer[-consoleLineIdx].type == 3:
  486.             BGL.glColor3f(0, 0.8, 0)
  487.         else:
  488.             BGL.glColor3f(1, 1, 0)
  489.         
  490.         if consoleLineIdx == 1: # NEVER WRAP THE USER INPUT
  491.             BGL.glRasterPos2i(0, (__LINE_HEIGHT__*consoleLineIdx) - 8)
  492.             Draw.Text(cmdBuffer[-consoleLineIdx].cmd, __FONT_SIZE__)
  493.             
  494.         
  495.         else: # WRAP?
  496.             # LINE WRAP
  497.             if Draw.GetStringWidth(cmdBuffer[-consoleLineIdx].cmd, __FONT_SIZE__) >  __CONSOLE_RECT__[2]:
  498.                 wrapLineList = []
  499.                 copyCmd = [cmdBuffer[-consoleLineIdx].cmd, '']
  500.                 while copyCmd != ['','']:
  501.                     while Draw.GetStringWidth(copyCmd[0], __FONT_SIZE__) > __CONSOLE_RECT__[2]:
  502.                         #print copyCmd
  503.                         copyCmd[1] = '%s%s'% (copyCmd[0][-1], copyCmd[1]) # Add the char on the end
  504.                         copyCmd[0] = copyCmd[0][:-1]# remove last chat
  505.                     
  506.                     # Now we have copyCmd[0] at a good length we can print it.                    
  507.                     if copyCmd[0] != '':
  508.                         wrapLineList.append(copyCmd[0])
  509.                     
  510.                     copyCmd[0]=''
  511.                     copyCmd = [copyCmd[1], copyCmd[0]]
  512.                 
  513.                 # Now we have a list of lines, draw them (OpenGLs reverse ordering requires this odd change)
  514.                 wrapLineList.reverse()
  515.                 for wline in wrapLineList:
  516.                     BGL.glRasterPos2i(0, (__LINE_HEIGHT__*(consoleLineIdx + wrapLineIndex)) - 8)
  517.                     Draw.Text(wline, __FONT_SIZE__)
  518.                     wrapLineIndex += 1
  519.                 wrapLineIndex-=1 # otherwise we get a silly extra line.
  520.                 
  521.             else: # no wrapping.
  522.                 
  523.                 BGL.glRasterPos2i(0, (__LINE_HEIGHT__*(consoleLineIdx+wrapLineIndex)) - 8)
  524.                 Draw.Text(cmdBuffer[-consoleLineIdx].cmd, __FONT_SIZE__)
  525.             
  526.             
  527.         consoleLineIdx += 1
  528.             
  529.  
  530. # This recieves the event index, call a function from here depending on the event.
  531. def handle_button_event(evt):
  532.     pass
  533.  
  534.  
  535. # Run the console
  536. __CONSOLE_VAR_DICT__ = {} # Initialize var dict
  537.  
  538.  
  539. # Print Startup lines
  540. cmdBuffer = [cmdLine("Welcome to Ideasman's Blender Console", 1, None),\
  541.     cmdLine(' * Right Click:  Console Menu (Save output, etc.)', 1, None),\
  542.     cmdLine(' * Arrow Keys:  Command history and cursor', 1, None),\
  543.     cmdLine(' * Shift With Arrow Keys:  Jump words', 1, None),\
  544.     cmdLine(' * Ctrl + Tab:  Auto compleate based on variable names and modules loaded, multiple choices popup a menu', 1, None),\
  545.     cmdLine(' * Ctrl + Enter:  Multiline functions, delays executing code until only Enter is pressed.', 1, None)]
  546.     
  547. histIndex = cursor = -1 # How far back from the first letter are we? - in current CMD line, history if for moving up and down lines.
  548.  
  549. # Autoexec, startup code.
  550. console_autoexec  = '%s%s' % (Get('datadir'), '/console_autoexec.py')
  551. if not sys.exists(console_autoexec):
  552.     # touch the file
  553.     open(console_autoexec, 'w').close()
  554.     cmdBuffer.append(cmdLine('...console_autoexec.py not found, making new in scripts data dir', 1, None))
  555. else:
  556.     cmdBuffer.append(cmdLine('...Using existing console_autoexec.py in scripts data dir', 1, None))
  557.  
  558.  
  559.  
  560. #-Autoexec---------------------------------------------------------------------#
  561. # Just use the function to jump into local naming mode.
  562. # This is so we can loop through all of the autoexec functions / vars and add them to the __CONSOLE_VAR_DICT__
  563. def autoexecToVarList():
  564.     global __CONSOLE_VAR_DICT__ # write autoexec vars to this.
  565.     
  566.     # Execute an external py file as if local
  567.     exec(include(console_autoexec))
  568.     
  569.     # Write local to global __CONSOLE_VAR_DICT__ for reuse,
  570.     for __TMP_VAR_NAME__ in dir() + dir(Blender):
  571.         # Execute the local > global coversion.
  572.         exec('%s%s' % ('__CONSOLE_VAR_DICT__[__TMP_VAR_NAME__]=', __TMP_VAR_NAME__))
  573.         
  574. autoexecToVarList() # pass the blender module
  575. #-end autoexec-----------------------------------------------------------------#
  576.  
  577.  
  578. # Append new line to write to
  579. cmdBuffer.append(cmdLine(' ', 0, 0))
  580.  
  581. #------------------------------------------------------------------------------#
  582. #                    register the event handling code, GUI                     #
  583. #------------------------------------------------------------------------------#
  584. def main():
  585.     Draw.Register(draw_gui, handle_event, handle_button_event)
  586.  
  587. main()
  588.