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