interact.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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. from . 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, 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. exec(compile(open(rcfile, "rb").read(), rcfile, 'exec', dont_inherit=True),
  271. __main__.__dict__, __main__.__dict__)
  272. except:
  273. sys.stderr.write(">>> \nError executing PYTHONSTARTUP script %r\n" % (rcfile))
  274. traceback.print_exc(file=sys.stderr)
  275. self.AppendToPrompt([])
  276. def SetContext(self, globals, locals, name = "Dbg"):
  277. oldPrompt = sys.ps1
  278. if globals is None:
  279. # Reset
  280. sys.ps1 = ">>> "
  281. sys.ps2 = "... "
  282. locals = globals = __main__.__dict__
  283. else:
  284. sys.ps1 = "[%s]>>> " % name
  285. sys.ps2 = "[%s]... " % name
  286. self.interp.locals = locals
  287. self.interp.globals = globals
  288. self.AppendToPrompt([], oldPrompt)
  289. def GetContext(self):
  290. return self.interp.globals, self.interp.locals
  291. def DoGetLine(self, line=-1):
  292. if line==-1: line = self.LineFromChar()
  293. line = self.GetLine(line)
  294. while line and line[-1] in ['\r', '\n']:
  295. line = line[:-1]
  296. return line
  297. def AppendToPrompt(self,bufLines, oldPrompt = None):
  298. " Take a command and stick it at the end of the buffer (with python prompts inserted if required)."
  299. self.flush()
  300. lastLineNo = self.GetLineCount()-1
  301. line = self.DoGetLine(lastLineNo)
  302. if oldPrompt and line==oldPrompt:
  303. self.SetSel(self.GetTextLength()-len(oldPrompt), self.GetTextLength())
  304. self.ReplaceSel(sys.ps1)
  305. elif (line!=str(sys.ps1)):
  306. if len(line)!=0: self.write('\n')
  307. self.write(sys.ps1)
  308. self.flush()
  309. self.idle.text.mark_set("iomark", "end-1c")
  310. if not bufLines:
  311. return
  312. terms = (["\n" + sys.ps2] * (len(bufLines)-1)) + ['']
  313. for bufLine, term in zip(bufLines, terms):
  314. if bufLine.strip():
  315. self.write( bufLine + term )
  316. self.flush()
  317. def EnsureNoPrompt(self):
  318. # Get ready to write some text NOT at a Python prompt.
  319. self.flush()
  320. lastLineNo = self.GetLineCount()-1
  321. line = self.DoGetLine(lastLineNo)
  322. if not line or line in [sys.ps1, sys.ps2]:
  323. self.SetSel(self.GetTextLength()-len(line), self.GetTextLength())
  324. self.ReplaceSel('')
  325. else:
  326. # Just add a new line.
  327. self.write('\n')
  328. def _GetSubConfigNames(self):
  329. return ["interactive"] # Allow [Keys:Interactive] sections to be specific
  330. def HookHandlers(self):
  331. # Hook menu command (executed when a menu item with that ID is selected from a menu/toolbar
  332. self.HookCommand(self.OnSelectBlock, win32ui.ID_EDIT_SELECT_BLOCK)
  333. self.HookCommand(self.OnEditCopyCode, ID_EDIT_COPY_CODE)
  334. self.HookCommand(self.OnEditExecClipboard, ID_EDIT_EXEC_CLIPBOARD)
  335. mod = pywin.scintilla.IDLEenvironment.GetIDLEModule("IdleHistory")
  336. if mod is not None:
  337. self.history = mod.History(self.idle.text, "\n" + sys.ps2)
  338. else:
  339. self.history = None
  340. # hack for now for event handling.
  341. # GetBlockBoundary takes a line number, and will return the
  342. # start and and line numbers of the block, and a flag indicating if the
  343. # block is a Python code block.
  344. # If the line specified has a Python prompt, then the lines are parsed
  345. # backwards and forwards, and the flag is true.
  346. # If the line does not start with a prompt, the block is searched forward
  347. # and backward until a prompt _is_ found, and all lines in between without
  348. # prompts are returned, and the flag is false.
  349. def GetBlockBoundary( self, lineNo ):
  350. line = self.DoGetLine(lineNo)
  351. maxLineNo = self.GetLineCount()-1
  352. prefix = GetPromptPrefix(line)
  353. if prefix is None: # Non code block
  354. flag = 0
  355. startLineNo = lineNo
  356. while startLineNo>0:
  357. if GetPromptPrefix(self.DoGetLine(startLineNo-1)) is not None:
  358. break # there _is_ a prompt
  359. startLineNo = startLineNo-1
  360. endLineNo = lineNo
  361. while endLineNo<maxLineNo:
  362. if GetPromptPrefix(self.DoGetLine(endLineNo+1)) is not None:
  363. break # there _is_ a prompt
  364. endLineNo = endLineNo+1
  365. else: # Code block
  366. flag = 1
  367. startLineNo = lineNo
  368. while startLineNo>0 and prefix!=str(sys.ps1):
  369. prefix = GetPromptPrefix(self.DoGetLine(startLineNo-1))
  370. if prefix is None:
  371. break; # there is no prompt.
  372. startLineNo = startLineNo - 1
  373. endLineNo = lineNo
  374. while endLineNo<maxLineNo:
  375. prefix = GetPromptPrefix(self.DoGetLine(endLineNo+1))
  376. if prefix is None:
  377. break # there is no prompt
  378. if prefix==str(sys.ps1):
  379. break # this is another command
  380. endLineNo = endLineNo+1
  381. # continue until end of buffer, or no prompt
  382. return (startLineNo, endLineNo, flag)
  383. def ExtractCommand( self, lines ):
  384. start, end = lines
  385. retList = []
  386. while end >= start:
  387. thisLine = self.DoGetLine(end)
  388. promptLen = len(GetPromptPrefix(thisLine))
  389. retList = [thisLine[promptLen:]] + retList
  390. end = end-1
  391. return retList
  392. def OutputGrab(self):
  393. # import win32traceutil; return
  394. self.oldStdOut = sys.stdout
  395. self.oldStdErr = sys.stderr
  396. sys.stdout=self
  397. sys.stderr=self
  398. self.flush()
  399. def OutputRelease(self):
  400. # a command may have overwritten these - only restore if not.
  401. if self.oldStdOut is not None:
  402. if sys.stdout == self:
  403. sys.stdout=self.oldStdOut
  404. if self.oldStdErr is not None:
  405. if sys.stderr == self:
  406. sys.stderr=self.oldStdErr
  407. self.oldStdOut = None
  408. self.oldStdErr = None
  409. self.flush()
  410. ###################################
  411. #
  412. # Message/Command/Key Hooks.
  413. #
  414. # Enter key handler
  415. #
  416. def ProcessEnterEvent(self, event ):
  417. #If autocompletion has been triggered, complete and do not process event
  418. if self.SCIAutoCActive():
  419. self.SCIAutoCComplete()
  420. self.SCICancel()
  421. return
  422. self.SCICancel()
  423. # First, check for an error message
  424. haveGrabbedOutput = 0
  425. if self.HandleSpecialLine(): return 0
  426. lineNo = self.LineFromChar()
  427. start, end, isCode = self.GetBlockBoundary(lineNo)
  428. # If we are not in a code block just go to the prompt (or create a new one)
  429. if not isCode:
  430. self.AppendToPrompt([])
  431. win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
  432. return
  433. lines = self.ExtractCommand((start,end))
  434. # If we are in a code-block, but it isnt at the end of the buffer
  435. # then copy it to the end ready for editing and subsequent execution
  436. if end!=self.GetLineCount()-1:
  437. win32ui.SetStatusText('Press ENTER to execute command')
  438. self.AppendToPrompt(lines)
  439. self.SetSel(-2)
  440. return
  441. # If SHIFT held down, we want new code here and now!
  442. bNeedIndent = win32api.GetKeyState(win32con.VK_SHIFT)<0 or win32api.GetKeyState(win32con.VK_CONTROL)<0
  443. if bNeedIndent:
  444. self.ReplaceSel("\n")
  445. else:
  446. self.SetSel(-2)
  447. self.ReplaceSel("\n")
  448. source = '\n'.join(lines)
  449. while source and source[-1] in '\t ':
  450. source = source[:-1]
  451. self.OutputGrab() # grab the output for the command exec.
  452. try:
  453. if self.interp.runsource(source, "<interactive input>"): # Need more input!
  454. bNeedIndent = 1
  455. else:
  456. # If the last line isnt empty, append a newline
  457. if self.history is not None:
  458. self.history.history_store(source)
  459. self.AppendToPrompt([])
  460. win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
  461. # win32ui.SetStatusText('Successfully executed statement')
  462. finally:
  463. self.OutputRelease()
  464. if bNeedIndent:
  465. win32ui.SetStatusText('Ready to continue the command')
  466. # Now attempt correct indentation (should use IDLE?)
  467. curLine = self.DoGetLine(lineNo)[len(sys.ps2):]
  468. pos = 0
  469. indent=''
  470. while len(curLine)>pos and curLine[pos] in string.whitespace:
  471. indent = indent + curLine[pos]
  472. pos = pos + 1
  473. if _is_block_opener(curLine):
  474. indent = indent + '\t'
  475. elif _is_block_closer(curLine):
  476. indent = indent[:-1]
  477. # use ReplaceSel to ensure it goes at the cursor rather than end of buffer.
  478. self.ReplaceSel(sys.ps2+indent)
  479. return 0
  480. # ESC key handler
  481. def ProcessEscEvent(self, event):
  482. # Implement a cancel.
  483. if self.SCIAutoCActive() or self.SCICallTipActive():
  484. self.SCICancel()
  485. else:
  486. win32ui.SetStatusText('Cancelled.')
  487. self.AppendToPrompt(('',))
  488. return 0
  489. def OnSelectBlock(self,command, code):
  490. lineNo = self.LineFromChar()
  491. start, end, isCode = self.GetBlockBoundary(lineNo)
  492. startIndex = self.LineIndex(start)
  493. endIndex = self.LineIndex(end+1)-2 # skip \r + \n
  494. if endIndex<0: # must be beyond end of buffer
  495. endIndex = -2 # self.Length()
  496. self.SetSel(startIndex,endIndex)
  497. def OnEditCopyCode(self, command, code):
  498. """ Sanitizes code from interactive window, removing prompts and output,
  499. and inserts it in the clipboard."""
  500. code=self.GetSelText()
  501. lines=code.splitlines()
  502. out_lines=[]
  503. for line in lines:
  504. if line.startswith(sys.ps1):
  505. line=line[len(sys.ps1):]
  506. out_lines.append(line)
  507. elif line.startswith(sys.ps2):
  508. line=line[len(sys.ps2):]
  509. out_lines.append(line)
  510. out_code=os.linesep.join(out_lines)
  511. win32clipboard.OpenClipboard()
  512. try:
  513. win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, str(out_code))
  514. finally:
  515. win32clipboard.CloseClipboard()
  516. def OnEditExecClipboard(self, command, code):
  517. """ Executes python code directly from the clipboard."""
  518. win32clipboard.OpenClipboard()
  519. try:
  520. code=win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
  521. finally:
  522. win32clipboard.CloseClipboard()
  523. code=code.replace('\r\n','\n')+'\n'
  524. try:
  525. o=compile(code, '<clipboard>', 'exec')
  526. exec(o, __main__.__dict__)
  527. except:
  528. traceback.print_exc()
  529. def GetRightMenuItems(self):
  530. # Just override parents
  531. ret = []
  532. flags = 0
  533. ret.append((flags, win32ui.ID_EDIT_UNDO, '&Undo'))
  534. ret.append(win32con.MF_SEPARATOR)
  535. ret.append((flags, win32ui.ID_EDIT_CUT, 'Cu&t'))
  536. ret.append((flags, win32ui.ID_EDIT_COPY, '&Copy'))
  537. start, end=self.GetSel()
  538. if start!=end:
  539. ret.append((flags, ID_EDIT_COPY_CODE, 'Copy code without prompts'))
  540. if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_UNICODETEXT):
  541. ret.append((flags, ID_EDIT_EXEC_CLIPBOARD, 'Execute python code from clipboard'))
  542. ret.append((flags, win32ui.ID_EDIT_PASTE, '&Paste'))
  543. ret.append(win32con.MF_SEPARATOR)
  544. ret.append((flags, win32ui.ID_EDIT_SELECT_ALL, '&Select all'))
  545. ret.append((flags, win32ui.ID_EDIT_SELECT_BLOCK, 'Select &block'))
  546. ret.append((flags, win32ui.ID_VIEW_WHITESPACE, "View &Whitespace"))
  547. return ret
  548. def MDINextEvent(self, event):
  549. win32ui.GetMainFrame().MDINext(0)
  550. def MDIPrevEvent(self, event):
  551. win32ui.GetMainFrame().MDINext(0)
  552. def WindowBackEvent(self, event):
  553. parent = self.GetParentFrame()
  554. if parent == win32ui.GetMainFrame():
  555. # It is docked.
  556. try:
  557. wnd, isactive = parent.MDIGetActive()
  558. wnd.SetFocus()
  559. except win32ui.error:
  560. # No MDI window active!
  561. pass
  562. else:
  563. # Normal Window
  564. try:
  565. lastActive = self.GetParentFrame().lastActive
  566. # If the window is invalid, reset it.
  567. if lastActive is not None and (lastActive._obj_ is None or lastActive.GetSafeHwnd()==0):
  568. lastActive = self.GetParentFrame().lastActive = None
  569. win32ui.SetStatusText("The last active Window has been closed.")
  570. except AttributeError:
  571. print("Can't find the last active window!")
  572. lastActive = None
  573. if lastActive is not None:
  574. lastActive.MDIActivate()
  575. class InteractiveView(InteractiveCore, winout.WindowOutputView):
  576. def __init__(self, doc):
  577. InteractiveCore.__init__(self)
  578. winout.WindowOutputView.__init__(self, doc)
  579. self.encoding = pywin.default_scintilla_encoding
  580. def _MakeColorizer(self):
  581. return InteractiveFormatter(self)
  582. def OnInitialUpdate(self):
  583. winout.WindowOutputView.OnInitialUpdate(self)
  584. self.SetWordWrap()
  585. self.Init()
  586. def HookHandlers(self):
  587. winout.WindowOutputView.HookHandlers(self)
  588. InteractiveCore.HookHandlers(self)
  589. class CInteractivePython(winout.WindowOutput):
  590. def __init__(self, makeDoc = None, makeFrame = None):
  591. self.IsFinalDestroy = 0
  592. winout.WindowOutput.__init__(self, sectionProfile, sectionProfile, \
  593. winout.flags.WQ_LINE, 1, None, makeDoc, makeFrame, InteractiveView )
  594. self.Create()
  595. def OnViewDestroy(self, view):
  596. if self.IsFinalDestroy:
  597. view.OutputRelease()
  598. winout.WindowOutput.OnViewDestroy(self, view)
  599. def Close(self):
  600. self.IsFinalDestroy = 1
  601. winout.WindowOutput.Close(self)
  602. class InteractiveFrame(winout.WindowOutputFrame):
  603. def __init__(self):
  604. self.lastActive = None
  605. winout.WindowOutputFrame.__init__(self)
  606. def OnMDIActivate(self, bActive, wndActive, wndDeactive):
  607. if bActive:
  608. self.lastActive = wndDeactive
  609. ######################################################################
  610. ##
  611. ## Dockable Window Support
  612. ##
  613. ######################################################################
  614. ID_DOCKED_INTERACTIVE_CONTROLBAR = 0xe802
  615. DockedInteractiveViewParent = InteractiveView
  616. class DockedInteractiveView(DockedInteractiveViewParent):
  617. def HookHandlers(self):
  618. DockedInteractiveViewParent.HookHandlers(self)
  619. self.HookMessage(self.OnSetFocus, win32con.WM_SETFOCUS)
  620. self.HookMessage(self.OnKillFocus, win32con.WM_KILLFOCUS)
  621. def OnSetFocus(self, msg):
  622. self.GetParentFrame().SetActiveView(self)
  623. return 1
  624. def OnKillFocus(self, msg):
  625. # If we are losing focus to another in this app, reset the main frame's active view.
  626. hwnd = wparam = msg[2]
  627. try:
  628. wnd = win32ui.CreateWindowFromHandle(hwnd)
  629. reset = wnd.GetTopLevelFrame()==self.GetTopLevelFrame()
  630. except win32ui.error:
  631. reset = 0 # Not my window
  632. if reset: self.GetParentFrame().SetActiveView(None)
  633. return 1
  634. def OnDestroy(self, msg):
  635. newSize = self.GetWindowPlacement()[4]
  636. pywin.framework.app.SaveWindowSize("Interactive Window", newSize, "docked")
  637. try:
  638. if self.GetParentFrame().GetActiveView==self:
  639. self.GetParentFrame().SetActiveView(None)
  640. except win32ui.error:
  641. pass
  642. try:
  643. if win32ui.GetMainFrame().GetActiveView()==self:
  644. win32ui.GetMainFrame().SetActiveView(None)
  645. except win32ui.error:
  646. pass
  647. return DockedInteractiveViewParent.OnDestroy(self, msg)
  648. class CDockedInteractivePython(CInteractivePython):
  649. def __init__(self, dockbar):
  650. self.bFirstCreated = 0
  651. self.dockbar = dockbar
  652. CInteractivePython.__init__(self)
  653. def NeedRecreateWindow(self):
  654. if self.bCreating:
  655. return 0
  656. try:
  657. frame = win32ui.GetMainFrame()
  658. if frame.closing:
  659. return 0 # Dieing!
  660. except (win32ui.error, AttributeError):
  661. return 0 # The app is dieing!
  662. try:
  663. cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
  664. return not cb.IsWindowVisible()
  665. except win32ui.error:
  666. return 1 # Control bar does not exist!
  667. def RecreateWindow(self):
  668. try:
  669. dockbar = win32ui.GetMainFrame().GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
  670. win32ui.GetMainFrame().ShowControlBar(dockbar, 1, 1)
  671. except win32ui.error:
  672. CreateDockedInteractiveWindow()
  673. def Create(self):
  674. self.bCreating = 1
  675. doc = InteractiveDocument(None, self.DoCreateDoc())
  676. view = DockedInteractiveView(doc)
  677. defRect = pywin.framework.app.LoadWindowSize("Interactive Window", "docked")
  678. if defRect[2]-defRect[0]==0:
  679. defRect = 0, 0, 500, 200
  680. style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER
  681. id = 1050 # win32ui.AFX_IDW_PANE_FIRST
  682. view.CreateWindow(self.dockbar, id, style, defRect)
  683. view.OnInitialUpdate()
  684. self.bFirstCreated = 1
  685. self.currentView = doc.GetFirstView()
  686. self.bCreating = 0
  687. if self.title: doc.SetTitle(self.title)
  688. # The factory we pass to the dockable window support.
  689. def InteractiveViewCreator(parent):
  690. global edit
  691. edit = CDockedInteractivePython(parent)
  692. return edit.currentView
  693. def CreateDockedInteractiveWindow():
  694. # Later, the DockingBar should be capable of hosting multiple
  695. # children.
  696. from pywin.docking.DockingBar import DockingBar
  697. bar = DockingBar()
  698. creator = InteractiveViewCreator
  699. bar.CreateWindow(win32ui.GetMainFrame(), creator, "Interactive Window", ID_DOCKED_INTERACTIVE_CONTROLBAR)
  700. bar.SetBarStyle( bar.GetBarStyle()|afxres.CBRS_TOOLTIPS|afxres.CBRS_FLYBY|afxres.CBRS_SIZE_DYNAMIC)
  701. bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
  702. win32ui.GetMainFrame().DockControlBar(bar, afxres.AFX_IDW_DOCKBAR_BOTTOM)
  703. ######################################################################
  704. #
  705. # The public interface to this module.
  706. #
  707. ######################################################################
  708. # No extra functionality now, but maybe later, so
  709. # publicize these names.
  710. InteractiveDocument = winout.WindowOutputDocument
  711. # We remember our one and only interactive window in the "edit" variable.
  712. edit = None
  713. def CreateInteractiveWindowUserPreference(makeDoc = None, makeFrame = None):
  714. """Create some sort of interactive window if the user's preference say we should.
  715. """
  716. bCreate = LoadPreference("Show at startup", 1)
  717. if bCreate:
  718. CreateInteractiveWindow(makeDoc, makeFrame)
  719. def CreateInteractiveWindow(makeDoc = None, makeFrame = None):
  720. """Create a standard or docked interactive window unconditionally
  721. """
  722. assert edit is None, "Creating second interactive window!"
  723. bDocking = LoadPreference("Docking", 0)
  724. if bDocking:
  725. CreateDockedInteractiveWindow()
  726. else:
  727. CreateMDIInteractiveWindow(makeDoc, makeFrame)
  728. assert edit is not None, "Created interactive window, but did not set the global!"
  729. edit.currentView.SetFocus()
  730. def CreateMDIInteractiveWindow(makeDoc = None, makeFrame = None):
  731. """Create a standard (non-docked) interactive window unconditionally
  732. """
  733. global edit
  734. if makeDoc is None: makeDoc = InteractiveDocument
  735. if makeFrame is None: makeFrame = InteractiveFrame
  736. edit = CInteractivePython(makeDoc=makeDoc,makeFrame=makeFrame)
  737. def DestroyInteractiveWindow():
  738. """ Destroy the interactive window.
  739. This is different to Closing the window,
  740. which may automatically re-appear. Once destroyed, it can never be recreated,
  741. and a complete new instance must be created (which the various other helper
  742. functions will then do after making this call
  743. """
  744. global edit
  745. if edit is not None and edit.currentView is not None:
  746. if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
  747. # It is docked - do nothing now (this is only called at shutdown!)
  748. pass
  749. else:
  750. # It is a standard window - call Close on the container.
  751. edit.Close()
  752. edit = None
  753. def CloseInteractiveWindow():
  754. """Close the interactive window, allowing it to be re-created on demand.
  755. """
  756. global edit
  757. if edit is not None and edit.currentView is not None:
  758. if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
  759. # It is docked, just hide the dock bar.
  760. frame = win32ui.GetMainFrame()
  761. cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
  762. frame.ShowControlBar(cb, 0, 1)
  763. else:
  764. # It is a standard window - destroy the frame/view, allowing the object itself to remain.
  765. edit.currentView.GetParentFrame().DestroyWindow()
  766. def ToggleInteractiveWindow():
  767. """If the interactive window is visible, hide it, otherwise show it.
  768. """
  769. if edit is None:
  770. CreateInteractiveWindow()
  771. else:
  772. if edit.NeedRecreateWindow():
  773. edit.RecreateWindow()
  774. else:
  775. # Close it, allowing a reopen.
  776. CloseInteractiveWindow()
  777. def ShowInteractiveWindow():
  778. """Shows (or creates if necessary) an interactive window"""
  779. if edit is None:
  780. CreateInteractiveWindow()
  781. else:
  782. if edit.NeedRecreateWindow():
  783. edit.RecreateWindow()
  784. else:
  785. parent = edit.currentView.GetParentFrame()
  786. if parent == win32ui.GetMainFrame(): # It is docked.
  787. edit.currentView.SetFocus()
  788. else: # It is a "normal" window
  789. edit.currentView.GetParentFrame().AutoRestore()
  790. win32ui.GetMainFrame().MDIActivate(edit.currentView.GetParentFrame())
  791. def IsInteractiveWindowVisible():
  792. return edit is not None and not edit.NeedRecreateWindow()