home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 October / maximum-cd-2011-10.iso / DiscContents / digsby_setup.exe / lib / wx / py / shell.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-06-22  |  36.3 KB  |  1,146 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. __author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
  5. __cvsid__ = '$Id: shell.py 46528 2007-06-18 19:09:00Z RD $'
  6. __revision__ = '$Revision: 46528 $'[11:-2]
  7. import wx
  8. from wx import stc
  9. import keyword
  10. import os
  11. import sys
  12. import time
  13. from buffer import Buffer
  14. import dispatcher
  15. import editwindow
  16. import frame
  17. from pseudo import PseudoFileIn
  18. from pseudo import PseudoFileOut
  19. from pseudo import PseudoFileErr
  20. from version import VERSION
  21. sys.ps3 = '<-- '
  22. NAVKEYS = (wx.WXK_END, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN, wx.WXK_PRIOR, wx.WXK_NEXT)
  23.  
  24. class ShellFrame(frame.Frame, frame.ShellFrameMixin):
  25.     name = 'Shell Frame'
  26.     revision = __revision__
  27.     
  28.     def __init__(self, parent = None, id = -1, title = 'PyShell', pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, locals = None, InterpClass = None, config = None, dataDir = None, *args, **kwds):
  29.         frame.Frame.__init__(self, parent, id, title, pos, size, style)
  30.         frame.ShellFrameMixin.__init__(self, config, dataDir)
  31.         if size == wx.DefaultSize:
  32.             self.SetSize((750, 525))
  33.         
  34.         intro = 'PyShell %s - The Flakiest Python Shell' % VERSION
  35.         self.SetStatusText(intro.replace('\n', ', '))
  36.         self.shell = Shell(parent = self, id = -1, introText = intro, locals = locals, InterpClass = InterpClass, startupScript = self.startupScript, execStartupScript = self.execStartupScript, *args, **kwds)
  37.         self.shell.setStatusText = self.SetStatusText
  38.         self.shell.SetFocus()
  39.         self.LoadSettings()
  40.  
  41.     
  42.     def OnClose(self, event):
  43.         if self.shell.waiting:
  44.             if event.CanVeto():
  45.                 event.Veto(True)
  46.             
  47.         else:
  48.             self.SaveSettings()
  49.             self.shell.destroy()
  50.             self.Destroy()
  51.  
  52.     
  53.     def OnAbout(self, event):
  54.         title = 'About PyShell'
  55.         text = 'PyShell %s\n\n' % VERSION + 'Yet another Python shell, only flakier.\n\n' + "Half-baked by Patrick K. O'Brien,\n" + 'the other half is still in the oven.\n\n' + 'Shell Revision: %s\n' % self.shell.revision + 'Interpreter Revision: %s\n\n' % self.shell.interp.revision + 'Platform: %s\n' % sys.platform + 'Python Version: %s\n' % sys.version.split()[0] + 'wxPython Version: %s\n' % wx.VERSION_STRING + '\t(%s)\n' % ', '.join(wx.PlatformInfo[1:])
  56.         dialog = wx.MessageDialog(self, text, title, wx.OK | wx.ICON_INFORMATION)
  57.         dialog.ShowModal()
  58.         dialog.Destroy()
  59.  
  60.     
  61.     def OnHelp(self, event):
  62.         frame.ShellFrameMixin.OnHelp(self, event)
  63.  
  64.     
  65.     def LoadSettings(self):
  66.         if self.config is not None:
  67.             frame.ShellFrameMixin.LoadSettings(self)
  68.             frame.Frame.LoadSettings(self, self.config)
  69.             self.shell.LoadSettings(self.config)
  70.         
  71.  
  72.     
  73.     def SaveSettings(self, force = False):
  74.         if self.config is not None:
  75.             frame.ShellFrameMixin.SaveSettings(self)
  76.             if self.autoSaveSettings or force:
  77.                 frame.Frame.SaveSettings(self, self.config)
  78.                 self.shell.SaveSettings(self.config)
  79.             
  80.         
  81.  
  82.     
  83.     def DoSaveSettings(self):
  84.         if self.config is not None:
  85.             self.SaveSettings(force = True)
  86.             self.config.Flush()
  87.         
  88.  
  89.  
  90. HELP_TEXT = '* Key bindings:\nHome              Go to the beginning of the command or line.\nShift+Home        Select to the beginning of the command or line.\nShift+End         Select to the end of the line.\nEnd               Go to the end of the line.\nCtrl+C            Copy selected text, removing prompts.\nCtrl+Shift+C      Copy selected text, retaining prompts.\nAlt+C             Copy to the clipboard, including prefixed prompts.\nCtrl+X            Cut selected text.\nCtrl+V            Paste from clipboard.\nCtrl+Shift+V      Paste and run multiple commands from clipboard.\nCtrl+Up Arrow     Retrieve Previous History item.\nAlt+P             Retrieve Previous History item.\nCtrl+Down Arrow   Retrieve Next History item.\nAlt+N             Retrieve Next History item.\nShift+Up Arrow    Insert Previous History item.\nShift+Down Arrow  Insert Next History item.\nF8                Command-completion of History item.\n                  (Type a few characters of a previous command and press F8.)\nCtrl+Enter        Insert new line into multiline command.\nCtrl+]            Increase font size.\nCtrl+[            Decrease font size.\nCtrl+=            Default font size.\nCtrl-Space        Show Auto Completion.\nCtrl-Alt-Space    Show Call Tip.\nShift+Enter       Complete Text from History.\nCtrl+F            Search\nF3                Search next\nCtrl+H            "hide" lines containing selection / "unhide"\nF12               on/off "free-edit" mode\n'
  91.  
  92. class ShellFacade:
  93.     name = 'Shell Interface'
  94.     revision = __revision__
  95.     
  96.     def __init__(self, other):
  97.         d = self.__dict__
  98.         d['other'] = other
  99.         d['helpText'] = HELP_TEXT
  100.  
  101.     
  102.     def help(self):
  103.         self.write(self.helpText)
  104.  
  105.     
  106.     def __getattr__(self, name):
  107.         if hasattr(self.other, name):
  108.             return getattr(self.other, name)
  109.         raise AttributeError, name
  110.  
  111.     
  112.     def __setattr__(self, name, value):
  113.         if self.__dict__.has_key(name):
  114.             self.__dict__[name] = value
  115.         elif hasattr(self.other, name):
  116.             setattr(self.other, name, value)
  117.         else:
  118.             raise AttributeError, name
  119.         return self.__dict__.has_key(name)
  120.  
  121.     
  122.     def _getAttributeNames(self):
  123.         list = [
  124.             'about',
  125.             'ask',
  126.             'autoCallTip',
  127.             'autoComplete',
  128.             'autoCompleteAutoHide',
  129.             'autoCompleteCaseInsensitive',
  130.             'autoCompleteIncludeDouble',
  131.             'autoCompleteIncludeMagic',
  132.             'autoCompleteIncludeSingle',
  133.             'callTipInsert',
  134.             'clear',
  135.             'pause',
  136.             'prompt',
  137.             'quit',
  138.             'redirectStderr',
  139.             'redirectStdin',
  140.             'redirectStdout',
  141.             'run',
  142.             'runfile',
  143.             'wrap',
  144.             'zoom']
  145.         list.sort()
  146.         return list
  147.  
  148.  
  149.  
  150. class Shell(editwindow.EditWindow):
  151.     name = 'Shell'
  152.     revision = __revision__
  153.     
  154.     def __init__(self, parent, id = -1, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.CLIP_CHILDREN, introText = '', locals = None, InterpClass = None, startupScript = None, execStartupScript = True, *args, **kwds):
  155.         editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
  156.         self.wrap()
  157.         if locals is None:
  158.             import __main__
  159.             locals = __main__.__dict__
  160.         
  161.         self.stdin = sys.stdin
  162.         self.stdout = sys.stdout
  163.         self.stderr = sys.stderr
  164.         if InterpClass == None:
  165.             Interpreter = Interpreter
  166.             import interpreter
  167.         else:
  168.             Interpreter = InterpClass
  169.         self.reader = PseudoFileIn(self.readline, self.readlines)
  170.         self.reader.input = ''
  171.         self.reader.isreading = False
  172.         self.interp = Interpreter(locals = locals, rawin = self.raw_input, stdin = self.reader, stdout = PseudoFileOut(self.writeOut), stderr = PseudoFileErr(self.writeErr), *args, **kwds)
  173.         self.buffer = Buffer()
  174.         self.autoCompleteKeys = self.interp.getAutoCompleteKeys()
  175.         self.promptPosStart = 0
  176.         self.promptPosEnd = 0
  177.         self.more = False
  178.         self.history = []
  179.         self.historyIndex = -1
  180.         self.noteMode = 0
  181.         self.MarkerDefine(0, stc.STC_MARK_ROUNDRECT)
  182.         self.searchTxt = ''
  183.         self.Bind(wx.EVT_CHAR, self.OnChar)
  184.         self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  185.         self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
  186.         self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI)
  187.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Cut()), id = wx.ID_CUT)
  188.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Copy()), id = wx.ID_COPY)
  189.         self.Bind((wx.EVT_MENU,), (lambda evt: self.CopyWithPrompts()), id = frame.ID_COPY_PLUS)
  190.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Paste()), id = wx.ID_PASTE)
  191.         self.Bind((wx.EVT_MENU,), (lambda evt: self.PasteAndRun()), id = frame.ID_PASTE_PLUS)
  192.         self.Bind((wx.EVT_MENU,), (lambda evt: self.SelectAll()), id = wx.ID_SELECTALL)
  193.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Clear()), id = wx.ID_CLEAR)
  194.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Undo()), id = wx.ID_UNDO)
  195.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Redo()), id = wx.ID_REDO)
  196.         self.waiting = False
  197.         self.Bind(wx.EVT_IDLE, self.OnIdle)
  198.         self.showIntro(introText)
  199.         self.setBuiltinKeywords()
  200.         self.setLocalShell()
  201.         if execStartupScript:
  202.             if startupScript is None:
  203.                 startupScript = os.environ.get('PYTHONSTARTUP')
  204.             
  205.             self.execStartupScript(startupScript)
  206.         else:
  207.             self.prompt()
  208.         wx.CallAfter(self.ScrollToLine, 0)
  209.  
  210.     
  211.     def clearHistory(self):
  212.         self.history = []
  213.         self.historyIndex = -1
  214.         dispatcher.send(signal = 'Shell.clearHistory')
  215.  
  216.     
  217.     def destroy(self):
  218.         del self.interp
  219.  
  220.     
  221.     def setFocus(self):
  222.         self.SetFocus()
  223.  
  224.     
  225.     def OnIdle(self, event):
  226.         if self.waiting:
  227.             time.sleep(0.05)
  228.         
  229.         event.Skip()
  230.  
  231.     
  232.     def showIntro(self, text = ''):
  233.         if text:
  234.             self.write(text)
  235.         
  236.         
  237.         try:
  238.             if self.interp.introText:
  239.                 if text and not text.endswith(os.linesep):
  240.                     self.write(os.linesep)
  241.                 
  242.                 self.write(self.interp.introText)
  243.         except AttributeError:
  244.             pass
  245.  
  246.  
  247.     
  248.     def setBuiltinKeywords(self):
  249.         import __builtin__
  250.         __builtin__.close = __builtin__.exit = __builtin__.quit = 'Click on the close button to leave the application.'
  251.  
  252.     
  253.     def quit(self):
  254.         self.write('Click on the close button to leave the application.')
  255.  
  256.     
  257.     def setLocalShell(self):
  258.         self.interp.locals['shell'] = ShellFacade(other = self)
  259.  
  260.     
  261.     def execStartupScript(self, startupScript):
  262.         if startupScript and os.path.isfile(startupScript):
  263.             text = 'Startup script executed: ' + startupScript
  264.             self.push('print %r; execfile(%r)' % (text, startupScript))
  265.             self.interp.startupScript = startupScript
  266.         else:
  267.             self.push('')
  268.  
  269.     
  270.     def about(self):
  271.         text = '\nAuthor: %r\nPy Version: %s\nPy Shell Revision: %s\nPy Interpreter Revision: %s\nPython Version: %s\nwxPython Version: %s\nwxPython PlatformInfo: %s\nPlatform: %s' % (__author__, VERSION, self.revision, self.interp.revision, sys.version.split()[0], wx.VERSION_STRING, str(wx.PlatformInfo), sys.platform)
  272.         self.write(text.strip())
  273.  
  274.     
  275.     def OnChar(self, event):
  276.         if self.noteMode:
  277.             event.Skip()
  278.             return None
  279.         if not self.CanEdit():
  280.             return None
  281.         key = event.GetKeyCode()
  282.         currpos = self.GetCurrentPos()
  283.         stoppos = self.promptPosEnd
  284.         if key in [
  285.             wx.WXK_RETURN,
  286.             wx.WXK_NUMPAD_ENTER]:
  287.             pass
  288.         elif key in self.autoCompleteKeys:
  289.             if self.AutoCompActive():
  290.                 self.AutoCompCancel()
  291.             
  292.             command = self.GetTextRange(stoppos, currpos) + chr(key)
  293.             self.write(chr(key))
  294.             if self.autoComplete:
  295.                 self.autoCompleteShow(command)
  296.             
  297.         elif key == ord('('):
  298.             if self.AutoCompActive():
  299.                 self.AutoCompCancel()
  300.             
  301.             self.ReplaceSelection('')
  302.             command = self.GetTextRange(stoppos, currpos) + '('
  303.             self.write('(')
  304.             self.autoCallTipShow(command, self.GetCurrentPos() == self.GetTextLength())
  305.         else:
  306.             event.Skip()
  307.  
  308.     
  309.     def OnKeyDown(self, event):
  310.         key = event.GetKeyCode()
  311.         if self.AutoCompActive():
  312.             event.Skip()
  313.             return None
  314.         controlDown = event.ControlDown()
  315.         altDown = event.AltDown()
  316.         shiftDown = event.ShiftDown()
  317.         currpos = self.GetCurrentPos()
  318.         endpos = self.GetTextLength()
  319.         selecting = self.GetSelectionStart() != self.GetSelectionEnd()
  320.         if controlDown and shiftDown and key in (ord('F'), ord('f')):
  321.             li = self.GetCurrentLine()
  322.             m = self.MarkerGet(li)
  323.             if m & 1:
  324.                 startP = self.PositionFromLine(li)
  325.                 self.MarkerDelete(li, 0)
  326.                 maxli = self.GetLineCount()
  327.                 li += 1
  328.                 li0 = li
  329.                 while li < maxli and self.GetLineVisible(li) == 0:
  330.                     li += 1
  331.                     continue
  332.                     self.AutoCompActive()
  333.                 endP = self.GetLineEndPosition(li - 1)
  334.                 self.ShowLines(li0, li - 1)
  335.                 self.SetSelection(startP, endP)
  336.                 return None
  337.             (startP, endP) = self.GetSelection()
  338.             endP -= 1
  339.             startL = self.LineFromPosition(startP)
  340.             endL = self.LineFromPosition(endP)
  341.             m = self.MarkerGet(startL)
  342.             self.MarkerAdd(startL, 0)
  343.             self.HideLines(startL + 1, endL)
  344.             self.SetCurrentPos(startP)
  345.         
  346.         if False and key == wx.WXK_F12:
  347.             if self.noteMode:
  348.                 self.promptPosEnd = self.PositionFromLine(self.GetLineCount() - 1) + len(str(sys.ps1))
  349.                 self.GotoLine(self.GetLineCount())
  350.                 self.GotoPos(self.promptPosEnd)
  351.                 self.prompt()
  352.                 self.SetCaretForeground('black')
  353.                 self.SetCaretWidth(1)
  354.                 self.SetCaretPeriod(500)
  355.             else:
  356.                 self.SetCaretForeground('red')
  357.                 self.SetCaretWidth(4)
  358.                 self.SetCaretPeriod(0)
  359.             self.noteMode = not (self.noteMode)
  360.             return None
  361.         if self.noteMode:
  362.             event.Skip()
  363.             return None
  364.         if (not controlDown and not shiftDown or not altDown) and key in [
  365.             wx.WXK_RETURN,
  366.             wx.WXK_NUMPAD_ENTER]:
  367.             self.processLine()
  368.         elif shiftDown and key in [
  369.             wx.WXK_RETURN,
  370.             wx.WXK_NUMPAD_ENTER]:
  371.             self.OnShowCompHistory()
  372.         elif controlDown and key in [
  373.             wx.WXK_RETURN,
  374.             wx.WXK_NUMPAD_ENTER]:
  375.             if self.CallTipActive():
  376.                 self.CallTipCancel()
  377.             
  378.             if currpos == endpos:
  379.                 self.processLine()
  380.             else:
  381.                 self.insertLineBreak()
  382.         elif controlDown and altDown:
  383.             event.Skip()
  384.         elif key == wx.WXK_ESCAPE:
  385.             if self.CallTipActive():
  386.                 event.Skip()
  387.             else:
  388.                 self.clearCommand()
  389.         elif key == wx.WXK_BACK and controlDown and shiftDown:
  390.             self.clearCommand()
  391.         elif controlDown and key in (ord(']'), wx.WXK_NUMPAD_ADD):
  392.             dispatcher.send(signal = 'FontIncrease')
  393.         elif controlDown and key in (ord('['), wx.WXK_NUMPAD_SUBTRACT):
  394.             dispatcher.send(signal = 'FontDecrease')
  395.         elif controlDown and key in (ord('='), wx.WXK_NUMPAD_DIVIDE):
  396.             dispatcher.send(signal = 'FontDefault')
  397.         elif (controlDown or key in (ord('X'), ord('x')) or shiftDown) and key == wx.WXK_DELETE:
  398.             self.Cut()
  399.         elif controlDown and not shiftDown and key in (ord('C'), ord('c'), wx.WXK_INSERT):
  400.             self.Copy()
  401.         elif controlDown and shiftDown and key in (ord('C'), ord('c'), wx.WXK_INSERT):
  402.             self.CopyWithPrompts()
  403.         elif altDown and not controlDown and key in (ord('C'), ord('c'), wx.WXK_INSERT):
  404.             self.CopyWithPromptsPrefixed()
  405.         elif key == wx.WXK_HOME:
  406.             home = self.promptPosEnd
  407.             if currpos > home:
  408.                 self.SetCurrentPos(home)
  409.                 if not selecting and not shiftDown:
  410.                     self.SetAnchor(home)
  411.                     self.EnsureCaretVisible()
  412.                 
  413.             else:
  414.                 event.Skip()
  415.         elif selecting and key not in NAVKEYS and not self.CanEdit():
  416.             pass
  417.         elif (controlDown and not shiftDown or key in (ord('V'), ord('v')) or shiftDown) and not controlDown and key == wx.WXK_INSERT:
  418.             self.Paste()
  419.         elif controlDown and key == wx.WXK_SPACE:
  420.             self.OnCallTipAutoCompleteManually(shiftDown)
  421.         elif controlDown and shiftDown and key in (ord('V'), ord('v')):
  422.             self.PasteAndRun()
  423.         elif (controlDown or key == wx.WXK_UP or altDown) and key in (ord('P'), ord('p')):
  424.             self.OnHistoryReplace(step = +1)
  425.         elif (controlDown or key == wx.WXK_DOWN or altDown) and key in (ord('N'), ord('n')):
  426.             self.OnHistoryReplace(step = -1)
  427.         elif (shiftDown or key == wx.WXK_UP) and self.CanEdit():
  428.             self.OnHistoryInsert(step = +1)
  429.         elif (shiftDown or key == wx.WXK_DOWN) and self.CanEdit():
  430.             self.OnHistoryInsert(step = -1)
  431.         elif key == wx.WXK_F8:
  432.             self.OnHistorySearch()
  433.         elif key == wx.WXK_BACK:
  434.             if selecting and self.CanEdit():
  435.                 event.Skip()
  436.             elif currpos > self.promptPosEnd:
  437.                 event.Skip()
  438.             
  439.         elif key in (wx.WXK_TAB, wx.WXK_DELETE):
  440.             if self.CanEdit():
  441.                 event.Skip()
  442.             
  443.         elif key == wx.WXK_INSERT:
  444.             pass
  445.         elif controlDown and key in (ord('L'), ord('l')):
  446.             pass
  447.         elif controlDown and key in (ord('T'), ord('t')):
  448.             pass
  449.         elif key in NAVKEYS:
  450.             event.Skip()
  451.         elif not self.CanEdit():
  452.             pass
  453.         else:
  454.             event.Skip()
  455.  
  456.     
  457.     def OnShowCompHistory(self):
  458.         his = self.history[:]
  459.         joined = ' '.join(his)
  460.         import re
  461.         newlist = re.split('[ \\.\\[\\]=}(\\)\\,0-9"]', joined)
  462.         thlist = []
  463.         for i in newlist:
  464.             if len(i) > 1:
  465.                 thlist.append(i)
  466.                 continue
  467.         
  468.         unlist = _[1]
  469.         unlist.sort((lambda a, b: cmp(a.lower(), b.lower())))
  470.         self.AutoCompSetIgnoreCase(True)
  471.         stringlist = ' '.join(unlist)
  472.         cpos = self.GetCurrentPos() - 1
  473.         while chr(self.GetCharAt(cpos)).isalnum():
  474.             cpos -= 1
  475.             continue
  476.             []
  477.         self.AutoCompShow(self.GetCurrentPos() - cpos - 1, stringlist)
  478.  
  479.     
  480.     def clearCommand(self):
  481.         startpos = self.promptPosEnd
  482.         endpos = self.GetTextLength()
  483.         self.SetSelection(startpos, endpos)
  484.         self.ReplaceSelection('')
  485.         self.more = False
  486.  
  487.     
  488.     def OnHistoryReplace(self, step):
  489.         self.clearCommand()
  490.         self.replaceFromHistory(step)
  491.  
  492.     
  493.     def replaceFromHistory(self, step):
  494.         ps2 = str(sys.ps2)
  495.         self.ReplaceSelection('')
  496.         newindex = self.historyIndex + step
  497.         if newindex <= newindex:
  498.             pass
  499.         elif newindex <= len(self.history):
  500.             self.historyIndex = newindex
  501.         
  502.         if newindex <= newindex:
  503.             pass
  504.         elif newindex <= len(self.history) - 1:
  505.             command = self.history[self.historyIndex]
  506.             command = command.replace('\n', os.linesep + ps2)
  507.             self.ReplaceSelection(command)
  508.         
  509.  
  510.     
  511.     def OnHistoryInsert(self, step):
  512.         if not self.CanEdit():
  513.             return None
  514.         startpos = self.GetCurrentPos()
  515.         self.replaceFromHistory(step)
  516.         endpos = self.GetCurrentPos()
  517.         self.SetSelection(endpos, startpos)
  518.  
  519.     
  520.     def OnHistorySearch(self):
  521.         if not self.CanEdit():
  522.             return None
  523.         startpos = self.GetCurrentPos()
  524.         numCharsAfterCursor = self.GetTextLength() - startpos
  525.         searchText = self.getCommand(rstrip = False)
  526.         if numCharsAfterCursor > 0:
  527.             searchText = searchText[:-numCharsAfterCursor]
  528.         
  529.         if not searchText:
  530.             return None
  531.         if self.historyIndex <= -1 or self.historyIndex >= len(self.history) - 2:
  532.             searchOrder = range(len(self.history))
  533.         else:
  534.             searchOrder = range(self.historyIndex + 1, len(self.history)) + range(self.historyIndex)
  535.         for i in searchOrder:
  536.             command = self.history[i]
  537.             if command[:len(searchText)] == searchText:
  538.                 self.ReplaceSelection(command[len(searchText):])
  539.                 endpos = self.GetCurrentPos()
  540.                 self.SetSelection(endpos, startpos)
  541.                 self.historyIndex = i
  542.                 break
  543.                 continue
  544.         
  545.  
  546.     
  547.     def setStatusText(self, text):
  548.         print text
  549.  
  550.     
  551.     def insertLineBreak(self):
  552.         if self.CanEdit():
  553.             self.write(os.linesep)
  554.             self.more = True
  555.             self.prompt()
  556.         
  557.  
  558.     
  559.     def processLine(self):
  560.         thepos = self.GetCurrentPos()
  561.         startpos = self.promptPosEnd
  562.         endpos = self.GetTextLength()
  563.         ps2 = str(sys.ps2)
  564.         if self.CanEdit():
  565.             self.SetCurrentPos(endpos)
  566.             self.interp.more = False
  567.             command = self.GetTextRange(startpos, endpos)
  568.             lines = command.split(os.linesep + ps2)
  569.             lines = [ line.rstrip() for line in lines ]
  570.             command = '\n'.join(lines)
  571.             if self.reader.isreading:
  572.                 self.reader.input = command
  573.                 self.write(os.linesep)
  574.             else:
  575.                 self.push(command)
  576.                 wx.FutureCall(1, self.EnsureCaretVisible)
  577.         elif self.getCommand(rstrip = False):
  578.             command = self.getMultilineCommand()
  579.             self.clearCommand()
  580.             self.write(command)
  581.         else:
  582.             self.SetCurrentPos(thepos)
  583.             self.SetAnchor(thepos)
  584.  
  585.     
  586.     def getMultilineCommand(self, rstrip = True):
  587.         ps1 = str(sys.ps1)
  588.         ps1size = len(ps1)
  589.         ps2 = str(sys.ps2)
  590.         ps2size = len(ps2)
  591.         text = self.GetCurLine()[0]
  592.         line = self.GetCurrentLine()
  593.         while text[:ps2size] == ps2 and line > 0:
  594.             line -= 1
  595.             self.GotoLine(line)
  596.             text = self.GetCurLine()[0]
  597.         if text[:ps1size] == ps1:
  598.             line = self.GetCurrentLine()
  599.             self.GotoLine(line)
  600.             startpos = self.GetCurrentPos() + ps1size
  601.             line += 1
  602.             self.GotoLine(line)
  603.             while self.GetCurLine()[0][:ps2size] == ps2:
  604.                 line += 1
  605.                 self.GotoLine(line)
  606.             stoppos = self.GetCurrentPos()
  607.             command = self.GetTextRange(startpos, stoppos)
  608.             command = command.replace(os.linesep + ps2, '\n')
  609.             command = command.rstrip()
  610.             command = command.replace('\n', os.linesep + ps2)
  611.         else:
  612.             command = ''
  613.         if rstrip:
  614.             command = command.rstrip()
  615.         
  616.         return command
  617.  
  618.     
  619.     def getCommand(self, text = None, rstrip = True):
  620.         if not text:
  621.             text = self.GetCurLine()[0]
  622.         
  623.         command = self.lstripPrompt(text)
  624.         if command == text:
  625.             command = ''
  626.         
  627.         if rstrip:
  628.             command = command.rstrip()
  629.         
  630.         return command
  631.  
  632.     
  633.     def lstripPrompt(self, text):
  634.         ps1 = str(sys.ps1)
  635.         ps1size = len(ps1)
  636.         ps2 = str(sys.ps2)
  637.         ps2size = len(ps2)
  638.         if text[:ps1size] == ps1:
  639.             text = text[ps1size:]
  640.         elif text[:ps2size] == ps2:
  641.             text = text[ps2size:]
  642.         
  643.         return text
  644.  
  645.     
  646.     def push(self, command, silent = False):
  647.         if not silent:
  648.             self.write(os.linesep)
  649.         
  650.         busy = wx.BusyCursor()
  651.         self.waiting = True
  652.         self.more = self.interp.push(command)
  653.         self.waiting = False
  654.         del busy
  655.         if not self.more:
  656.             self.addHistory(command.rstrip())
  657.         
  658.         if not silent:
  659.             self.prompt()
  660.         
  661.  
  662.     
  663.     def addHistory(self, command):
  664.         self.historyIndex = -1
  665.         if command != '':
  666.             if len(self.history) == 0 or command != self.history[0]:
  667.                 self.history.insert(0, command)
  668.                 dispatcher.send(signal = 'Shell.addHistory', command = command)
  669.             
  670.  
  671.     
  672.     def write(self, text):
  673.         if wx.IsMainThread():
  674.             text = self.fixLineEndings(text)
  675.             self.AddText(text)
  676.             self.EnsureCaretVisible()
  677.         else:
  678.             self.stderr.write(text)
  679.  
  680.     
  681.     def fixLineEndings(self, text):
  682.         lines = text.split('\r\n')
  683.         for l in range(len(lines)):
  684.             chunks = lines[l].split('\r')
  685.             for c in range(len(chunks)):
  686.                 chunks[c] = os.linesep.join(chunks[c].split('\n'))
  687.             
  688.             lines[l] = os.linesep.join(chunks)
  689.         
  690.         text = os.linesep.join(lines)
  691.         return text
  692.  
  693.     
  694.     def prompt(self):
  695.         isreading = self.reader.isreading
  696.         skip = False
  697.         if isreading:
  698.             prompt = str(sys.ps3)
  699.         elif self.more:
  700.             prompt = str(sys.ps2)
  701.         else:
  702.             prompt = str(sys.ps1)
  703.         pos = self.GetCurLine()[1]
  704.         if pos > 0:
  705.             if isreading:
  706.                 skip = True
  707.             else:
  708.                 self.write(os.linesep)
  709.         
  710.         if not self.more:
  711.             self.promptPosStart = self.GetCurrentPos()
  712.         
  713.         if not skip:
  714.             self.write(prompt)
  715.         
  716.         if not self.more:
  717.             self.promptPosEnd = self.GetCurrentPos()
  718.             self.EmptyUndoBuffer()
  719.         
  720.         if self.more:
  721.             self.write('    ')
  722.         
  723.         self.EnsureCaretVisible()
  724.         self.ScrollToColumn(0)
  725.  
  726.     
  727.     def readline(self):
  728.         input = ''
  729.         reader = self.reader
  730.         reader.isreading = True
  731.         self.prompt()
  732.         
  733.         try:
  734.             while not reader.input:
  735.                 wx.YieldIfNeeded()
  736.             input = reader.input
  737.         finally:
  738.             reader.input = ''
  739.             reader.isreading = False
  740.  
  741.         input = str(input)
  742.         return input
  743.  
  744.     
  745.     def readlines(self):
  746.         lines = []
  747.         while lines[-1:] != [
  748.             '\n']:
  749.             lines.append(self.readline())
  750.         return lines
  751.  
  752.     
  753.     def raw_input(self, prompt = ''):
  754.         if prompt:
  755.             self.write(prompt)
  756.         
  757.         return self.readline()
  758.  
  759.     
  760.     def ask(self, prompt = 'Please enter your response:'):
  761.         dialog = wx.TextEntryDialog(None, prompt, 'Input Dialog (Raw)', '')
  762.         
  763.         try:
  764.             if dialog.ShowModal() == wx.ID_OK:
  765.                 text = dialog.GetValue()
  766.                 return text
  767.         finally:
  768.             dialog.Destroy()
  769.  
  770.         return ''
  771.  
  772.     
  773.     def pause(self):
  774.         self.ask('Press enter to continue:')
  775.  
  776.     
  777.     def clear(self):
  778.         self.ClearAll()
  779.  
  780.     
  781.     def run(self, command, prompt = True, verbose = True):
  782.         endpos = self.GetTextLength()
  783.         self.SetCurrentPos(endpos)
  784.         command = command.rstrip()
  785.         if prompt:
  786.             self.prompt()
  787.         
  788.         if verbose:
  789.             self.write(command)
  790.         
  791.         self.push(command)
  792.  
  793.     
  794.     def runfile(self, filename):
  795.         file = open(filename)
  796.         
  797.         try:
  798.             self.prompt()
  799.             for command in file.readlines():
  800.                 if command[:6] == 'shell.':
  801.                     self.run(command, prompt = False, verbose = False)
  802.                     continue
  803.                 self.run(command, prompt = False, verbose = True)
  804.         finally:
  805.             file.close()
  806.  
  807.  
  808.     
  809.     def autoCompleteShow(self, command, offset = 0):
  810.         self.AutoCompSetAutoHide(self.autoCompleteAutoHide)
  811.         self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive)
  812.         list = self.interp.getAutoCompleteList(command, includeMagic = self.autoCompleteIncludeMagic, includeSingle = self.autoCompleteIncludeSingle, includeDouble = self.autoCompleteIncludeDouble)
  813.         if list:
  814.             options = ' '.join(list)
  815.             self.AutoCompShow(offset, options)
  816.         
  817.  
  818.     
  819.     def autoCallTipShow(self, command, insertcalltip = True, forceCallTip = False):
  820.         if self.CallTipActive():
  821.             self.CallTipCancel()
  822.         
  823.         (name, argspec, tip) = self.interp.getCallTip(command)
  824.         if tip:
  825.             dispatcher.send(signal = 'Shell.calltip', sender = self, calltip = tip)
  826.         
  827.         if not (self.autoCallTip) and not forceCallTip:
  828.             return None
  829.         if argspec and insertcalltip and self.callTipInsert:
  830.             startpos = self.GetCurrentPos()
  831.             self.write(argspec + ')')
  832.             endpos = self.GetCurrentPos()
  833.             self.SetSelection(endpos, startpos)
  834.         
  835.         if tip:
  836.             curpos = self.GetCurrentPos()
  837.             tippos = curpos - (len(name) + 1)
  838.             fallback = curpos - self.GetColumn(curpos)
  839.             tippos = max(tippos, fallback)
  840.             self.CallTipShow(tippos, tip)
  841.         
  842.  
  843.     
  844.     def OnCallTipAutoCompleteManually(self, shiftDown):
  845.         if self.AutoCompActive():
  846.             self.AutoCompCancel()
  847.         
  848.         currpos = self.GetCurrentPos()
  849.         stoppos = self.promptPosEnd
  850.         cpos = currpos
  851.         pointavailpos = -1
  852.         while cpos >= stoppos:
  853.             if self.GetCharAt(cpos) == ord('.'):
  854.                 pointavailpos = cpos
  855.                 break
  856.             
  857.             cpos -= 1
  858.         if pointavailpos != -1:
  859.             textbehind = self.GetTextRange(pointavailpos + 1, currpos)
  860.             pointavailpos += 1
  861.             if not shiftDown:
  862.                 stoppos = self.promptPosEnd
  863.                 textbefore = self.GetTextRange(stoppos, pointavailpos)
  864.                 self.autoCompleteShow(textbefore, len(textbehind))
  865.             else:
  866.                 cpos = pointavailpos
  867.                 begpos = -1
  868.                 while cpos > stoppos:
  869.                     if chr(self.GetCharAt(cpos)).isspace():
  870.                         begpos = cpos
  871.                         break
  872.                     
  873.                     cpos -= 1
  874.                 if begpos == -1:
  875.                     begpos = cpos
  876.                 
  877.                 ctips = self.GetTextRange(begpos, currpos)
  878.                 ctindex = ctips.find('(')
  879.                 if ctindex != -1 and not self.CallTipActive():
  880.                     if self.GetCharAt(currpos - 1) == ord('('):
  881.                         pass
  882.                     self.autoCallTipShow(ctips[:ctindex + 1], self.GetCurrentPos() == self.GetTextLength(), True)
  883.                 
  884.         
  885.  
  886.     
  887.     def writeOut(self, text):
  888.         self.write(text)
  889.  
  890.     
  891.     def writeErr(self, text):
  892.         self.write(text)
  893.  
  894.     
  895.     def redirectStdin(self, redirect = True):
  896.         if redirect:
  897.             sys.stdin = self.reader
  898.         else:
  899.             sys.stdin = self.stdin
  900.  
  901.     
  902.     def redirectStdout(self, redirect = True):
  903.         if redirect:
  904.             sys.stdout = PseudoFileOut(self.writeOut)
  905.         else:
  906.             sys.stdout = self.stdout
  907.  
  908.     
  909.     def redirectStderr(self, redirect = True):
  910.         if redirect:
  911.             sys.stderr = PseudoFileErr(self.writeErr)
  912.         else:
  913.             sys.stderr = self.stderr
  914.  
  915.     
  916.     def CanCut(self):
  917.         if self.GetSelectionStart() != self.GetSelectionEnd() and self.GetSelectionStart() >= self.promptPosEnd and self.GetSelectionEnd() >= self.promptPosEnd:
  918.             return True
  919.         return False
  920.  
  921.     
  922.     def CanPaste(self):
  923.         if self.CanEdit() and editwindow.EditWindow.CanPaste(self):
  924.             return True
  925.         return False
  926.  
  927.     
  928.     def CanEdit(self):
  929.         if self.GetSelectionStart() != self.GetSelectionEnd():
  930.             if self.GetSelectionStart() >= self.promptPosEnd and self.GetSelectionEnd() >= self.promptPosEnd:
  931.                 return True
  932.             return False
  933.         self.GetSelectionStart() != self.GetSelectionEnd()
  934.         return self.GetCurrentPos() >= self.promptPosEnd
  935.  
  936.     
  937.     def Cut(self):
  938.         if self.CanCut() and self.CanCopy():
  939.             if self.AutoCompActive():
  940.                 self.AutoCompCancel()
  941.             
  942.             if self.CallTipActive():
  943.                 self.CallTipCancel()
  944.             
  945.             self.Copy()
  946.             self.ReplaceSelection('')
  947.         
  948.  
  949.     
  950.     def Copy(self):
  951.         if self.CanCopy():
  952.             ps1 = str(sys.ps1)
  953.             ps2 = str(sys.ps2)
  954.             command = self.GetSelectedText()
  955.             command = command.replace(os.linesep + ps2, os.linesep)
  956.             command = command.replace(os.linesep + ps1, os.linesep)
  957.             command = self.lstripPrompt(text = command)
  958.             data = wx.TextDataObject(command)
  959.             self._clip(data)
  960.         
  961.  
  962.     
  963.     def CopyWithPrompts(self):
  964.         if self.CanCopy():
  965.             command = self.GetSelectedText()
  966.             data = wx.TextDataObject(command)
  967.             self._clip(data)
  968.         
  969.  
  970.     
  971.     def CopyWithPromptsPrefixed(self):
  972.         if self.CanCopy():
  973.             command = self.GetSelectedText()
  974.             spaces = '    '
  975.             command = spaces + command.replace(os.linesep, os.linesep + spaces)
  976.             data = wx.TextDataObject(command)
  977.             self._clip(data)
  978.         
  979.  
  980.     
  981.     def _clip(self, data):
  982.         if wx.TheClipboard.Open():
  983.             wx.TheClipboard.UsePrimarySelection(False)
  984.             wx.TheClipboard.SetData(data)
  985.             wx.TheClipboard.Flush()
  986.             wx.TheClipboard.Close()
  987.         
  988.  
  989.     
  990.     def Paste(self):
  991.         if self.CanPaste() and wx.TheClipboard.Open():
  992.             ps2 = str(sys.ps2)
  993.             if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
  994.                 data = wx.TextDataObject()
  995.                 if wx.TheClipboard.GetData(data):
  996.                     self.ReplaceSelection('')
  997.                     command = data.GetText()
  998.                     command = command.rstrip()
  999.                     command = self.fixLineEndings(command)
  1000.                     command = self.lstripPrompt(text = command)
  1001.                     command = command.replace(os.linesep + ps2, '\n')
  1002.                     command = command.replace(os.linesep, '\n')
  1003.                     command = command.replace('\n', os.linesep + ps2)
  1004.                     self.write(command)
  1005.                 
  1006.             
  1007.             wx.TheClipboard.Close()
  1008.         
  1009.  
  1010.     
  1011.     def PasteAndRun(self):
  1012.         text = ''
  1013.         if wx.TheClipboard.Open():
  1014.             if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
  1015.                 data = wx.TextDataObject()
  1016.                 if wx.TheClipboard.GetData(data):
  1017.                     text = data.GetText()
  1018.                 
  1019.             
  1020.             wx.TheClipboard.Close()
  1021.         
  1022.         if text:
  1023.             self.Execute(text)
  1024.         
  1025.  
  1026.     
  1027.     def Execute(self, text):
  1028.         ps1 = str(sys.ps1)
  1029.         ps2 = str(sys.ps2)
  1030.         endpos = self.GetTextLength()
  1031.         self.SetCurrentPos(endpos)
  1032.         startpos = self.promptPosEnd
  1033.         self.SetSelection(startpos, endpos)
  1034.         self.ReplaceSelection('')
  1035.         text = text.lstrip()
  1036.         text = self.fixLineEndings(text)
  1037.         text = self.lstripPrompt(text)
  1038.         text = text.replace(os.linesep + ps1, '\n')
  1039.         text = text.replace(os.linesep + ps2, '\n')
  1040.         text = text.replace(os.linesep, '\n')
  1041.         lines = text.split('\n')
  1042.         commands = []
  1043.         command = ''
  1044.         for line in lines:
  1045.             if line.strip() == ps2.strip():
  1046.                 line = ''
  1047.             
  1048.             lstrip = line.lstrip()
  1049.             if line.strip() != '' and lstrip == line and lstrip[:4] not in ('else', 'elif') and lstrip[:6] != 'except':
  1050.                 if command:
  1051.                     commands.append(command)
  1052.                 
  1053.                 command = line
  1054.                 continue
  1055.             command += '\n'
  1056.             command += line
  1057.         
  1058.         commands.append(command)
  1059.         for command in commands:
  1060.             command = command.replace('\n', os.linesep + ps2)
  1061.             self.write(command)
  1062.             self.processLine()
  1063.         
  1064.  
  1065.     
  1066.     def wrap(self, wrap = True):
  1067.         
  1068.         try:
  1069.             self.SetWrapMode(wrap)
  1070.         except AttributeError:
  1071.             return 'Wrapping is not available in this version.'
  1072.  
  1073.  
  1074.     
  1075.     def zoom(self, points = 0):
  1076.         self.SetZoom(points)
  1077.  
  1078.     
  1079.     def LoadSettings(self, config):
  1080.         self.autoComplete = config.ReadBool('Options/AutoComplete', True)
  1081.         self.autoCompleteIncludeMagic = config.ReadBool('Options/AutoCompleteIncludeMagic', True)
  1082.         self.autoCompleteIncludeSingle = config.ReadBool('Options/AutoCompleteIncludeSingle', True)
  1083.         self.autoCompleteIncludeDouble = config.ReadBool('Options/AutoCompleteIncludeDouble', True)
  1084.         self.autoCallTip = config.ReadBool('Options/AutoCallTip', True)
  1085.         self.callTipInsert = config.ReadBool('Options/CallTipInsert', True)
  1086.         self.SetWrapMode(config.ReadBool('View/WrapMode', True))
  1087.         useAA = config.ReadBool('Options/UseAntiAliasing', self.GetUseAntiAliasing())
  1088.         self.SetUseAntiAliasing(useAA)
  1089.         self.lineNumbers = config.ReadBool('View/ShowLineNumbers', True)
  1090.         self.setDisplayLineNumbers(self.lineNumbers)
  1091.         zoom = config.ReadInt('View/Zoom/Shell', -99)
  1092.         if zoom != -99:
  1093.             self.SetZoom(zoom)
  1094.         
  1095.  
  1096.     
  1097.     def SaveSettings(self, config):
  1098.         config.WriteBool('Options/AutoComplete', self.autoComplete)
  1099.         config.WriteBool('Options/AutoCompleteIncludeMagic', self.autoCompleteIncludeMagic)
  1100.         config.WriteBool('Options/AutoCompleteIncludeSingle', self.autoCompleteIncludeSingle)
  1101.         config.WriteBool('Options/AutoCompleteIncludeDouble', self.autoCompleteIncludeDouble)
  1102.         config.WriteBool('Options/AutoCallTip', self.autoCallTip)
  1103.         config.WriteBool('Options/CallTipInsert', self.callTipInsert)
  1104.         config.WriteBool('Options/UseAntiAliasing', self.GetUseAntiAliasing())
  1105.         config.WriteBool('View/WrapMode', self.GetWrapMode())
  1106.         config.WriteBool('View/ShowLineNumbers', self.lineNumbers)
  1107.         config.WriteInt('View/Zoom/Shell', self.GetZoom())
  1108.  
  1109.     
  1110.     def GetContextMenu(self):
  1111.         menu = wx.Menu()
  1112.         menu.Append(wx.ID_UNDO, 'Undo')
  1113.         menu.Append(wx.ID_REDO, 'Redo')
  1114.         menu.AppendSeparator()
  1115.         menu.Append(wx.ID_CUT, 'Cut')
  1116.         menu.Append(wx.ID_COPY, 'Copy')
  1117.         menu.Append(frame.ID_COPY_PLUS, 'Copy Plus')
  1118.         menu.Append(wx.ID_PASTE, 'Paste')
  1119.         menu.Append(frame.ID_PASTE_PLUS, 'Paste Plus')
  1120.         menu.Append(wx.ID_CLEAR, 'Clear')
  1121.         menu.AppendSeparator()
  1122.         menu.Append(wx.ID_SELECTALL, 'Select All')
  1123.         return menu
  1124.  
  1125.     
  1126.     def OnContextMenu(self, evt):
  1127.         menu = self.GetContextMenu()
  1128.         self.PopupMenu(menu)
  1129.  
  1130.     
  1131.     def OnUpdateUI(self, evt):
  1132.         id = evt.Id
  1133.         if id in (wx.ID_CUT, wx.ID_CLEAR):
  1134.             evt.Enable(self.CanCut())
  1135.         elif id in (wx.ID_COPY, frame.ID_COPY_PLUS):
  1136.             evt.Enable(self.CanCopy())
  1137.         elif id in (wx.ID_PASTE, frame.ID_PASTE_PLUS):
  1138.             evt.Enable(self.CanPaste())
  1139.         elif id == wx.ID_UNDO:
  1140.             evt.Enable(self.CanUndo())
  1141.         elif id == wx.ID_REDO:
  1142.             evt.Enable(self.CanRedo())
  1143.         
  1144.  
  1145.  
  1146.