Final merge of HEAD (bf-blender) into the orange branch.
[blender.git] / release / scripts / console.py
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   - Mousewheel: Scroll text
22   - Arrow keys: command history and cursor;<br>
23   - Shift + Backspace: Backspace whole word;<br>
24   - Shift + Arrow keys: jump words;<br>
25   - Ctrl + (+/- or mousewheel): Zoom text size;<br>
26   - Ctrl + Tab: auto compleate based on variable names and modules loaded -- multiple choices popup a menu;<br>
27   - Ctrl + Enter: multiline functions -- delays executing code until only Enter is pressed.
28 """
29 __author__ = "Campbell Barton AKA Ideasman"
30 __url__ = ["http://members.iinet.net.au/~cpbarton/ideasman/", "blender", "elysiun"]
31
32 import Blender
33 from Blender import *
34 import sys as python_sys
35 import StringIO
36 import types
37
38 # Constants
39 __DELIMETERS__ = '. ,=+-*/%<>&~][{}():\t'
40 __VARIABLE_DELIMETERS__ = ' ,=+-*/%<>&~{}():\t'
41
42 __LINE_HISTORY__ = 500
43
44 global __FONT_SIZE__
45
46 __FONT_SIZES__ = ( ('tiny', 10), ('small', 12), ('normal', 14), ('large', 16) )
47 __FONT_SIZE__ = 2 # index for the list above, normal default.
48
49 global __CONSOLE_LINE_OFFSET__
50 __CONSOLE_LINE_OFFSET__ = 0
51
52 '''
53 # Generic Blender functions
54 def getActScriptWinRect():
55         area = Window.GetAreaSize()
56         area = (area[0]-1, area[1]-1)
57         for scrInfo in Window.GetScreenInfo(Window.Types['SCRIPT'], 'win', ''):
58                 if scrInfo['vertices'][2]-scrInfo['vertices'][0] == area[0]:
59                         if scrInfo['vertices'][3]-scrInfo['vertices'][1] == area[1]:
60                                 return scrInfo['vertices']
61         return None
62 '''
63
64
65 # menuText, # per group
66 def PupMenuLess(menu, groupSize=35):
67         more = ['   more...']
68         less = ['   less...']
69         
70         menuList= menu.split('|')
71         
72         # No Less Needed, just call.
73         if len(menuList) < groupSize:
74                 return Draw.PupMenu(menu)
75         
76         title = menuList[0].split('%t')[0]
77         
78         # Split the list into groups
79         menuGroups = [[]]
80         for li in menuList[1:]:
81                 if len(menuGroups[-1]) < groupSize:
82                         menuGroups[-1].append(li)
83                 else:
84                         menuGroups.append([li])
85         
86         # Stores teh current menu group we are looking at
87         groupIdx = 0
88         while 1:
89                 # Give us a title with the menu number
90                 numTitle = [ ' '.join([title, str(groupIdx + 1), 'of', str(len(menuGroups)), '%t'])]
91                 if groupIdx == 0:
92                         menuString = '|'.join(numTitle + menuGroups[groupIdx] + more)
93                 elif groupIdx == len(menuGroups)-1:
94                         menuString = '|'.join(numTitle + less + menuGroups[groupIdx])
95                 else: # In the middle somewhere so Show a more and less
96                         menuString = '|'.join(numTitle + less + menuGroups[groupIdx] + more)
97                 result = Draw.PupMenu(menuString)
98                 # User Exit
99                 if result == -1:
100                         return -1
101                 
102                 if groupIdx == 0: # First menu
103                         if result-1 < groupSize:
104                                 return result
105                         else: # must be more
106                                 groupIdx +=1
107                 elif groupIdx == len(menuGroups): # Last Menu
108                         if result == 1: # Must be less
109                                 groupIdx -= 1
110                         else: # Must be a choice
111                                 return result + (groupIdx*groupSize)
112                         
113                 else:   
114                         if result == 1: # Must be less
115                                 groupIdx -= 1
116                         elif result-2 == groupSize:
117                                 groupIdx +=1
118                         else:
119                                 return result - 1 + (groupIdx*groupSize)
120                                 
121
122
123 def unzip(list):
124
125         """
126                 unzip: inverse of zip - converts a list of tuples into a tuple of lists
127                 
128                 e.g.
129                  a,b = unzip(zip(a,b))
130         
131                 * note: all tuples in list have to have the same length, if not,
132                                 this function will fail
133         """
134         
135         if len(list) == 0: return ()
136         l = []
137         for t in range(len(list[0])):
138                 l.append(map( lambda x,t=t: x[t], list ))
139         return tuple(l)
140
141
142
143 # Use newstyle classes, Im not bothering with inheretence
144 # but slots are faster.
145 class cmdLine(object):
146         __slots__ = [\
147         'cmd', # is the command string, or any other message
148         'type',# type: 0:user input  1:program feedback  2:error message.  3:option feedback
149         'exe' #  0- not yet executed   1:executed
150         ]
151         def __init__(self, cmd, type, exe):
152                 self.cmd = cmd
153                 self.type = type
154                 self.exe = exe
155
156 # Include external file with internal namespace
157 def include(filename):
158         file = open(filename, 'r')
159         filedata = file.read()
160         file.close()
161         return compile(filedata, filename, 'exec')
162
163 # Writes command line data to a blender text file.
164 def writeCmdData(cmdLineList, type):
165         if type == 3:
166                 typeList = [0,1,2, 3, None] # all
167         else:
168                 typeList = [type] # so we can use athe lists 'in' methiod
169         
170         newText = Text.New('command_output.py', 1)
171         for myCmd in cmdLineList:
172                 if myCmd.type in typeList: # user input
173                         newText.write('%s\n' % myCmd.cmd)
174         Draw.PupMenu('%s written' % newText.name)
175
176 def insertCmdData(cmdBuffer):
177         textNames = [tex.name for tex in Text.Get()]
178         if textNames:
179                 choice = Draw.PupMenu('|'.join(textNames))
180                 if choice != -1:
181                         text = Text.Get()[choice-1]
182                         
183                         # Add the text!
184                         for l in text.asLines():
185                                 cmdBuffer.append(cmdLine('%s ' % l, 0, 0))
186                         Draw.Redraw()
187         
188
189 COLLECTED_VAR_NAMES = {} # a list of keys, each key has a list of absolute paths
190
191 # Pain and simple recursice dir(), accepts a string
192 def rdir(dirString, depth=0):
193         
194         # MAX DEPTH SET HERE
195         if depth > 4:
196                 print 'maxdepoth reached.'
197                 return
198                 
199         global COLLECTED_VAR_NAMES
200         dirStringSplit = dirString.split('.')
201         
202         exec('dirList = dir(%s)' % dirString) 
203         for dirItem in dirList:
204                 if dirItem.startswith('_'):
205                         continue
206                         
207                 dirData = None
208                 try:
209                         # Rare cases this can mess up, material.shader was a problem.
210                         exec('dirData = %s.%s' % (dirString, dirItem))
211                         #print dirData
212                 except:
213                         # Dont bother with this data.
214                         continue
215                 
216                 if type(dirItem) != type('str'):
217                         print dirItem, type(dirItem)
218                 
219                 if dirItem not in COLLECTED_VAR_NAMES.keys():
220                         COLLECTED_VAR_NAMES[dirItem] = []
221                 
222                 # Add the string
223                 splitD = dirString.split('"')[-2]
224                 if splitD not in COLLECTED_VAR_NAMES[dirItem]:
225                         COLLECTED_VAR_NAMES[dirItem].append(splitD)
226                 
227                 
228                 # Stops recursice stuff, overlooping
229                 #print type(dirItem)
230                 #if type(dirData) == types.ClassType or \
231                 #        type(dirData) == types.ModuleType:
232                 
233                 if type(dirData) != types.StringType and\
234                 type(dirData) != types.DictType and\
235                 type(dirData) != types.DictionaryType and\
236                 type(dirData) != types.FloatType and\
237                 type(dirData) != types.IntType and\
238                 type(dirData) != types.NoneType and\
239                 type(dirData) != types.StringTypes and\
240                 type(dirData) != types.TypeType and\
241                 type(dirData) != types.TupleType and\
242                 type(dirData) != types.BuiltinFunctionType:
243                         # print type(dirData), dirItem
244                         # Dont loop up dirs for strings ints etc.
245                         if dirItem not in dirStringSplit:
246                                 rdir( '%s.%s' % (dirString, dirItem), depth+1)
247                 '''
248                 elif depth == 0: # Add local variables
249                         # print type(dirData), dirItem
250                         # Dont loop up dirs for strings ints etc.
251                         if dirItem not in dirStringSplit:
252                                 rdir( '%s.%s' % (dirString, dirItem), depth+1)
253                 '''
254
255 def recursive_dir():
256         global COLLECTED_VAR_NAMES
257         
258         for name in __CONSOLE_VAR_DICT__.keys():
259                 if not name.startswith('_'): # Dont pick names like __name__
260                         rdir('__CONSOLE_VAR_DICT__["%s"]' % name)
261                         #print COLLECTED_VAR_NAMES
262                         COLLECTED_VAR_NAMES[name] = [''] 
263         return COLLECTED_VAR_NAMES
264
265 # Runs the code line(s) the user has entered and handle errors
266 # As well as feeding back the output into the blender window.
267 def runUserCode(__USER_CODE_STRING__):
268         global __CONSOLE_VAR_DICT__ # We manipulate the variables here. loading and saving from localspace to this global var.
269         
270         # Open A File like object to write all output to, that would useually be printed. 
271         python_sys.stdout.flush() # Get rid of whatever came before
272         __FILE_LIKE_STRING__ = StringIO.StringIO() # make a new file like string, this saves up from making a file.
273         __STD_OUTPUT__ = python_sys.stdout # we need to store the normal output.
274         python_sys.stdout=__FILE_LIKE_STRING__ # Now anything printed will be written to the file like string.
275         
276         # Try and run the user entered line(s)
277         try:
278                 # Load all variabls from global dict to local space.
279                 for __TMP_VAR_NAME__, __TMP_VAR__ in __CONSOLE_VAR_DICT__.items():
280                         exec('%s%s' % (__TMP_VAR_NAME__,'=__TMP_VAR__'))
281                 del __TMP_VAR_NAME__
282                 del __TMP_VAR__
283                 
284                 # Now all the vars are loaded, execute the code. # Newline thanks to phillip,
285                 exec(compile(__USER_CODE_STRING__, 'blender_cmd.py', 'single')) #exec(compile(__USER_CODE_STRING__, 'blender_cmd.py', 'exec'))
286                 
287                 # Flush global dict, allow the user to remove items.
288                 __CONSOLE_VAR_DICT__ = {}
289                 
290                 # Write local veriables to global __CONSOLE_VAR_DICT__
291                 for __TMP_VAR_NAME__ in dir():
292                         if      __TMP_VAR_NAME__ != '__FILE_LIKE_STRING__' and\
293                                         __TMP_VAR_NAME__ != '__STD_OUTPUT__' and\
294                                         __TMP_VAR_NAME__ != '__TMP_VAR_NAME__' and\
295                                         __TMP_VAR_NAME__ != '__USER_CODE_STRING__':
296                                 
297                                 # Execute the local > global coversion.
298                                 exec('%s%s' % ('__CONSOLE_VAR_DICT__[__TMP_VAR_NAME__]=', __TMP_VAR_NAME__))
299                 del __TMP_VAR_NAME__
300         
301         except: # Prints the REAL exception.
302                 error = '%s:  %s' % (python_sys.exc_type, python_sys.exc_value)         
303                 for errorLine in error.split('\n'):
304                         cmdBuffer.append(cmdLine(errorLine, 2, None)) # new line to type into
305         
306         python_sys.stdout = __STD_OUTPUT__ # Go back to output to the normal blender console
307         
308         # Copy all new output to cmdBuffer
309         
310         __FILE_LIKE_STRING__.seek(0) # the readline function requires that we go back to the start of the file.
311         
312         for line in __FILE_LIKE_STRING__.readlines():
313                 cmdBuffer.append(cmdLine(line, 1, None))
314                 
315         cmdBuffer.append(cmdLine(' ', 0, 0)) # new line to type into
316         python_sys.stdout=__STD_OUTPUT__
317         __FILE_LIKE_STRING__.close()
318
319
320
321
322
323 #------------------------------------------------------------------------------#
324 #                             event handling code                              #
325 #------------------------------------------------------------------------------#
326 def handle_event(evt, val):
327         
328         # Insert Char into the cammand line
329         def insCh(ch): # Instert a char
330                 global cmdBuffer
331                 global cursor
332                 # Later account for a cursor variable
333                 cmdBuffer[-1].cmd = ('%s%s%s' % ( cmdBuffer[-1].cmd[:cursor], ch, cmdBuffer[-1].cmd[cursor:]))
334         
335         #------------------------------------------------------------------------------#
336         #                        Define Complex Key Actions                            #
337         #------------------------------------------------------------------------------#
338         def actionEnterKey():
339                 global histIndex, cursor, cmdBuffer
340                 
341                 def getIndent(string):
342                         # Gather white space to add in the previous line
343                         # Ignore the last char since its padding.
344                         whiteSpace = ''
345                         #for i in range(len(cmdBuffer[-1].cmd)):
346                         for i in range(len(string)-1):
347                                 if cmdBuffer[-1].cmd[i] == ' ' or cmdBuffer[-1].cmd[i] == '\t':
348                                         whiteSpace += string[i]
349                                 else:
350                                         break
351                         return whiteSpace
352                 
353                 # Are we in the moddle of a multiline part or not?
354                 # try be smart about it
355                 if cmdBuffer[-1].cmd.split('#')[0].rstrip().endswith(':'):
356                         # : indicates an indent is needed
357                         cmdBuffer.append(cmdLine('\t%s ' % getIndent(cmdBuffer[-1].cmd), 0, 0))
358                         print ': indicates an indent is needed'         
359                 
360                 elif cmdBuffer[-1].cmd[0] in [' ', '\t'] and len(cmdBuffer[-1].cmd) > 1 and cmdBuffer[-1].cmd.split():
361                         # white space at the start means he havnt finished the multiline.
362                         cmdBuffer.append(cmdLine('%s ' % getIndent(cmdBuffer[-1].cmd), 0, 0))
363                         print 'white space at the start means he havnt finished the multiline.'
364                 
365                 elif Window.GetKeyQualifiers() & Window.Qual.CTRL:
366                         # Crtl forces multiline
367                         cmdBuffer.append(cmdLine('%s ' % getIndent(cmdBuffer[-1].cmd), 0, 0))
368                         print 'Crtl forces multiline'                   
369                 
370                 else: # Execute multiline code block
371                         
372                         # Multiline code will still run with 1 line,
373                         multiLineCode = ['if 1:'] # End of the multiline first.
374                         
375                         # Seek the start of the file multiline
376                         i = 1
377                         while cmdBuffer[-i].exe == 0:
378                                 i+=1
379                         
380                         while i > 1:
381                                 i-=1
382                                 
383                                 if cmdBuffer[-i].cmd == ' ':# Tag as an output type so its not used in the key history
384                                         cmdBuffer[-i].type = 1
385                                 else: # Tab added at the start for added if 1: statement
386                                         multiLineCode.append('\t%s' % cmdBuffer[-i].cmd )
387                                 
388                                 # Mark as executed
389                                 cmdBuffer[-i].exe = 1                           
390                                 
391                         multiLineCode.append('\tpass') # reverse will make this the start.                      
392                         
393                         # Dubug, print the code that is executed.
394                         #for m in multiLineCode: print m
395                         
396                         runUserCode('\n'.join(multiLineCode))
397                         
398                         # Clear the output based on __LINE_HISTORY__
399                         if len(cmdBuffer) > __LINE_HISTORY__:
400                                 cmdBuffer = cmdBuffer[-__LINE_HISTORY__:]
401                 
402                 histIndex = cursor = -1 # Reset cursor and history
403         
404         def actionUpKey():
405                 global histIndex, cmdBuffer
406                 if abs(histIndex)+1 >= len(cmdBuffer):
407                         histIndex = -1
408                 histIndex -= 1
409                 while cmdBuffer[histIndex].type != 0 and abs(histIndex) < len(cmdBuffer):
410                         histIndex -= 1
411                 if cmdBuffer[histIndex].type == 0: # we found one
412                         cmdBuffer[-1].cmd = cmdBuffer[histIndex].cmd                    
413         
414         def actionDownKey():
415                 global histIndex, cmdBuffer
416                 if histIndex >= -2:
417                         histIndex = -len(cmdBuffer)
418                 histIndex += 1
419                 while cmdBuffer[histIndex].type != 0 and histIndex != -2:
420                         histIndex += 1
421                 if cmdBuffer[histIndex].type == 0: # we found one
422                         cmdBuffer[-1].cmd = cmdBuffer[histIndex].cmd
423         
424         def actionRightMouse():
425                 global __FONT_SIZE__
426                 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|Quit')
427                 
428                 if choice == 1:
429                         writeCmdData(cmdBuffer, 0) # type 0 user
430                 elif choice == 2:
431                         writeCmdData(cmdBuffer, 1) # type 1 user output
432                 elif choice == 3:
433                         writeCmdData(cmdBuffer, 2) # type 2 errors
434                 elif choice == 4:
435                         writeCmdData(cmdBuffer, 3) # All
436                 elif choice == 6:
437                         insertCmdData(cmdBuffer) # Insert text from Blender and run it.
438                 elif choice == 8:
439                         # Fontsize.
440                         font_choice = Draw.PupMenu('Font Size%t|Large|Normal|Small|Tiny')
441                         if font_choice != -1:
442                                 if font_choice == 1:
443                                         __FONT_SIZE__ = 3
444                                 elif font_choice == 2:
445                                         __FONT_SIZE__ = 2
446                                 elif font_choice == 3:
447                                         __FONT_SIZE__ = 1
448                                 elif font_choice == 4:
449                                         __FONT_SIZE__ = 0
450                                 Draw.Redraw()
451                                 
452                 elif choice == 10: # Exit
453                         Draw.Exit()
454         
455         
456         # Auto compleating, quite complex- use recutsice dir for the moment.
457         def actionAutoCompleate(): # Ctrl + Tab
458                 if not cmdBuffer[-1].cmd[:cursor].split():
459                         return
460                 
461                 
462                 RECURSIVE_DIR = recursive_dir()
463                 
464                 # get last name of user input
465                 editVar = cmdBuffer[-1].cmd[:cursor]
466                 # Split off spaces operators etc from the staryt of the command so we can use the startswith function.
467                 for splitChar in __VARIABLE_DELIMETERS__:
468                         editVar = editVar[:-1].split(splitChar)[-1] + editVar[-1]
469                 
470                 
471                 # Now we should have the var by its self
472                 if editVar:
473                         possibilities = []
474                         
475                         for __TMP_VAR_NAME__ in RECURSIVE_DIR.keys():
476                                 #print '\t', __TMP_VAR_NAME__
477                                 if __TMP_VAR_NAME__ == editVar:
478                                         # print 'ADITVAR IS A VAR'
479                                         pass
480                                 '''
481                                 elif __TMP_VAR_NAME__.startswith( editVar ):
482                                         print __TMP_VAR_NAME__, 'aaa'
483                                         possibilities.append( __TMP_VAR_NAME__ )
484                                 '''
485                                 possibilities.append( __TMP_VAR_NAME__ )
486                         
487                         if len(possibilities) == 1:
488                                 cmdBuffer[-1].cmd = ('%s%s%s' % (cmdBuffer[-1].cmd[:cursor - len(editVar)], possibilities[0], cmdBuffer[-1].cmd[cursor:]))    
489                         
490                         elif possibilities: # If its not just []
491                                 # -1 with insert is the second last.
492                                 
493                                 # Text choice
494                                 #cmdBuffer.insert(-1, cmdLine('options: %s' % ' '.join(possibilities), 3, None))
495                                 
496                                 menuList = [] # A lits of tuples- ABSOLUTE, RELATIVE
497                                 
498                                 for __TMP_VAR_NAME__ in possibilities:
499                                         for usage in RECURSIVE_DIR[__TMP_VAR_NAME__]:
500                                                 # Account for non absolute (variables for eg.)
501                                                 if usage: # not ''
502                                                         absName = '%s.%s' % (usage, __TMP_VAR_NAME__)
503                                                         if absName.find('.'+editVar) != -1 or\
504                                                         absName.startswith(editVar) or\
505                                                         __TMP_VAR_NAME__.startswith(editVar):
506                                                                 #print editVar, 'found in', absName
507                                                                 menuList.append( # Used for names and can be entered when pressing shift.
508                                                                   (absName, # Absolute name
509                                                                   __TMP_VAR_NAME__) # Relative name, non shift
510                                                                   )
511                                                 #else:
512                                                 #       if absName.find(editVar) != -1:
513                                                 #               menuList.append((__TMP_VAR_NAME__, __TMP_VAR_NAME__)) # Used for names and can be entered when pressing shift.
514                                 
515                                 # No items to display? no menu
516                                 if not menuList:
517                                         return
518                                         
519                                 menuList.sort()
520                                 
521                                 choice = PupMenuLess( # Menu for the user to choose the autocompleate
522                                 'Choices (Shift for Whole name, Ctrl for Docs)%t|' + # Title Text
523                                 '|'.join(['%s,  %s' % m for m in menuList])) # Use Absolute names m[0]
524                                 
525                                 if choice != -1:
526                                         if Window.GetKeyQualifiers() & Window.Qual.CTRL:  # Help
527                                                 cmdBuffer[-1].cmd = ('help(%s%s) ' % (cmdBuffer[-1].cmd[:cursor - len(editVar)], menuList[choice-1][0]))    
528                                         elif Window.GetKeyQualifiers() & Window.Qual.SHIFT:  # Put in the long name
529                                                 cmdBuffer[-1].cmd = ('%s%s%s' % (cmdBuffer[-1].cmd[:cursor - len(editVar)], menuList[choice-1][0], cmdBuffer[-1].cmd[cursor:]))    
530                                         else: # Only paste in the Short name
531                                                 cmdBuffer[-1].cmd = ('%s%s%s' % (cmdBuffer[-1].cmd[:cursor - len(editVar)], menuList[choice-1][1], cmdBuffer[-1].cmd[cursor:]))    
532                                                 
533                 else:
534                         # print 'NO EDITVAR'
535                         return
536                 
537         # ------------------end------------------ #
538         
539         # Quit from menu only
540         #if (evt == Draw.ESCKEY and not val):
541         #       Draw.Exit()
542         if evt == Draw.MOUSEX: # AVOID TOO MANY REDRAWS.
543                 return
544         elif evt == Draw.MOUSEY:
545                 return
546         
547         
548         
549         global cursor
550         global histIndex        
551         global __FONT_SIZE__
552         global __CONSOLE_LINE_OFFSET__
553         
554         ascii = Blender.event
555         
556         resetScroll = True
557         
558         #------------------------------------------------------------------------------#
559         #                             key codes and key handling                       #
560         #------------------------------------------------------------------------------#
561         
562         # UP DOWN ARROW KEYS, TO TRAVERSE HISTORY
563         if (evt == Draw.UPARROWKEY and val): actionUpKey()
564         elif (evt == Draw.DOWNARROWKEY and val): actionDownKey()
565         
566         elif (evt == Draw.RIGHTARROWKEY and val):
567                 if Window.GetKeyQualifiers() & Window.Qual.SHIFT:
568                         wordJump = False
569                         newCursor = cursor+1
570                         while newCursor<0:
571                                 
572                                 if cmdBuffer[-1].cmd[newCursor] not in __DELIMETERS__:
573                                         newCursor+=1
574                                 else:
575                                         wordJump = True
576                                         break
577                         if wordJump: # Did we find a new cursor pos?
578                                 cursor = newCursor
579                         else:
580                                 cursor = -1 # end of line
581                 else:
582                         cursor +=1
583                         if cursor > -1:
584                                 cursor = -1
585         
586         elif (evt == Draw.LEFTARROWKEY and val):
587                 if Window.GetKeyQualifiers() & Window.Qual.SHIFT:
588                         wordJump = False
589                         newCursor = cursor-1
590                         while abs(newCursor) < len(cmdBuffer[-1].cmd):
591                                 
592                                 if cmdBuffer[-1].cmd[newCursor] not in __DELIMETERS__ or\
593                                 newCursor == cursor:
594                                         newCursor-=1
595                                 else:
596                                         wordJump = True
597                                         break
598                         if wordJump: # Did we find a new cursor pos?
599                                 cursor = newCursor
600                         else: 
601                                 cursor = -len(cmdBuffer[-1].cmd) # Start of line
602                         
603                 else:
604                         if len(cmdBuffer[-1].cmd) > abs(cursor):
605                                 cursor -=1
606         
607         elif (evt == Draw.HOMEKEY and val):
608                 cursor  = -len(cmdBuffer[-1].cmd)
609         
610         elif (evt == Draw.ENDKEY and val):
611                 cursor = -1
612         
613         elif (evt == Draw.TABKEY and val):
614                 if Window.GetKeyQualifiers() & Window.Qual.CTRL:
615                         actionAutoCompleate()
616                 else:
617                         insCh('\t')     
618         
619         elif (evt == Draw.BACKSPACEKEY and val):
620                 if Window.GetKeyQualifiers() & Window.Qual.SHIFT:
621                         i = -1
622                         for d in __DELIMETERS__:
623                                 i = max(i, cmdBuffer[-1].cmd[:cursor-1].rfind(d))
624                         if i == -1:
625                                 i=0
626                         cmdBuffer[-1].cmd = ('%s%s' % (cmdBuffer[-1].cmd[:i] , cmdBuffer[-1].cmd[cursor:]))
627                         
628                 else:
629                         # Normal backspace.
630                         cmdBuffer[-1].cmd = ('%s%s' % (cmdBuffer[-1].cmd[:cursor-1] , cmdBuffer[-1].cmd[cursor:]))
631                         
632         elif (evt == Draw.DELKEY and val) and cursor < -1:
633                 cmdBuffer[-1].cmd = cmdBuffer[-1].cmd[:cursor] + cmdBuffer[-1].cmd[cursor+1:]
634                 cursor +=1
635                 
636         elif ((evt == Draw.RETKEY or evt == Draw.PADENTER) and val): actionEnterKey()
637         elif (evt == Draw.RIGHTMOUSE and not val): actionRightMouse(); return
638         
639         elif (evt == Draw.PADPLUSKEY or evt == Draw.EQUALKEY or evt == Draw.WHEELUPMOUSE) and val and Window.GetKeyQualifiers() & Window.Qual.CTRL:
640                 __FONT_SIZE__ += 1
641                 __FONT_SIZE__ = min(len(__FONT_SIZES__)-1, __FONT_SIZE__)
642         elif (evt == Draw.PADMINUS or evt == Draw.MINUSKEY or evt == Draw.WHEELDOWNMOUSE) and val and Window.GetKeyQualifiers() & Window.Qual.CTRL:
643                 __FONT_SIZE__ -=1
644                 __FONT_SIZE__ = max(0, __FONT_SIZE__)
645         
646         
647         elif evt == Draw.WHEELUPMOUSE and val:
648                 __CONSOLE_LINE_OFFSET__ += 1
649                 __CONSOLE_LINE_OFFSET__ = min(len(cmdBuffer)-2, __CONSOLE_LINE_OFFSET__)
650                 resetScroll = False
651                 
652         elif evt == Draw.WHEELDOWNMOUSE and val:
653                 __CONSOLE_LINE_OFFSET__ -= 1
654                 __CONSOLE_LINE_OFFSET__ = max(0, __CONSOLE_LINE_OFFSET__)
655                 resetScroll = False
656         
657
658         elif ascii:
659                 insCh(chr(ascii))
660         else:
661                 return # dont redraw.
662         
663         # If the user types in anything then scroll to bottom.
664         if resetScroll:
665                 __CONSOLE_LINE_OFFSET__ = 0
666         Draw.Redraw()
667
668
669 def draw_gui():
670         # Get the bounds from ObleGL directly
671         __CONSOLE_RECT__ = BGL.Buffer(BGL.GL_FLOAT, 4)
672         BGL.glGetFloatv(BGL.GL_SCISSOR_BOX, __CONSOLE_RECT__) 
673         __CONSOLE_RECT__= __CONSOLE_RECT__.list
674         
675         # Clear the screen
676         BGL.glClearColor(0.0, 0.0, 0.0, 1.0)
677         BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)         # use it to clear the color buffer
678         
679         
680         # Fixed margin. use a margin since 0 margin can be hard to seewhen close to a crt's edge.
681         margin = 4
682         
683         # Draw cursor location colour
684         if __CONSOLE_LINE_OFFSET__ == 0:
685                 cmd2curWidth = Draw.GetStringWidth(cmdBuffer[-1].cmd[:cursor], __FONT_SIZES__[__FONT_SIZE__][0])
686                 BGL.glColor3f(0.8, 0.2, 0.2)
687                 if cmd2curWidth == 0:
688                         BGL.glRecti(margin,2,margin+2, __FONT_SIZES__[__FONT_SIZE__][1]+2)
689                 else:
690                         BGL.glRecti(margin + cmd2curWidth-2,2, margin+cmd2curWidth, __FONT_SIZES__[__FONT_SIZE__][1]+2)
691         
692         BGL.glColor3f(1,1,1)
693         # Draw the set of cammands to the buffer
694         consoleLineIdx = __CONSOLE_LINE_OFFSET__ + 1
695         wrapLineIndex = 0
696         while consoleLineIdx < len(cmdBuffer) and  __CONSOLE_RECT__[3] > (consoleLineIdx - __CONSOLE_LINE_OFFSET__) * __FONT_SIZES__[__FONT_SIZE__][1]:
697                 if cmdBuffer[-consoleLineIdx].type == 0:
698                         BGL.glColor3f(1, 1, 1)
699                 elif cmdBuffer[-consoleLineIdx].type == 1:
700                         BGL.glColor3f(.3, .3, 1)
701                 elif cmdBuffer[-consoleLineIdx].type == 2:
702                         BGL.glColor3f(1.0, 0, 0)
703                 elif cmdBuffer[-consoleLineIdx].type == 3:
704                         BGL.glColor3f(0, 0.8, 0)
705                 else:  
706                         BGL.glColor3f(1, 1, 0)
707                 
708                 if consoleLineIdx == 1: # NEVER WRAP THE USER INPUT
709                         BGL.glRasterPos2i(margin, (__FONT_SIZES__[__FONT_SIZE__][1] * (consoleLineIdx-__CONSOLE_LINE_OFFSET__)) - 8)
710                         # BUG, LARGE TEXT DOSENT DISPLAY
711                         Draw.Text(cmdBuffer[-consoleLineIdx].cmd, __FONT_SIZES__[__FONT_SIZE__][0])
712                         
713                 
714                 else: # WRAP?
715                         # LINE WRAP
716                         if Draw.GetStringWidth(cmdBuffer[-consoleLineIdx].cmd, __FONT_SIZES__[__FONT_SIZE__][0]) >  __CONSOLE_RECT__[2]:
717                                 wrapLineList = []
718                                 copyCmd = [cmdBuffer[-consoleLineIdx].cmd, '']
719                                 while copyCmd != ['','']:
720                                         while margin + Draw.GetStringWidth(copyCmd[0], __FONT_SIZES__[__FONT_SIZE__][0]) > __CONSOLE_RECT__[2]:
721                                                 #print copyCmd
722                                                 copyCmd[1] = '%s%s'% (copyCmd[0][-1], copyCmd[1]) # Add the char on the end
723                                                 copyCmd[0] = copyCmd[0][:-1]# remove last chat
724                                         
725                                         # Now we have copyCmd[0] at a good length we can print it.                                      
726                                         if copyCmd[0] != '':
727                                                 wrapLineList.append(copyCmd[0])
728                                         
729                                         copyCmd[0]=''
730                                         copyCmd = [copyCmd[1], copyCmd[0]]
731                                 
732                                 # Now we have a list of lines, draw them (OpenGLs reverse ordering requires this odd change)
733                                 wrapLineList.reverse()
734                                 for wline in wrapLineList:
735                                         BGL.glRasterPos2i(margin, (__FONT_SIZES__[__FONT_SIZE__][1]*((consoleLineIdx-__CONSOLE_LINE_OFFSET__) + wrapLineIndex)) - 8)
736                                         Draw.Text(wline, __FONT_SIZES__[__FONT_SIZE__][0])
737                                         wrapLineIndex += 1
738                                 wrapLineIndex-=1 # otherwise we get a silly extra line.
739                                 
740                         else: # no wrapping.
741                                 
742                                 BGL.glRasterPos2i(margin, (__FONT_SIZES__[__FONT_SIZE__][1] * ((consoleLineIdx-__CONSOLE_LINE_OFFSET__)+wrapLineIndex)) - 8)
743                                 Draw.Text(cmdBuffer[-consoleLineIdx].cmd, __FONT_SIZES__[__FONT_SIZE__][0])
744                 
745                 consoleLineIdx += 1
746                         
747
748 # This recieves the event index, call a function from here depending on the event.
749 def handle_button_event(evt):
750         pass
751
752
753 # Run the console
754 __CONSOLE_VAR_DICT__ = {} # Initialize var dict
755
756
757 # Print Startup lines, add __bpydoc__ to the console startup.
758 cmdBuffer = []
759 for l in __bpydoc__.split('<br>'):
760         cmdBuffer.append( cmdLine(l, 1, None) )
761         
762
763 histIndex = cursor = -1 # How far back from the first letter are we? - in current CMD line, history if for moving up and down lines.
764
765 # Autoexec, startup code.
766 scriptDir = Get('scriptsdir')
767 if not scriptDir.endswith(Blender.sys.sep):
768         scriptDir += Blender.sys.sep
769
770 console_autoexec  = '%s%s' % (scriptDir, 'console_autoexec.py')
771
772 if not sys.exists(console_autoexec):
773         # touch the file
774         cmdBuffer.append(cmdLine('...console_autoexec.py not found, making new in scripts dir', 1, None))
775         open(console_autoexec, 'w').close()
776 else:
777         cmdBuffer.append(cmdLine('...Using existing console_autoexec.py in scripts dir', 1, None))
778
779
780
781 #-Autoexec---------------------------------------------------------------------#
782 # Just use the function to jump into local naming mode.
783 # This is so we can loop through all of the autoexec functions / vars and add them to the __CONSOLE_VAR_DICT__
784 def include_console(includeFile):
785         global __CONSOLE_VAR_DICT__ # write autoexec vars to this.
786         
787         # Execute an external py file as if local
788         exec(include(includeFile))
789         
790         # Write local to global __CONSOLE_VAR_DICT__ for reuse,
791         for __TMP_VAR_NAME__ in dir() + dir(Blender):
792                 # Execute the local > global coversion.
793                 exec('%s%s' % ('__CONSOLE_VAR_DICT__[__TMP_VAR_NAME__]=', __TMP_VAR_NAME__))
794                 
795 include_console(console_autoexec) # pass the blender module
796 #-end autoexec-----------------------------------------------------------------#
797
798
799 # Append new line to write to
800 cmdBuffer.append(cmdLine(' ', 0, 0))
801
802 #------------------------------------------------------------------------------#
803 #                    register the event handling code, GUI                     #
804 #------------------------------------------------------------------------------#
805 def main():
806         Draw.Register(draw_gui, handle_event, handle_button_event)
807
808 main()