1 """The PyCrust Shell is an interactive text control in which a user types in
2 commands to be sent to the interpreter. This particular shell is based on
3 wxPython's wxStyledTextCtrl. The latest files are always available at the
4 SourceForge project page at http://sourceforge.net/projects/pycrust/."""
6 __author__
= "Patrick K. O'Brien <pobrien@orbtech.com>"
8 __date__
= "July 1, 2001"
9 __version__
= "$Revision$"[11:-2]
11 from wxPython
.wx
import *
12 from wxPython
.stc
import *
16 from pseudo
import PseudoFileIn
17 from pseudo
import PseudoFileOut
18 from pseudo
import PseudoFileErr
19 from version
import VERSION
22 if wxPlatform
== '__WXMSW__':
23 faces
= { 'times' : 'Times New Roman',
24 'mono' : 'Courier New',
25 'helv' : 'Lucida Console',
26 'lucida' : 'Lucida Console',
27 'other' : 'Comic Sans MS',
32 # Versions of wxPython prior to 2.3.2 had a sizing bug on Win platform.
33 # The font was 2 points too large. So we need to reduce the font size.
34 if ((wxMAJOR_VERSION
, wxMINOR_VERSION
) == (2, 3) and wxRELEASE_NUMBER
< 2) \
35 or (wxMAJOR_VERSION
<= 2 and wxMINOR_VERSION
<= 2):
39 faces
= { 'times' : 'Times',
42 'other' : 'new century schoolbook',
50 """Simplified interface to all shell-related functionality.
52 This is a semi-transparent facade, in that all attributes of other are
53 still accessible, even though only some are visible to the user."""
55 name
= 'PyCrust Shell Interface'
56 revision
= __version__
58 def __init__(self
, other
):
59 """Create a ShellFacade instance."""
71 for method
in methods
:
72 self
.__dict
__[method
] = getattr(other
, method
)
75 d
['help'] = 'There is no help available, yet.'
78 def __getattr__(self
, name
):
79 if hasattr(self
.other
, name
):
80 return getattr(self
.other
, name
)
82 raise AttributeError, name
84 def __setattr__(self
, name
, value
):
85 if self
.__dict
__.has_key(name
):
86 self
.__dict
__[name
] = value
87 elif hasattr(self
.other
, name
):
88 return setattr(self
.other
, name
, value
)
90 raise AttributeError, name
92 def _getAttributeNames(self
):
93 """Return list of magic attributes to extend introspection."""
94 list = ['autoCallTip',
96 'autoCompleteCaseInsensitive',
97 'autoCompleteIncludeDouble',
98 'autoCompleteIncludeMagic',
99 'autoCompleteIncludeSingle',
105 class Shell(wxStyledTextCtrl
):
106 """PyCrust Shell based on wxStyledTextCtrl."""
108 name
= 'PyCrust Shell'
109 revision
= __version__
111 def __init__(self
, parent
, id=-1, pos
=wxDefaultPosition
, \
112 size
=wxDefaultSize
, style
=wxCLIP_CHILDREN
, introText
='', \
113 locals=None, InterpClass
=None, *args
, **kwds
):
114 """Create a PyCrust Shell instance."""
115 wxStyledTextCtrl
.__init
__(self
, parent
, id, pos
, size
, style
)
116 # Grab these so they can be restored by self.redirect* methods.
117 self
.stdin
= sys
.stdin
118 self
.stdout
= sys
.stdout
119 self
.stderr
= sys
.stderr
120 # Add the current working directory "." to the search path.
121 sys
.path
.insert(0, os
.curdir
)
122 # Import a default interpreter class if one isn't provided.
123 if InterpClass
== None:
124 from interpreter
import Interpreter
126 Interpreter
= InterpClass
127 # Create default locals so we have something interesting.
128 shellLocals
= {'__name__': 'PyShell',
129 '__doc__': 'PyShell, The PyCrust Python Shell.',
130 '__version__': VERSION
,
132 # Add the dictionary that was passed in.
134 shellLocals
.update(locals)
135 self
.interp
= Interpreter(locals=shellLocals
, \
136 rawin
=self
.readRaw
, \
137 stdin
=PseudoFileIn(self
.readIn
), \
138 stdout
=PseudoFileOut(self
.writeOut
), \
139 stderr
=PseudoFileErr(self
.writeErr
), \
141 # Keep track of the most recent prompt starting and ending positions.
142 self
.promptPos
= [0, 0]
143 # Keep track of the most recent non-continuation prompt.
144 self
.prompt1Pos
= [0, 0]
145 # Keep track of multi-line commands.
147 # Create the command history. Commands are added into the front of
148 # the list (ie. at index 0) as they are entered. self.historyIndex
149 # is the current position in the history; it gets incremented as you
150 # retrieve the previous command, decremented as you retrieve the
151 # next, and reset when you hit Enter. self.historyIndex == -1 means
152 # you're on the current command, not in the history.
154 self
.historyIndex
= -1
155 # Assign handlers for keyboard events.
156 EVT_KEY_DOWN(self
, self
.OnKeyDown
)
157 EVT_CHAR(self
, self
.OnChar
)
158 # Configure various defaults and user preferences.
160 # Display the introductory banner information.
161 try: self
.showIntro(introText
)
163 # Assign some pseudo keywords to the interpreter's namespace.
164 try: self
.setBuiltinKeywords()
166 # Add 'shell' to the interpreter's local namespace.
167 try: self
.setLocalShell()
169 # Do this last so the user has complete control over their
170 # environment. They can override anything they want.
171 try: self
.execStartupScript(self
.interp
.startupScript
)
178 """Configure shell based on user preferences."""
179 self
.SetMarginType(1, wxSTC_MARGIN_NUMBER
)
180 self
.SetMarginWidth(1, 40)
182 self
.SetLexer(wxSTC_LEX_PYTHON
)
183 self
.SetKeyWords(0, ' '.join(keyword
.kwlist
))
185 self
.setStyles(faces
)
186 self
.SetViewWhiteSpace(0)
189 # Do we want to automatically pop up command completion options?
190 self
.autoComplete
= 1
191 self
.autoCompleteIncludeMagic
= 1
192 self
.autoCompleteIncludeSingle
= 1
193 self
.autoCompleteIncludeDouble
= 1
194 self
.autoCompleteCaseInsensitive
= 1
195 self
.AutoCompSetIgnoreCase(self
.autoCompleteCaseInsensitive
)
196 # De we want to automatically pop up command argument help?
198 self
.CallTipSetBackground(wxColour(255, 255, 232))
200 def showIntro(self
, text
=''):
201 """Display introductory text in the shell."""
203 if not text
.endswith(os
.linesep
): text
+= os
.linesep
206 self
.write(self
.interp
.introText
)
207 except AttributeError:
210 def setBuiltinKeywords(self
):
211 """Create pseudo keywords as part of builtins.
213 This is a rather clever hack that sets "close", "exit" and "quit"
214 to a PseudoKeyword object so that we can make them do what we want.
215 In this case what we want is to call our self.quit() method.
216 The user can type "close", "exit" or "quit" without the final parens.
218 ## POB: This is having some weird side-effects so I'm taking it out.
219 ## import __builtin__
220 ## from pseudo import PseudoKeyword
221 ## __builtin__.close = __builtin__.exit = __builtin__.quit = \
222 ## PseudoKeyword(self.quit)
224 from pseudo
import PseudoKeyword
225 __builtin__
.close
= __builtin__
.exit
= __builtin__
.quit
= \
226 'Click on the close button to leave the application.'
229 """Quit the application."""
231 # XXX Good enough for now but later we want to send a close event.
233 # In the close event handler we can make sure they want to quit.
234 # Other applications, like PythonCard, may choose to hide rather than
235 # quit so we should just post the event and let the surrounding app
236 # decide what it wants to do.
237 self
.write('Click on the close button to leave the application.')
239 def setLocalShell(self
):
240 """Add 'shell' to locals as reference to ShellFacade instance."""
241 self
.interp
.locals['shell'] = ShellFacade(other
=self
)
243 def execStartupScript(self
, startupScript
):
244 """Execute the user's PYTHONSTARTUP script if they have one."""
245 if startupScript
and os
.path
.isfile(startupScript
):
246 startupText
= 'Startup script executed: ' + startupScript
247 self
.push('print %s;execfile(%s)' % \
248 (`startupText`
, `startupScript`
))
252 def setStyles(self
, faces
):
253 """Configure font size, typeface and color for lexer."""
256 self
.StyleSetSpec(wxSTC_STYLE_DEFAULT
, "face:%(mono)s,size:%(size)d" % faces
)
261 self
.StyleSetSpec(wxSTC_STYLE_LINENUMBER
, "back:#C0C0C0,face:%(mono)s,size:%(lnsize)d" % faces
)
262 self
.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR
, "face:%(mono)s" % faces
)
263 self
.StyleSetSpec(wxSTC_STYLE_BRACELIGHT
, "fore:#0000FF,back:#FFFF88")
264 self
.StyleSetSpec(wxSTC_STYLE_BRACEBAD
, "fore:#FF0000,back:#FFFF88")
267 self
.StyleSetSpec(wxSTC_P_DEFAULT
, "face:%(mono)s" % faces
)
268 self
.StyleSetSpec(wxSTC_P_COMMENTLINE
, "fore:#007F00,face:%(mono)s" % faces
)
269 self
.StyleSetSpec(wxSTC_P_NUMBER
, "")
270 self
.StyleSetSpec(wxSTC_P_STRING
, "fore:#7F007F,face:%(mono)s" % faces
)
271 self
.StyleSetSpec(wxSTC_P_CHARACTER
, "fore:#7F007F,face:%(mono)s" % faces
)
272 self
.StyleSetSpec(wxSTC_P_WORD
, "fore:#00007F,bold")
273 self
.StyleSetSpec(wxSTC_P_TRIPLE
, "fore:#7F0000")
274 self
.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE
, "fore:#000033,back:#FFFFE8")
275 self
.StyleSetSpec(wxSTC_P_CLASSNAME
, "fore:#0000FF,bold")
276 self
.StyleSetSpec(wxSTC_P_DEFNAME
, "fore:#007F7F,bold")
277 self
.StyleSetSpec(wxSTC_P_OPERATOR
, "")
278 self
.StyleSetSpec(wxSTC_P_IDENTIFIER
, "")
279 self
.StyleSetSpec(wxSTC_P_COMMENTBLOCK
, "fore:#7F7F7F")
280 self
.StyleSetSpec(wxSTC_P_STRINGEOL
, "fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled" % faces
)
282 def OnChar(self
, event
):
283 """Keypress event handler.
285 Prevents modification of previously submitted commands/responses."""
286 key
= event
.KeyCode()
287 currpos
= self
.GetCurrentPos()
288 if currpos
< self
.prompt1Pos
[1]:
290 stoppos
= self
.promptPos
[1]
292 # The dot or period key activates auto completion.
293 # Get the command between the prompt and the cursor.
294 # Add a dot to the end of the command.
295 command
= self
.GetTextRange(stoppos
, currpos
) + '.'
297 if self
.autoComplete
: self
.autoCompleteShow(command
)
298 elif key
== ord('('):
299 # The left paren activates a call tip and cancels
300 # an active auto completion.
301 if self
.AutoCompActive(): self
.AutoCompCancel()
302 # Get the command between the prompt and the cursor.
303 # Add the '(' to the end of the command.
304 command
= self
.GetTextRange(stoppos
, currpos
) + '('
306 if self
.autoCallTip
: self
.autoCallTipShow(command
)
307 # Hack to keep characters from entering when Alt or Control are down.
308 elif event
.ControlDown() or event
.AltDown():
311 # Allow the normal event handling to take place.
314 def OnKeyDown(self
, event
):
315 """Key down event handler.
317 Prevents modification of previously submitted commands/responses."""
318 key
= event
.KeyCode()
319 currpos
= self
.GetCurrentPos()
320 stoppos
= self
.promptPos
[1]
321 # If the auto-complete window is up let it do its thing.
322 if self
.AutoCompActive():
324 # Retrieve the previous command from the history buffer.
325 elif (event
.ControlDown() and key
== WXK_UP
) \
326 or (event
.AltDown() and key
in (ord('P'), ord('p'))):
327 self
.OnHistoryRetrieve(step
=+1)
328 # Retrieve the next command from the history buffer.
329 elif (event
.ControlDown() and key
== WXK_DOWN
) \
330 or (event
.AltDown() and key
in (ord('N'), ord('n'))):
331 self
.OnHistoryRetrieve(step
=-1)
332 # Search up the history for the text in front of the cursor.
334 self
.OnHistorySearch()
335 # Return is used to submit a command to the interpreter.
336 elif key
== WXK_RETURN
:
337 if self
.CallTipActive
: self
.CallTipCancel()
339 # Home needs to be aware of the prompt.
340 elif key
== WXK_HOME
:
341 if currpos
>= stoppos
:
342 if event
.ShiftDown():
343 # Select text from current position to end of prompt.
344 self
.SetSelection(self
.GetCurrentPos(), stoppos
)
346 self
.SetCurrentPos(stoppos
)
347 self
.SetAnchor(stoppos
)
350 # Basic navigation keys should work anywhere.
351 elif key
in (WXK_END
, WXK_LEFT
, WXK_RIGHT
, WXK_UP
, WXK_DOWN
, \
352 WXK_PRIOR
, WXK_NEXT
):
354 # Don't backspace over the latest prompt.
355 elif key
== WXK_BACK
:
356 if currpos
> self
.prompt1Pos
[1]:
358 # Only allow these keys after the latest prompt.
359 elif key
in (WXK_TAB
, WXK_DELETE
):
360 if currpos
>= self
.prompt1Pos
[1]:
362 # Don't toggle between insert mode and overwrite mode.
363 elif key
== WXK_INSERT
:
368 def OnHistoryRetrieve(self
, step
):
369 """Retrieve the previous/next command from the history buffer."""
370 startpos
= self
.GetCurrentPos()
371 if startpos
< self
.prompt1Pos
[1]:
373 newindex
= self
.historyIndex
+ step
374 if not (-1 <= newindex
< len(self
.history
)):
376 self
.historyIndex
= newindex
378 self
.ReplaceSelection('')
380 self
.ReplaceSelection('')
381 command
= self
.history
[self
.historyIndex
]
382 command
= command
.replace('\n', os
.linesep
+ sys
.ps2
)
383 self
.ReplaceSelection(command
)
384 endpos
= self
.GetCurrentPos()
385 self
.SetSelection(endpos
, startpos
)
387 def OnHistorySearch(self
):
388 """Search up the history buffer for the text in front of the cursor."""
389 startpos
= self
.GetCurrentPos()
390 if startpos
< self
.prompt1Pos
[1]:
392 # The text up to the cursor is what we search for.
393 numCharsAfterCursor
= self
.GetTextLength() - startpos
394 searchText
= self
.getCommand(rstrip
=0)
395 if numCharsAfterCursor
> 0:
396 searchText
= searchText
[:-numCharsAfterCursor
]
399 # Search upwards from the current history position and loop back
400 # to the beginning if we don't find anything.
401 if (self
.historyIndex
<= -1) \
402 or (self
.historyIndex
>= len(self
.history
)-2):
403 searchOrder
= range(len(self
.history
))
405 searchOrder
= range(self
.historyIndex
+1, len(self
.history
)) + \
406 range(self
.historyIndex
)
407 for i
in searchOrder
:
408 command
= self
.history
[i
]
409 if command
[:len(searchText
)] == searchText
:
410 # Replace the current selection with the one we've found.
411 self
.ReplaceSelection(command
[len(searchText
):])
412 endpos
= self
.GetCurrentPos()
413 self
.SetSelection(endpos
, startpos
)
414 # We've now warped into middle of the history.
415 self
.historyIndex
= i
418 def setStatusText(self
, text
):
419 """Display status information."""
421 # This method will most likely be replaced by the enclosing app
422 # to do something more interesting, like write to a status bar.
425 def processLine(self
):
426 """Process the line of text at which the user hit Enter."""
428 # The user hit ENTER and we need to decide what to do. They could be
429 # sitting on any line in the shell.
431 thepos
= self
.GetCurrentPos()
432 endpos
= self
.GetTextLength()
433 # If they hit RETURN at the very bottom, execute the command.
436 if self
.getCommand():
437 command
= self
.GetTextRange(self
.prompt1Pos
[1], endpos
)
439 # This is a hack, now that we allow editing of previous
440 # lines, which throws off our promptPos values.
441 newend
= endpos
- len(self
.getCommand(rstrip
=0))
442 command
= self
.GetTextRange(self
.prompt1Pos
[1], newend
)
443 command
= command
.replace(os
.linesep
+ sys
.ps2
, '\n')
445 # Or replace the current command with the other command.
446 elif thepos
< self
.prompt1Pos
[0]:
447 theline
= self
.GetCurrentLine()
448 command
= self
.getCommand(rstrip
=0)
449 # If the new line contains a command (even an invalid one).
451 command
= self
.getMultilineCommand()
452 self
.SetCurrentPos(endpos
)
453 startpos
= self
.prompt1Pos
[1]
454 self
.SetSelection(startpos
, endpos
)
455 self
.ReplaceSelection('')
458 # Otherwise, put the cursor back where we started.
460 self
.SetCurrentPos(thepos
)
461 self
.SetAnchor(thepos
)
462 # Or add a new line to the current single or multi-line command.
463 elif thepos
> self
.prompt1Pos
[1]:
464 self
.write(os
.linesep
)
468 def getMultilineCommand(self
, rstrip
=1):
469 """Extract a multi-line command from the editor.
471 The command may not necessarily be valid Python syntax."""
472 # XXX Need to extract real prompts here. Need to keep track of the
473 # prompt every time a command is issued.
478 # This is a total hack job, but it works.
479 text
= self
.GetCurLine()[0]
480 line
= self
.GetCurrentLine()
481 while text
[:ps2size
] == ps2
and line
> 0:
484 text
= self
.GetCurLine()[0]
485 if text
[:ps1size
] == ps1
:
486 line
= self
.GetCurrentLine()
488 startpos
= self
.GetCurrentPos() + ps1size
491 while self
.GetCurLine()[0][:ps2size
] == ps2
:
494 stoppos
= self
.GetCurrentPos()
495 command
= self
.GetTextRange(startpos
, stoppos
)
496 command
= command
.replace(os
.linesep
+ sys
.ps2
, '\n')
497 command
= command
.rstrip()
498 command
= command
.replace('\n', os
.linesep
+ sys
.ps2
)
502 command
= command
.rstrip()
505 def getCommand(self
, text
=None, rstrip
=1):
506 """Extract a command from text which may include a shell prompt.
508 The command may not necessarily be valid Python syntax."""
510 text
= self
.GetCurLine()[0]
511 # XXX Need to extract real prompts here. Need to keep track of the
512 # prompt every time a command is issued.
517 # Strip the prompt off the front of text leaving just the command.
518 if text
[:ps1size
] == ps1
:
519 command
= text
[ps1size
:]
520 elif text
[:ps2size
] == ps2
:
521 command
= text
[ps2size
:]
525 command
= command
.rstrip()
528 def push(self
, command
):
529 """Send command to the interpreter for execution."""
530 self
.write(os
.linesep
)
531 self
.more
= self
.interp
.push(command
)
533 self
.addHistory(command
.rstrip())
536 def addHistory(self
, command
):
537 """Add command to the command history."""
538 # Reset the history position.
539 self
.historyIndex
= -1
540 # Insert this command into the history, unless it's a blank
541 # line or the same as the last command.
543 and (len(self
.history
) == 0 or command
!= self
.history
[0]):
544 self
.history
.insert(0, command
)
546 def write(self
, text
):
547 """Display text in the shell.
549 Replace line endings with OS-specific endings."""
550 lines
= text
.split('\r\n')
551 for l
in range(len(lines
)):
552 chunks
= lines
[l
].split('\r')
553 for c
in range(len(chunks
)):
554 chunks
[c
] = os
.linesep
.join(chunks
[c
].split('\n'))
555 lines
[l
] = os
.linesep
.join(chunks
)
556 text
= os
.linesep
.join(lines
)
558 self
.EnsureCaretVisible()
559 #self.ScrollToColumn(0)
562 """Display appropriate prompt for the context, either ps1 or ps2.
564 If this is a continuation line, autoindent as necessary."""
566 prompt
= str(sys
.ps2
)
568 prompt
= str(sys
.ps1
)
569 pos
= self
.GetCurLine()[1]
570 if pos
> 0: self
.write(os
.linesep
)
571 self
.promptPos
[0] = self
.GetCurrentPos()
572 if not self
.more
: self
.prompt1Pos
[0] = self
.GetCurrentPos()
574 self
.promptPos
[1] = self
.GetCurrentPos()
576 self
.prompt1Pos
[1] = self
.GetCurrentPos()
577 # Keep the undo feature from undoing previous responses.
578 self
.EmptyUndoBuffer()
579 # XXX Add some autoindent magic here if more.
581 self
.write(' '*4) # Temporary hack indentation.
582 self
.EnsureCaretVisible()
583 self
.ScrollToColumn(0)
586 """Replacement for stdin."""
587 prompt
= 'Please enter your response:'
588 dialog
= wxTextEntryDialog(None, prompt
, \
589 'Input Dialog (Standard)', '')
591 if dialog
.ShowModal() == wxID_OK
:
592 text
= dialog
.GetValue()
593 self
.write(text
+ os
.linesep
)
599 def readRaw(self
, prompt
='Please enter your response:'):
600 """Replacement for raw_input."""
601 dialog
= wxTextEntryDialog(None, prompt
, \
602 'Input Dialog (Raw)', '')
604 if dialog
.ShowModal() == wxID_OK
:
605 text
= dialog
.GetValue()
611 def ask(self
, prompt
='Please enter your response:'):
612 """Get response from the user."""
613 return raw_input(prompt
=prompt
)
616 """Halt execution pending a response from the user."""
617 self
.ask('Press enter to continue:')
620 """Delete all text from the shell."""
623 def run(self
, command
, prompt
=1, verbose
=1):
624 """Execute command within the shell as if it was typed in directly.
625 >>> shell.run('print "this"')
630 # Go to the very bottom of the text.
631 endpos
= self
.GetTextLength()
632 self
.SetCurrentPos(endpos
)
633 command
= command
.rstrip()
634 if prompt
: self
.prompt()
635 if verbose
: self
.write(command
)
638 def runfile(self
, filename
):
639 """Execute all commands in file as if they were typed into the shell."""
640 file = open(filename
)
643 for command
in file.readlines():
644 if command
[:6] == 'shell.': # Run shell methods silently.
645 self
.run(command
, prompt
=0, verbose
=0)
647 self
.run(command
, prompt
=0, verbose
=1)
651 def autoCompleteShow(self
, command
):
652 """Display auto-completion popup list."""
653 list = self
.interp
.getAutoCompleteList(command
, \
654 includeMagic
=self
.autoCompleteIncludeMagic
, \
655 includeSingle
=self
.autoCompleteIncludeSingle
, \
656 includeDouble
=self
.autoCompleteIncludeDouble
)
658 options
= ' '.join(list)
660 self
.AutoCompShow(offset
, options
)
662 def autoCallTipShow(self
, command
):
663 """Display argument spec and docstring in a popup bubble thingie."""
664 if self
.CallTipActive
: self
.CallTipCancel()
665 tip
= self
.interp
.getCallTip(command
)
667 offset
= self
.GetCurrentPos()
668 self
.CallTipShow(offset
, tip
)
670 def writeOut(self
, text
):
671 """Replacement for stdout."""
674 def writeErr(self
, text
):
675 """Replacement for stderr."""
678 def redirectStdin(self
, redirect
=1):
679 """If redirect is true then sys.stdin will come from the shell."""
681 sys
.stdin
= PseudoFileIn(self
.readIn
)
683 sys
.stdin
= self
.stdin
685 def redirectStdout(self
, redirect
=1):
686 """If redirect is true then sys.stdout will go to the shell."""
688 sys
.stdout
= PseudoFileOut(self
.writeOut
)
690 sys
.stdout
= self
.stdout
692 def redirectStderr(self
, redirect
=1):
693 """If redirect is true then sys.stderr will go to the shell."""
695 sys
.stderr
= PseudoFileErr(self
.writeErr
)
697 sys
.stderr
= self
.stderr
700 """Return true if text is selected and can be cut."""
701 return self
.GetSelectionStart() != self
.GetSelectionEnd()
704 """Return true if text is selected and can be copied."""
705 return self
.GetSelectionStart() != self
.GetSelectionEnd()
708 wxID_SELECTALL
= NewId() # This *should* be defined by wxPython.
709 ID_AUTOCOMP
= NewId()
710 ID_AUTOCOMP_SHOW
= NewId()
711 ID_AUTOCOMP_INCLUDE_MAGIC
= NewId()
712 ID_AUTOCOMP_INCLUDE_SINGLE
= NewId()
713 ID_AUTOCOMP_INCLUDE_DOUBLE
= NewId()
714 ID_CALLTIPS
= NewId()
715 ID_CALLTIPS_SHOW
= NewId()
719 """Mixin class to add standard menu items."""
721 def createMenus(self
):
722 m
= self
.fileMenu
= wxMenu()
724 m
.Append(wxID_EXIT
, 'E&xit', 'Exit PyCrust')
726 m
= self
.editMenu
= wxMenu()
727 m
.Append(wxID_UNDO
, '&Undo \tCtrl+Z', 'Undo the last action')
728 m
.Append(wxID_REDO
, '&Redo \tCtrl+Y', 'Redo the last undone action')
730 m
.Append(wxID_CUT
, 'Cu&t', 'Cut the selection')
731 m
.Append(wxID_COPY
, '&Copy', 'Copy the selection')
732 m
.Append(wxID_PASTE
, '&Paste', 'Paste')
734 m
.Append(wxID_CLEAR
, 'Cle&ar', 'Delete the selection')
735 m
.Append(wxID_SELECTALL
, 'Select A&ll', 'Select all text')
737 m
= self
.autocompMenu
= wxMenu()
738 m
.Append(ID_AUTOCOMP_SHOW
, 'Show Auto Completion', \
739 'Show auto completion during dot syntax', \
741 m
.Append(ID_AUTOCOMP_INCLUDE_MAGIC
, 'Include Magic Attributes', \
742 'Include attributes visible to __getattr__ and __setattr__', \
744 m
.Append(ID_AUTOCOMP_INCLUDE_SINGLE
, 'Include Single Underscores', \
745 'Include attibutes prefixed by a single underscore', \
747 m
.Append(ID_AUTOCOMP_INCLUDE_DOUBLE
, 'Include Double Underscores', \
748 'Include attibutes prefixed by a double underscore', \
751 m
= self
.calltipsMenu
= wxMenu()
752 m
.Append(ID_CALLTIPS_SHOW
, 'Show Call Tips', \
753 'Show call tips with argument specifications', checkable
=1)
755 m
= self
.optionsMenu
= wxMenu()
756 m
.AppendMenu(ID_AUTOCOMP
, '&Auto Completion', self
.autocompMenu
, \
757 'Auto Completion Options')
758 m
.AppendMenu(ID_CALLTIPS
, '&Call Tips', self
.calltipsMenu
, \
761 m
= self
.helpMenu
= wxMenu()
763 m
.Append(wxID_ABOUT
, '&About...', 'About PyCrust')
765 b
= self
.menuBar
= wxMenuBar()
766 b
.Append(self
.fileMenu
, '&File')
767 b
.Append(self
.editMenu
, '&Edit')
768 b
.Append(self
.optionsMenu
, '&Options')
769 b
.Append(self
.helpMenu
, '&Help')
772 EVT_MENU(self
, wxID_EXIT
, self
.OnExit
)
773 EVT_MENU(self
, wxID_UNDO
, self
.OnUndo
)
774 EVT_MENU(self
, wxID_REDO
, self
.OnRedo
)
775 EVT_MENU(self
, wxID_CUT
, self
.OnCut
)
776 EVT_MENU(self
, wxID_COPY
, self
.OnCopy
)
777 EVT_MENU(self
, wxID_PASTE
, self
.OnPaste
)
778 EVT_MENU(self
, wxID_CLEAR
, self
.OnClear
)
779 EVT_MENU(self
, wxID_SELECTALL
, self
.OnSelectAll
)
780 EVT_MENU(self
, wxID_ABOUT
, self
.OnAbout
)
781 EVT_MENU(self
, ID_AUTOCOMP_SHOW
, \
782 self
.OnAutoCompleteShow
)
783 EVT_MENU(self
, ID_AUTOCOMP_INCLUDE_MAGIC
, \
784 self
.OnAutoCompleteIncludeMagic
)
785 EVT_MENU(self
, ID_AUTOCOMP_INCLUDE_SINGLE
, \
786 self
.OnAutoCompleteIncludeSingle
)
787 EVT_MENU(self
, ID_AUTOCOMP_INCLUDE_DOUBLE
, \
788 self
.OnAutoCompleteIncludeDouble
)
789 EVT_MENU(self
, ID_CALLTIPS_SHOW
, \
792 EVT_UPDATE_UI(self
, wxID_UNDO
, self
.OnUpdateMenu
)
793 EVT_UPDATE_UI(self
, wxID_REDO
, self
.OnUpdateMenu
)
794 EVT_UPDATE_UI(self
, wxID_CUT
, self
.OnUpdateMenu
)
795 EVT_UPDATE_UI(self
, wxID_COPY
, self
.OnUpdateMenu
)
796 EVT_UPDATE_UI(self
, wxID_PASTE
, self
.OnUpdateMenu
)
797 EVT_UPDATE_UI(self
, wxID_CLEAR
, self
.OnUpdateMenu
)
798 EVT_UPDATE_UI(self
, ID_AUTOCOMP_SHOW
, self
.OnUpdateMenu
)
799 EVT_UPDATE_UI(self
, ID_AUTOCOMP_INCLUDE_MAGIC
, self
.OnUpdateMenu
)
800 EVT_UPDATE_UI(self
, ID_AUTOCOMP_INCLUDE_SINGLE
, self
.OnUpdateMenu
)
801 EVT_UPDATE_UI(self
, ID_AUTOCOMP_INCLUDE_DOUBLE
, self
.OnUpdateMenu
)
802 EVT_UPDATE_UI(self
, ID_CALLTIPS_SHOW
, self
.OnUpdateMenu
)
804 def OnExit(self
, event
):
807 def OnUndo(self
, event
):
810 def OnRedo(self
, event
):
813 def OnCut(self
, event
):
816 def OnCopy(self
, event
):
819 def OnPaste(self
, event
):
822 def OnClear(self
, event
):
825 def OnSelectAll(self
, event
):
826 self
.shell
.SelectAll()
828 def OnAbout(self
, event
):
829 """Display an About PyCrust window."""
831 title
= 'About PyCrust'
832 text
= 'PyCrust %s\n\n' % VERSION
+ \
833 'Yet another Python shell, only flakier.\n\n' + \
834 'Half-baked by Patrick K. O\'Brien,\n' + \
835 'the other half is still in the oven.\n\n' + \
836 'Shell Revision: %s\n' % self
.shell
.revision
+ \
837 'Interpreter Revision: %s\n\n' % self
.shell
.interp
.revision
+ \
838 'Python Version: %s\n' % sys
.version
.split()[0] + \
839 'wxPython Version: %s\n' % wx
.__version
__ + \
840 'Platform: %s\n' % sys
.platform
841 dialog
= wxMessageDialog(self
, text
, title
, wxOK | wxICON_INFORMATION
)
845 def OnAutoCompleteShow(self
, event
):
846 self
.shell
.autoComplete
= event
.IsChecked()
848 def OnAutoCompleteIncludeMagic(self
, event
):
849 self
.shell
.autoCompleteIncludeMagic
= event
.IsChecked()
851 def OnAutoCompleteIncludeSingle(self
, event
):
852 self
.shell
.autoCompleteIncludeSingle
= event
.IsChecked()
854 def OnAutoCompleteIncludeDouble(self
, event
):
855 self
.shell
.autoCompleteIncludeDouble
= event
.IsChecked()
857 def OnCallTipsShow(self
, event
):
858 self
.shell
.autoCallTip
= event
.IsChecked()
860 def OnUpdateMenu(self
, event
):
861 """Update menu items based on current status."""
864 event
.Enable(self
.shell
.CanUndo())
865 elif id == wxID_REDO
:
866 event
.Enable(self
.shell
.CanRedo())
868 event
.Enable(self
.shell
.CanCut())
869 elif id == wxID_COPY
:
870 event
.Enable(self
.shell
.CanCopy())
871 elif id == wxID_PASTE
:
872 event
.Enable(self
.shell
.CanPaste())
873 elif id == wxID_CLEAR
:
874 event
.Enable(self
.shell
.CanCut())
875 elif id == ID_AUTOCOMP_SHOW
:
876 event
.Check(self
.shell
.autoComplete
)
877 elif id == ID_AUTOCOMP_INCLUDE_MAGIC
:
878 event
.Check(self
.shell
.autoCompleteIncludeMagic
)
879 elif id == ID_AUTOCOMP_INCLUDE_SINGLE
:
880 event
.Check(self
.shell
.autoCompleteIncludeSingle
)
881 elif id == ID_AUTOCOMP_INCLUDE_DOUBLE
:
882 event
.Check(self
.shell
.autoCompleteIncludeDouble
)
883 elif id == ID_CALLTIPS_SHOW
:
884 event
.Check(self
.shell
.autoCallTip
)
887 class ShellFrame(wxFrame
, ShellMenu
):
888 """Frame containing the PyCrust shell component."""
890 name
= 'PyCrust Shell Frame'
891 revision
= __version__
893 def __init__(self
, parent
=None, id=-1, title
='PyShell', \
894 pos
=wxDefaultPosition
, size
=wxDefaultSize
, \
895 style
=wxDEFAULT_FRAME_STYLE
, locals=None, \
896 InterpClass
=None, *args
, **kwds
):
897 """Create a PyCrust ShellFrame instance."""
898 wxFrame
.__init
__(self
, parent
, id, title
, pos
, size
, style
)
899 intro
= 'Welcome To PyCrust %s - The Flakiest Python Shell' % VERSION
900 self
.CreateStatusBar()
901 self
.SetStatusText(intro
)
902 if wxPlatform
== '__WXMSW__':
903 icon
= wxIcon('PyCrust.ico', wxBITMAP_TYPE_ICO
)
905 self
.shell
= Shell(parent
=self
, id=-1, introText
=intro
, \
906 locals=locals, InterpClass
=InterpClass
, \
908 # Override the shell so that status messages go to the status bar.
909 self
.shell
.setStatusText
= self
.SetStatusText