interact.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. ##################################################################
  2. ##
  3. ## Interactive Shell Window
  4. ##
  5. import sys, os
  6. import code
  7. import string
  8. import win32ui
  9. import win32api
  10. import win32clipboard
  11. import win32con
  12. import traceback
  13. import afxres
  14. import array
  15. import __main__
  16. import pywin.scintilla.formatter
  17. import pywin.scintilla.control
  18. import pywin.scintilla.IDLEenvironment
  19. import pywin.framework.app
  20. ## sequential after ID_GOTO_LINE defined in editor.py
  21. ID_EDIT_COPY_CODE = 0xe2002
  22. ID_EDIT_EXEC_CLIPBOARD = 0x2003
  23. trace=pywin.scintilla.formatter.trace
  24. import winout
  25. import re
  26. # from IDLE.
  27. _is_block_opener = re.compile(r":\s*(#.*)?$").search
  28. _is_block_closer = re.compile(r"""
  29. \s*
  30. ( return
  31. | break
  32. | continue
  33. | raise
  34. | pass
  35. )
  36. \b
  37. """, re.VERBOSE).match
  38. tracebackHeader = "Traceback (".encode("ascii")
  39. sectionProfile = "Interactive Window"
  40. valueFormatTitle = "FormatTitle"
  41. valueFormatInput = "FormatInput"
  42. valueFormatOutput = "FormatOutput"
  43. valueFormatOutputError = "FormatOutputError"
  44. # These are defaults only. Values are read from the registry.
  45. formatTitle = (-536870897, 0, 220, 0, 16711680, 184, 34, 'Arial')
  46. formatInput = (-402653169, 0, 200, 0, 0, 0, 49, 'Courier New')
  47. formatOutput = (-402653169, 0, 200, 0, 8421376, 0, 49, 'Courier New')
  48. formatOutputError = (-402653169, 0, 200, 0, 255, 0, 49, 'Courier New')
  49. try:
  50. sys.ps1
  51. except AttributeError:
  52. sys.ps1 = '>>> '
  53. sys.ps2 = '... '
  54. def LoadPreference(preference, default = ""):
  55. return win32ui.GetProfileVal(sectionProfile, preference, default)
  56. def SavePreference( prefName, prefValue ):
  57. win32ui.WriteProfileVal( sectionProfile, prefName, prefValue )
  58. def GetPromptPrefix(line):
  59. ps1=sys.ps1
  60. if line[:len(ps1)]==ps1: return ps1
  61. ps2=sys.ps2
  62. if line[:len(ps2)]==ps2: return ps2
  63. #############################################################
  64. #
  65. # Colorizer related code.
  66. #
  67. #############################################################
  68. STYLE_INTERACTIVE_EOL = "Interactive EOL"
  69. STYLE_INTERACTIVE_OUTPUT = "Interactive Output"
  70. STYLE_INTERACTIVE_PROMPT = "Interactive Prompt"
  71. STYLE_INTERACTIVE_BANNER = "Interactive Banner"
  72. STYLE_INTERACTIVE_ERROR = "Interactive Error"
  73. STYLE_INTERACTIVE_ERROR_FINALLINE = "Interactive Error (final line)"
  74. INTERACTIVE_STYLES = [STYLE_INTERACTIVE_EOL, STYLE_INTERACTIVE_OUTPUT, STYLE_INTERACTIVE_PROMPT, STYLE_INTERACTIVE_BANNER, STYLE_INTERACTIVE_ERROR, STYLE_INTERACTIVE_ERROR_FINALLINE]
  75. FormatterParent = pywin.scintilla.formatter.PythonSourceFormatter
  76. class InteractiveFormatter(FormatterParent):
  77. def __init__(self, scintilla):
  78. FormatterParent.__init__(self, scintilla)
  79. self.bannerDisplayed = False
  80. def SetStyles(self):
  81. FormatterParent.SetStyles(self)
  82. Style = pywin.scintilla.formatter.Style
  83. self.RegisterStyle( Style(STYLE_INTERACTIVE_EOL, STYLE_INTERACTIVE_PROMPT ) )
  84. self.RegisterStyle( Style(STYLE_INTERACTIVE_PROMPT, formatInput ) )
  85. self.RegisterStyle( Style(STYLE_INTERACTIVE_OUTPUT, formatOutput) )
  86. self.RegisterStyle( Style(STYLE_INTERACTIVE_BANNER, formatTitle ) )
  87. self.RegisterStyle( Style(STYLE_INTERACTIVE_ERROR, formatOutputError ) )
  88. self.RegisterStyle( Style(STYLE_INTERACTIVE_ERROR_FINALLINE, STYLE_INTERACTIVE_ERROR ) )
  89. def LoadPreference(self, name, default):
  90. rc = win32ui.GetProfileVal("Format", name, default)
  91. if rc==default:
  92. rc = win32ui.GetProfileVal(sectionProfile, name, default)
  93. return rc
  94. def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart):
  95. lengthDoc = len(cdoc)
  96. if lengthDoc == 0: return
  97. state = styleStart
  98. # As per comments in Colorize(), we work with the raw utf8
  99. # bytes. To avoid too muych py3k pain, we treat each utf8 byte
  100. # as a latin-1 unicode character - we only use it to compare
  101. # against ascii chars anyway...
  102. chNext = cdoc[0:1].decode('latin-1')
  103. startSeg = 0
  104. i = 0
  105. lastState=state # debug only
  106. while i < lengthDoc:
  107. ch = chNext
  108. chNext = cdoc[i+1:i+2].decode('latin-1')
  109. # trace("ch=%r, i=%d, next=%r, state=%s" % (ch, i, chNext, state))
  110. if state == STYLE_INTERACTIVE_EOL:
  111. if ch not in '\r\n':
  112. self.ColorSeg(startSeg, i-1, state)
  113. startSeg = i
  114. if ch in [sys.ps1[0], sys.ps2[0]]:
  115. state = STYLE_INTERACTIVE_PROMPT
  116. elif cdoc[i:i+len(tracebackHeader)]==tracebackHeader:
  117. state = STYLE_INTERACTIVE_ERROR
  118. else:
  119. state = STYLE_INTERACTIVE_OUTPUT
  120. elif state == STYLE_INTERACTIVE_PROMPT:
  121. if ch not in sys.ps1 + sys.ps2 + " ":
  122. self.ColorSeg(startSeg, i-1, state)
  123. startSeg = i
  124. if ch in '\r\n':
  125. state = STYLE_INTERACTIVE_EOL
  126. else:
  127. state = stylePyStart # Start coloring Python code.
  128. elif state in [STYLE_INTERACTIVE_OUTPUT]:
  129. if ch in '\r\n':
  130. self.ColorSeg(startSeg, i-1, state)
  131. startSeg = i
  132. state = STYLE_INTERACTIVE_EOL
  133. elif state == STYLE_INTERACTIVE_ERROR:
  134. if ch in '\r\n' and chNext and chNext not in string.whitespace:
  135. # Everything including me
  136. self.ColorSeg(startSeg, i, state)
  137. startSeg = i+1
  138. state = STYLE_INTERACTIVE_ERROR_FINALLINE
  139. elif i == 0 and ch not in string.whitespace:
  140. # If we are coloring from the start of a line,
  141. # we need this better check for the last line
  142. # Color up to not including me
  143. self.ColorSeg(startSeg, i-1, state)
  144. startSeg = i
  145. state = STYLE_INTERACTIVE_ERROR_FINALLINE
  146. elif state == STYLE_INTERACTIVE_ERROR_FINALLINE:
  147. if ch in '\r\n':
  148. self.ColorSeg(startSeg, i-1, state)
  149. startSeg = i
  150. state = STYLE_INTERACTIVE_EOL
  151. elif state == STYLE_INTERACTIVE_BANNER:
  152. if ch in '\r\n' and (chNext=='' or chNext in ">["):
  153. # Everything including me
  154. self.ColorSeg(startSeg, i-1, state)
  155. startSeg = i
  156. state = STYLE_INTERACTIVE_EOL
  157. else:
  158. # It is a PythonColorizer state - seek past the end of the line
  159. # and ask the Python colorizer to color that.
  160. end = startSeg
  161. while end < lengthDoc and cdoc[end] not in '\r\n'.encode('ascii'):
  162. end = end + 1
  163. self.ColorizePythonCode( cdoc[:end], startSeg, state)
  164. stylePyStart = self.GetStringStyle(end-1)
  165. if stylePyStart is None:
  166. stylePyStart = pywin.scintilla.formatter.STYLE_DEFAULT
  167. else:
  168. stylePyStart = stylePyStart.name
  169. startSeg =end
  170. i = end - 1 # ready for increment.
  171. chNext = cdoc[end:end+1].decode('latin-1')
  172. state = STYLE_INTERACTIVE_EOL
  173. if lastState != state:
  174. lastState = state
  175. i = i + 1
  176. # and the rest
  177. if startSeg<i:
  178. self.ColorSeg(startSeg, i-1, state)
  179. def Colorize(self, start=0, end=-1):
  180. # scintilla's formatting is all done in terms of utf, so
  181. # we work with utf8 bytes instead of unicode. This magically
  182. # works as any extended chars found in the utf8 don't change
  183. # the semantics.
  184. stringVal = self.scintilla.GetTextRange(start, end, decode=False)
  185. styleStart = None
  186. stylePyStart = None
  187. if start > 1:
  188. # Likely we are being asked to color from the start of the line.
  189. # We find the last formatted character on the previous line.
  190. # If TQString, we continue it. Otherwise, we reset.
  191. look = start -1
  192. while look and self.scintilla.SCIGetCharAt(look) in '\n\r':
  193. look = look - 1
  194. if look and look < start-1: # Did we find a char before the \n\r sets?
  195. strstyle = self.GetStringStyle(look)
  196. quote_char = None
  197. if strstyle is not None:
  198. if strstyle.name == pywin.scintilla.formatter.STYLE_TQSSTRING:
  199. quote_char = "'"
  200. elif strstyle.name == pywin.scintilla.formatter.STYLE_TQDSTRING:
  201. quote_char = '"'
  202. if quote_char is not None:
  203. # It is a TQS. If the TQS is not terminated, we
  204. # carry the style through.
  205. if look > 2:
  206. look_str = self.scintilla.SCIGetCharAt(look-2) + self.scintilla.SCIGetCharAt(look-1) + self.scintilla.SCIGetCharAt(look)
  207. if look_str != quote_char * 3:
  208. stylePyStart = strstyle.name
  209. if stylePyStart is None: stylePyStart = pywin.scintilla.formatter.STYLE_DEFAULT
  210. if start > 0:
  211. stylenum = self.scintilla.SCIGetStyleAt(start - 1)
  212. styleStart = self.GetStyleByNum(stylenum).name
  213. elif self.bannerDisplayed:
  214. styleStart = STYLE_INTERACTIVE_EOL
  215. else:
  216. styleStart = STYLE_INTERACTIVE_BANNER
  217. self.bannerDisplayed = True
  218. self.scintilla.SCIStartStyling(start, 31)
  219. self.style_buffer = array.array("b", (0,)*len(stringVal))
  220. self.ColorizeInteractiveCode(stringVal, styleStart, stylePyStart)
  221. self.scintilla.SCISetStylingEx(self.style_buffer)
  222. self.style_buffer = None
  223. ###############################################################
  224. #
  225. # This class handles the Python interactive interpreter.
  226. #
  227. # It uses a basic EditWindow, and does all the magic.
  228. # This is triggered by the enter key hander attached by the
  229. # start-up code. It determines if a command is to be executed
  230. # or continued (ie, emit "... ") by snooping around the current
  231. # line, looking for the prompts
  232. #
  233. class PythonwinInteractiveInterpreter(code.InteractiveInterpreter):
  234. def __init__(self, locals = None, globals = None):
  235. if locals is None: locals = __main__.__dict__
  236. if globals is None: globals = locals
  237. self.globals = globals
  238. code.InteractiveInterpreter.__init__(self, locals)
  239. def showsyntaxerror(self, filename=None):
  240. sys.stderr.write(tracebackHeader.decode('ascii')) # So the color syntaxer recognises it.
  241. code.InteractiveInterpreter.showsyntaxerror(self, filename)
  242. def runcode(self, code):
  243. try:
  244. exec code in self.globals, self.locals
  245. except SystemExit:
  246. raise
  247. except:
  248. self.showtraceback()
  249. class InteractiveCore:
  250. def __init__(self, banner = None):
  251. self.banner = banner
  252. # LoadFontPreferences()
  253. def Init(self):
  254. self.oldStdOut = self.oldStdErr = None
  255. # self.SetWordWrap(win32ui.CRichEditView_WrapNone)
  256. self.interp = PythonwinInteractiveInterpreter()
  257. self.OutputGrab() # Release at cleanup.
  258. if self.GetTextLength()==0:
  259. if self.banner is None:
  260. suffix = ""
  261. if win32ui.debug: suffix = ", debug build"
  262. sys.stderr.write("PythonWin %s on %s%s.\n" % (sys.version, sys.platform, suffix) )
  263. sys.stderr.write("Portions %s - see 'Help/About PythonWin' for further copyright information.\n" % (win32ui.copyright,) )
  264. else:
  265. sys.stderr.write(banner)
  266. rcfile = os.environ.get('PYTHONSTARTUP')
  267. if rcfile:
  268. import __main__
  269. try:
  270. execfile(rcfile, __main__.__dict__, __main__.__dict__)
  271. except:
  272. sys.stderr.write(">>> \nError executing PYTHONSTARTUP script %r\n" % (rcfile))
  273. traceback.print_exc(file=sys.stderr)
  274. self.AppendToPrompt([])
  275. def SetContext(self, globals, locals, name = "Dbg"):
  276. oldPrompt = sys.ps1
  277. if globals is None:
  278. # Reset
  279. sys.ps1 = ">>> "
  280. sys.ps2 = "... "
  281. locals = globals = __main__.__dict__
  282. else:
  283. sys.ps1 = "[%s]>>> " % name
  284. sys.ps2 = "[%s]... " % name
  285. self.interp.locals = locals
  286. self.interp.globals = globals
  287. self.AppendToPrompt([], oldPrompt)
  288. def GetContext(self):
  289. return self.interp.globals, self.interp.locals
  290. def DoGetLine(self, line=-1):
  291. if line==-1: line = self.LineFromChar()
  292. line = self.GetLine(line)
  293. while line and line[-1] in ['\r', '\n']:
  294. line = line[:-1]
  295. return line
  296. def AppendToPrompt(self,bufLines, oldPrompt = None):
  297. " Take a command and stick it at the end of the buffer (with python prompts inserted if required)."
  298. self.flush()
  299. lastLineNo = self.GetLineCount()-1
  300. line = self.DoGetLine(lastLineNo)
  301. if oldPrompt and line==oldPrompt:
  302. self.SetSel(self.GetTextLength()-len(oldPrompt), self.GetTextLength())
  303. self.ReplaceSel(sys.ps1)
  304. elif (line!=str(sys.ps1)):
  305. if len(line)!=0: self.write('\n')
  306. self.write(sys.ps1)
  307. self.flush()
  308. self.idle.text.mark_set("iomark", "end-1c")
  309. if not bufLines:
  310. return
  311. terms = (["\n" + sys.ps2] * (len(bufLines)-1)) + ['']
  312. for bufLine, term in zip(bufLines, terms):
  313. if bufLine.strip():
  314. self.write( bufLine + term )
  315. self.flush()
  316. def EnsureNoPrompt(self):
  317. # Get ready to write some text NOT at a Python prompt.
  318. self.flush()
  319. lastLineNo = self.GetLineCount()-1
  320. line = self.DoGetLine(lastLineNo)
  321. if not line or line in [sys.ps1, sys.ps2]:
  322. self.SetSel(self.GetTextLength()-len(line), self.GetTextLength())
  323. self.ReplaceSel('')
  324. else:
  325. # Just add a new line.
  326. self.write('\n')
  327. def _GetSubConfigNames(self):
  328. return ["interactive"] # Allow [Keys:Interactive] sections to be specific
  329. def HookHandlers(self):
  330. # Hook menu command (executed when a menu item with that ID is selected from a menu/toolbar
  331. self.HookCommand(self.OnSelectBlock, win32ui.ID_EDIT_SELECT_BLOCK)
  332. self.HookCommand(self.OnEditCopyCode, ID_EDIT_COPY_CODE)
  333. self.HookCommand(self.OnEditExecClipboard, ID_EDIT_EXEC_CLIPBOARD)
  334. mod = pywin.scintilla.IDLEenvironment.GetIDLEModule("IdleHistory")
  335. if mod is not None:
  336. self.history = mod.History(self.idle.text, "\n" + sys.ps2)
  337. else:
  338. self.history = None
  339. # hack for now for event handling.
  340. # GetBlockBoundary takes a line number, and will return the
  341. # start and and line numbers of the block, and a flag indicating if the
  342. # block is a Python code block.
  343. # If the line specified has a Python prompt, then the lines are parsed
  344. # backwards and forwards, and the flag is true.
  345. # If the line does not start with a prompt, the block is searched forward
  346. # and backward until a prompt _is_ found, and all lines in between without
  347. # prompts are returned, and the flag is false.
  348. def GetBlockBoundary( self, lineNo ):
  349. line = self.DoGetLine(lineNo)
  350. maxLineNo = self.GetLineCount()-1
  351. prefix = GetPromptPrefix(line)
  352. if prefix is None: # Non code block
  353. flag = 0
  354. startLineNo = lineNo
  355. while startLineNo>0:
  356. if GetPromptPrefix(self.DoGetLine(startLineNo-1)) is not None:
  357. break # there _is_ a prompt
  358. startLineNo = startLineNo-1
  359. endLineNo = lineNo
  360. while endLineNo<maxLineNo:
  361. if GetPromptPrefix(self.DoGetLine(endLineNo+1)) is not None:
  362. break # there _is_ a prompt
  363. endLineNo = endLineNo+1
  364. else: # Code block
  365. flag = 1
  366. startLineNo = lineNo
  367. while startLineNo>0 and prefix!=str(sys.ps1):
  368. prefix = GetPromptPrefix(self.DoGetLine(startLineNo-1))
  369. if prefix is None:
  370. break; # there is no prompt.
  371. startLineNo = startLineNo - 1
  372. endLineNo = lineNo
  373. while endLineNo<maxLineNo:
  374. prefix = GetPromptPrefix(self.DoGetLine(endLineNo+1))
  375. if prefix is None:
  376. break # there is no prompt
  377. if prefix==str(sys.ps1):
  378. break # this is another command
  379. endLineNo = endLineNo+1
  380. # continue until end of buffer, or no prompt
  381. return (startLineNo, endLineNo, flag)
  382. def ExtractCommand( self, lines ):
  383. start, end = lines
  384. retList = []
  385. while end >= start:
  386. thisLine = self.DoGetLine(end)
  387. promptLen = len(GetPromptPrefix(thisLine))
  388. retList = [thisLine[promptLen:]] + retList
  389. end = end-1
  390. return retList
  391. def OutputGrab(self):
  392. # import win32traceutil; return
  393. self.oldStdOut = sys.stdout
  394. self.oldStdErr = sys.stderr
  395. sys.stdout=self
  396. sys.stderr=self
  397. self.flush()
  398. def OutputRelease(self):
  399. # a command may have overwritten these - only restore if not.
  400. if self.oldStdOut is not None:
  401. if sys.stdout == self:
  402. sys.stdout=self.oldStdOut
  403. if self.oldStdErr is not None:
  404. if sys.stderr == self:
  405. sys.stderr=self.oldStdErr
  406. self.oldStdOut = None
  407. self.oldStdErr = None
  408. self.flush()
  409. ###################################
  410. #
  411. # Message/Command/Key Hooks.
  412. #
  413. # Enter key handler
  414. #
  415. def ProcessEnterEvent(self, event ):
  416. #If autocompletion has been triggered, complete and do not process event
  417. if self.SCIAutoCActive():
  418. self.SCIAutoCComplete()
  419. self.SCICancel()
  420. return
  421. self.SCICancel()
  422. # First, check for an error message
  423. haveGrabbedOutput = 0
  424. if self.HandleSpecialLine(): return 0
  425. lineNo = self.LineFromChar()
  426. start, end, isCode = self.GetBlockBoundary(lineNo)
  427. # If we are not in a code block just go to the prompt (or create a new one)
  428. if not isCode:
  429. self.AppendToPrompt([])
  430. win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
  431. return
  432. lines = self.ExtractCommand((start,end))
  433. # If we are in a code-block, but it isnt at the end of the buffer
  434. # then copy it to the end ready for editing and subsequent execution
  435. if end!=self.GetLineCount()-1:
  436. win32ui.SetStatusText('Press ENTER to execute command')
  437. self.AppendToPrompt(lines)
  438. self.SetSel(-2)
  439. return
  440. # If SHIFT held down, we want new code here and now!
  441. bNeedIndent = win32api.GetKeyState(win32con.VK_SHIFT)<0 or win32api.GetKeyState(win32con.VK_CONTROL)<0
  442. if bNeedIndent:
  443. self.ReplaceSel("\n")
  444. else:
  445. self.SetSel(-2)
  446. self.ReplaceSel("\n")
  447. source = '\n'.join(lines)
  448. while source and source[-1] in '\t ':
  449. source = source[:-1]
  450. self.OutputGrab() # grab the output for the command exec.
  451. try:
  452. if self.interp.runsource(source, "<interactive input>"): # Need more input!
  453. bNeedIndent = 1
  454. else:
  455. # If the last line isnt empty, append a newline
  456. if self.history is not None:
  457. self.history.history_store(source)
  458. self.AppendToPrompt([])
  459. win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
  460. # win32ui.SetStatusText('Successfully executed statement')
  461. finally:
  462. self.OutputRelease()
  463. if bNeedIndent:
  464. win32ui.SetStatusText('Ready to continue the command')
  465. # Now attempt correct indentation (should use IDLE?)
  466. curLine = self.DoGetLine(lineNo)[len(sys.ps2):]
  467. pos = 0
  468. indent=''
  469. while len(curLine)>pos and curLine[pos] in string.whitespace:
  470. indent = indent + curLine[pos]
  471. pos = pos + 1
  472. if _is_block_opener(curLine):
  473. indent = indent + '\t'
  474. elif _is_block_closer(curLine):
  475. indent = indent[:-1]
  476. # use ReplaceSel to ensure it goes at the cursor rather than end of buffer.
  477. self.ReplaceSel(sys.ps2+indent)
  478. return 0
  479. # ESC key handler
  480. def ProcessEscEvent(self, event):
  481. # Implement a cancel.
  482. if self.SCIAutoCActive() or self.SCICallTipActive():
  483. self.SCICancel()
  484. else:
  485. win32ui.SetStatusText('Cancelled.')
  486. self.AppendToPrompt(('',))
  487. return 0
  488. def OnSelectBlock(self,command, code):
  489. lineNo = self.LineFromChar()
  490. start, end, isCode = self.GetBlockBoundary(lineNo)
  491. startIndex = self.LineIndex(start)
  492. endIndex = self.LineIndex(end+1)-2 # skip \r + \n
  493. if endIndex<0: # must be beyond end of buffer
  494. endIndex = -2 # self.Length()
  495. self.SetSel(startIndex,endIndex)
  496. def OnEditCopyCode(self, command, code):
  497. """ Sanitizes code from interactive window, removing prompts and output,
  498. and inserts it in the clipboard."""
  499. code=self.GetSelText()
  500. lines=code.splitlines()
  501. out_lines=[]
  502. for line in lines:
  503. if line.startswith(sys.ps1):
  504. line=line[len(sys.ps1):]
  505. out_lines.append(line)
  506. elif line.startswith(sys.ps2):
  507. line=line[len(sys.ps2):]
  508. out_lines.append(line)
  509. out_code=os.linesep.join(out_lines)
  510. win32clipboard.OpenClipboard()
  511. try:
  512. win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, unicode(out_code))
  513. finally:
  514. win32clipboard.CloseClipboard()
  515. def OnEditExecClipboard(self, command, code):
  516. """ Executes python code directly from the clipboard."""
  517. win32clipboard.OpenClipboard()
  518. try:
  519. code=win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
  520. finally:
  521. win32clipboard.CloseClipboard()
  522. code=code.replace('\r\n','\n')+'\n'
  523. try:
  524. o=compile(code, '<clipboard>', 'exec')
  525. exec o in __main__.__dict__
  526. except:
  527. traceback.print_exc()
  528. def GetRightMenuItems(self):
  529. # Just override parents
  530. ret = []
  531. flags = 0
  532. ret.append((flags, win32ui.ID_EDIT_UNDO, '&Undo'))
  533. ret.append(win32con.MF_SEPARATOR)
  534. ret.append((flags, win32ui.ID_EDIT_CUT, 'Cu&t'))
  535. ret.append((flags, win32ui.ID_EDIT_COPY, '&Copy'))
  536. start, end=self.GetSel()
  537. if start!=end:
  538. ret.append((flags, ID_EDIT_COPY_CODE, 'Copy code without prompts'))
  539. if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_UNICODETEXT):
  540. ret.append((flags, ID_EDIT_EXEC_CLIPBOARD, 'Execute python code from clipboard'))
  541. ret.append((flags, win32ui.ID_EDIT_PASTE, '&Paste'))
  542. ret.append(win32con.MF_SEPARATOR)
  543. ret.append((flags, win32ui.ID_EDIT_SELECT_ALL, '&Select all'))
  544. ret.append((flags, win32ui.ID_EDIT_SELECT_BLOCK, 'Select &block'))
  545. ret.append((flags, win32ui.ID_VIEW_WHITESPACE, "View &Whitespace"))
  546. return ret
  547. def MDINextEvent(self, event):
  548. win32ui.GetMainFrame().MDINext(0)
  549. def MDIPrevEvent(self, event):
  550. win32ui.GetMainFrame().MDINext(0)
  551. def WindowBackEvent(self, event):
  552. parent = self.GetParentFrame()
  553. if parent == win32ui.GetMainFrame():
  554. # It is docked.
  555. try:
  556. wnd, isactive = parent.MDIGetActive()
  557. wnd.SetFocus()
  558. except win32ui.error:
  559. # No MDI window active!
  560. pass
  561. else:
  562. # Normal Window
  563. try:
  564. lastActive = self.GetParentFrame().lastActive
  565. # If the window is invalid, reset it.
  566. if lastActive is not None and (lastActive._obj_ is None or lastActive.GetSafeHwnd()==0):
  567. lastActive = self.GetParentFrame().lastActive = None
  568. win32ui.SetStatusText("The last active Window has been closed.")
  569. except AttributeError:
  570. print "Can't find the last active window!"
  571. lastActive = None
  572. if lastActive is not None:
  573. lastActive.MDIActivate()
  574. class InteractiveView(InteractiveCore, winout.WindowOutputView):
  575. def __init__(self, doc):
  576. InteractiveCore.__init__(self)
  577. winout.WindowOutputView.__init__(self, doc)
  578. self.encoding = pywin.default_scintilla_encoding
  579. def _MakeColorizer(self):
  580. return InteractiveFormatter(self)
  581. def OnInitialUpdate(self):
  582. winout.WindowOutputView.OnInitialUpdate(self)
  583. self.SetWordWrap()
  584. self.Init()
  585. def HookHandlers(self):
  586. winout.WindowOutputView.HookHandlers(self)
  587. InteractiveCore.HookHandlers(self)
  588. class CInteractivePython(winout.WindowOutput):
  589. def __init__(self, makeDoc = None, makeFrame = None):
  590. self.IsFinalDestroy = 0
  591. winout.WindowOutput.__init__(self, sectionProfile, sectionProfile, \
  592. winout.flags.WQ_LINE, 1, None, makeDoc, makeFrame, InteractiveView )
  593. self.Create()
  594. def OnViewDestroy(self, view):
  595. if self.IsFinalDestroy:
  596. view.OutputRelease()
  597. winout.WindowOutput.OnViewDestroy(self, view)
  598. def Close(self):
  599. self.IsFinalDestroy = 1
  600. winout.WindowOutput.Close(self)
  601. class InteractiveFrame(winout.WindowOutputFrame):
  602. def __init__(self):
  603. self.lastActive = None
  604. winout.WindowOutputFrame.__init__(self)
  605. def OnMDIActivate(self, bActive, wndActive, wndDeactive):
  606. if bActive:
  607. self.lastActive = wndDeactive
  608. ######################################################################
  609. ##
  610. ## Dockable Window Support
  611. ##
  612. ######################################################################
  613. ID_DOCKED_INTERACTIVE_CONTROLBAR = 0xe802
  614. DockedInteractiveViewParent = InteractiveView
  615. class DockedInteractiveView(DockedInteractiveViewParent):
  616. def HookHandlers(self):
  617. DockedInteractiveViewParent.HookHandlers(self)
  618. self.HookMessage(self.OnSetFocus, win32con.WM_SETFOCUS)
  619. self.HookMessage(self.OnKillFocus, win32con.WM_KILLFOCUS)
  620. def OnSetFocus(self, msg):
  621. self.GetParentFrame().SetActiveView(self)
  622. return 1
  623. def OnKillFocus(self, msg):
  624. # If we are losing focus to another in this app, reset the main frame's active view.
  625. hwnd = wparam = msg[2]
  626. try:
  627. wnd = win32ui.CreateWindowFromHandle(hwnd)
  628. reset = wnd.GetTopLevelFrame()==self.GetTopLevelFrame()
  629. except win32ui.error:
  630. reset = 0 # Not my window
  631. if reset: self.GetParentFrame().SetActiveView(None)
  632. return 1
  633. def OnDestroy(self, msg):
  634. newSize = self.GetWindowPlacement()[4]
  635. pywin.framework.app.SaveWindowSize("Interactive Window", newSize, "docked")
  636. try:
  637. if self.GetParentFrame().GetActiveView==self:
  638. self.GetParentFrame().SetActiveView(None)
  639. except win32ui.error:
  640. pass
  641. try:
  642. if win32ui.GetMainFrame().GetActiveView()==self:
  643. win32ui.GetMainFrame().SetActiveView(None)
  644. except win32ui.error:
  645. pass
  646. return DockedInteractiveViewParent.OnDestroy(self, msg)
  647. class CDockedInteractivePython(CInteractivePython):
  648. def __init__(self, dockbar):
  649. self.bFirstCreated = 0
  650. self.dockbar = dockbar
  651. CInteractivePython.__init__(self)
  652. def NeedRecreateWindow(self):
  653. if self.bCreating:
  654. return 0
  655. try:
  656. frame = win32ui.GetMainFrame()
  657. if frame.closing:
  658. return 0 # Dieing!
  659. except (win32ui.error, AttributeError):
  660. return 0 # The app is dieing!
  661. try:
  662. cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
  663. return not cb.IsWindowVisible()
  664. except win32ui.error:
  665. return 1 # Control bar does not exist!
  666. def RecreateWindow(self):
  667. try:
  668. dockbar = win32ui.GetMainFrame().GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
  669. win32ui.GetMainFrame().ShowControlBar(dockbar, 1, 1)
  670. except win32ui.error:
  671. CreateDockedInteractiveWindow()
  672. def Create(self):
  673. self.bCreating = 1
  674. doc = InteractiveDocument(None, self.DoCreateDoc())
  675. view = DockedInteractiveView(doc)
  676. defRect = pywin.framework.app.LoadWindowSize("Interactive Window", "docked")
  677. if defRect[2]-defRect[0]==0:
  678. defRect = 0, 0, 500, 200
  679. style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER
  680. id = 1050 # win32ui.AFX_IDW_PANE_FIRST
  681. view.CreateWindow(self.dockbar, id, style, defRect)
  682. view.OnInitialUpdate()
  683. self.bFirstCreated = 1
  684. self.currentView = doc.GetFirstView()
  685. self.bCreating = 0
  686. if self.title: doc.SetTitle(self.title)
  687. # The factory we pass to the dockable window support.
  688. def InteractiveViewCreator(parent):
  689. global edit
  690. edit = CDockedInteractivePython(parent)
  691. return edit.currentView
  692. def CreateDockedInteractiveWindow():
  693. # Later, the DockingBar should be capable of hosting multiple
  694. # children.
  695. from pywin.docking.DockingBar import DockingBar
  696. bar = DockingBar()
  697. creator = InteractiveViewCreator
  698. bar.CreateWindow(win32ui.GetMainFrame(), creator, "Interactive Window", ID_DOCKED_INTERACTIVE_CONTROLBAR)
  699. bar.SetBarStyle( bar.GetBarStyle()|afxres.CBRS_TOOLTIPS|afxres.CBRS_FLYBY|afxres.CBRS_SIZE_DYNAMIC)
  700. bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
  701. win32ui.GetMainFrame().DockControlBar(bar, afxres.AFX_IDW_DOCKBAR_BOTTOM)
  702. ######################################################################
  703. #
  704. # The public interface to this module.
  705. #
  706. ######################################################################
  707. # No extra functionality now, but maybe later, so
  708. # publicize these names.
  709. InteractiveDocument = winout.WindowOutputDocument
  710. # We remember our one and only interactive window in the "edit" variable.
  711. edit = None
  712. def CreateInteractiveWindowUserPreference(makeDoc = None, makeFrame = None):
  713. """Create some sort of interactive window if the user's preference say we should.
  714. """
  715. bCreate = LoadPreference("Show at startup", 1)
  716. if bCreate:
  717. CreateInteractiveWindow(makeDoc, makeFrame)
  718. def CreateInteractiveWindow(makeDoc = None, makeFrame = None):
  719. """Create a standard or docked interactive window unconditionally
  720. """
  721. assert edit is None, "Creating second interactive window!"
  722. bDocking = LoadPreference("Docking", 0)
  723. if bDocking:
  724. CreateDockedInteractiveWindow()
  725. else:
  726. CreateMDIInteractiveWindow(makeDoc, makeFrame)
  727. assert edit is not None, "Created interactive window, but did not set the global!"
  728. edit.currentView.SetFocus()
  729. def CreateMDIInteractiveWindow(makeDoc = None, makeFrame = None):
  730. """Create a standard (non-docked) interactive window unconditionally
  731. """
  732. global edit
  733. if makeDoc is None: makeDoc = InteractiveDocument
  734. if makeFrame is None: makeFrame = InteractiveFrame
  735. edit = CInteractivePython(makeDoc=makeDoc,makeFrame=makeFrame)
  736. def DestroyInteractiveWindow():
  737. """ Destroy the interactive window.
  738. This is different to Closing the window,
  739. which may automatically re-appear. Once destroyed, it can never be recreated,
  740. and a complete new instance must be created (which the various other helper
  741. functions will then do after making this call
  742. """
  743. global edit
  744. if edit is not None and edit.currentView is not None:
  745. if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
  746. # It is docked - do nothing now (this is only called at shutdown!)
  747. pass
  748. else:
  749. # It is a standard window - call Close on the container.
  750. edit.Close()
  751. edit = None
  752. def CloseInteractiveWindow():
  753. """Close the interactive window, allowing it to be re-created on demand.
  754. """
  755. global edit
  756. if edit is not None and edit.currentView is not None:
  757. if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
  758. # It is docked, just hide the dock bar.
  759. frame = win32ui.GetMainFrame()
  760. cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
  761. frame.ShowControlBar(cb, 0, 1)
  762. else:
  763. # It is a standard window - destroy the frame/view, allowing the object itself to remain.
  764. edit.currentView.GetParentFrame().DestroyWindow()
  765. def ToggleInteractiveWindow():
  766. """If the interactive window is visible, hide it, otherwise show it.
  767. """
  768. if edit is None:
  769. CreateInteractiveWindow()
  770. else:
  771. if edit.NeedRecreateWindow():
  772. edit.RecreateWindow()
  773. else:
  774. # Close it, allowing a reopen.
  775. CloseInteractiveWindow()
  776. def ShowInteractiveWindow():
  777. """Shows (or creates if necessary) an interactive window"""
  778. if edit is None:
  779. CreateInteractiveWindow()
  780. else:
  781. if edit.NeedRecreateWindow():
  782. edit.RecreateWindow()
  783. else:
  784. parent = edit.currentView.GetParentFrame()
  785. if parent == win32ui.GetMainFrame(): # It is docked.
  786. edit.currentView.SetFocus()
  787. else: # It is a "normal" window
  788. edit.currentView.GetParentFrame().AutoRestore()
  789. win32ui.GetMainFrame().MDIActivate(edit.currentView.GetParentFrame())
  790. def IsInteractiveWindowVisible():
  791. return edit is not None and not edit.NeedRecreateWindow()