winout.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. # winout.py
  2. #
  3. # generic "output window"
  4. #
  5. # This Window will detect itself closing, and recreate next time output is
  6. # written to it.
  7. # This has the option of writing output at idle time (by hooking the
  8. # idle message, and queueing output) or writing as each
  9. # write is executed.
  10. # Updating the window directly gives a jerky appearance as many writes
  11. # take place between commands, and the windows scrolls, and updates etc
  12. # Updating at idle-time may defer all output of a long process, giving the
  13. # appearence nothing is happening.
  14. # There is a compromise "line" mode, which will output whenever
  15. # a complete line is available.
  16. # behaviour depends on self.writeQueueing
  17. # This module is thread safe - output can originate from any thread. If any thread
  18. # other than the main thread attempts to print, it is always queued until next idle time
  19. import sys, string, re
  20. from pywin.mfc import docview
  21. from pywin.framework import app, window
  22. import win32ui, win32api, win32con
  23. import queue
  24. debug = lambda msg: None
  25. ##debug=win32ui.OutputDebugString
  26. ##import win32trace;win32trace.InitWrite() # for debugging - delete me!
  27. ##debug = win32trace.write
  28. class flags:
  29. # queueing of output.
  30. WQ_NONE = 0
  31. WQ_LINE = 1
  32. WQ_IDLE = 2
  33. #WindowOutputDocumentParent=docview.RichEditDoc
  34. #WindowOutputDocumentParent=docview.Document
  35. import pywin.scintilla.document
  36. from pywin.scintilla import scintillacon
  37. from pywin import default_scintilla_encoding
  38. WindowOutputDocumentParent=pywin.scintilla.document.CScintillaDocument
  39. class WindowOutputDocument(WindowOutputDocumentParent):
  40. def SaveModified(self):
  41. return 1 # say it is OK to destroy my document
  42. def OnSaveDocument( self, fileName ):
  43. win32ui.SetStatusText("Saving file...",1)
  44. try:
  45. self.SaveFile(fileName)
  46. except IOError as details:
  47. win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details)
  48. return 0
  49. win32ui.SetStatusText("Ready")
  50. return 1
  51. class WindowOutputFrame(window.MDIChildWnd):
  52. def __init__(self, wnd = None):
  53. window.MDIChildWnd.__init__(self, wnd)
  54. self.HookMessage(self.OnSizeMove, win32con.WM_SIZE)
  55. self.HookMessage(self.OnSizeMove, win32con.WM_MOVE)
  56. def LoadFrame( self, idResource, style, wndParent, context ):
  57. self.template = context.template
  58. return self._obj_.LoadFrame(idResource, style, wndParent, context)
  59. def PreCreateWindow(self, cc):
  60. cc = self._obj_.PreCreateWindow(cc)
  61. if self.template.defSize and self.template.defSize[0] != self.template.defSize[1]:
  62. rect = app.RectToCreateStructRect(self.template.defSize)
  63. cc = cc[0], cc[1], cc[2], cc[3], rect, cc[5], cc[6], cc[7], cc[8]
  64. return cc
  65. def OnSizeMove(self, msg):
  66. # so recreate maintains position.
  67. # Need to map coordinates from the
  68. # frame windows first child.
  69. mdiClient = self.GetParent()
  70. self.template.defSize = mdiClient.ScreenToClient(self.GetWindowRect())
  71. def OnDestroy(self, message):
  72. self.template.OnFrameDestroy(self)
  73. return 1
  74. class WindowOutputViewImpl:
  75. def __init__(self):
  76. self.patErrorMessage=re.compile('\W*File "(.*)", line ([0-9]+)')
  77. self.template = self.GetDocument().GetDocTemplate()
  78. def HookHandlers(self):
  79. # Hook for the right-click menu.
  80. self.HookMessage(self.OnRClick,win32con.WM_RBUTTONDOWN)
  81. def OnDestroy(self, msg):
  82. self.template.OnViewDestroy(self)
  83. def OnInitialUpdate(self):
  84. self.RestoreKillBuffer()
  85. self.SetSel(-2) # end of buffer
  86. def GetRightMenuItems(self):
  87. ret = []
  88. flags=win32con.MF_STRING|win32con.MF_ENABLED
  89. ret.append((flags, win32ui.ID_EDIT_COPY, '&Copy'))
  90. ret.append((flags, win32ui.ID_EDIT_SELECT_ALL, '&Select all'))
  91. return ret
  92. #
  93. # Windows command handlers, virtuals, etc.
  94. #
  95. def OnRClick(self,params):
  96. paramsList = self.GetRightMenuItems()
  97. menu = win32ui.CreatePopupMenu()
  98. for appendParams in paramsList:
  99. if type(appendParams)!=type(()):
  100. appendParams = (appendParams,)
  101. menu.AppendMenu(*appendParams)
  102. menu.TrackPopupMenu(params[5]) # track at mouse position.
  103. return 0
  104. # as this is often used as an output window, exeptions will often
  105. # be printed. Therefore, we support this functionality at this level.
  106. # Returns TRUE if the current line is an error message line, and will
  107. # jump to it. FALSE if no error (and no action taken)
  108. def HandleSpecialLine(self):
  109. from . import scriptutils
  110. line = self.GetLine()
  111. if line[:11]=="com_error: ":
  112. # An OLE Exception - pull apart the exception
  113. # and try and locate a help file.
  114. try:
  115. import win32api, win32con
  116. det = eval(line[line.find(":")+1:].strip())
  117. win32ui.SetStatusText("Opening help file on OLE error...");
  118. from . import help
  119. help.OpenHelpFile(det[2][3],win32con.HELP_CONTEXT, det[2][4])
  120. return 1
  121. except win32api.error as details:
  122. win32ui.SetStatusText("The help file could not be opened - %s" % details.strerror)
  123. return 1
  124. except:
  125. win32ui.SetStatusText("Line is a COM error, but no WinHelp details can be parsed");
  126. # Look for a Python traceback.
  127. matchResult = self.patErrorMessage.match(line)
  128. if matchResult is None:
  129. # No match - try the previous line
  130. lineNo = self.LineFromChar()
  131. if lineNo > 0:
  132. line = self.GetLine(lineNo-1)
  133. matchResult = self.patErrorMessage.match(line)
  134. if matchResult is not None:
  135. # we have an error line.
  136. fileName = matchResult.group(1)
  137. if fileName[0]=="<":
  138. win32ui.SetStatusText("Can not load this file")
  139. return 1 # still was an error message.
  140. else:
  141. lineNoString = matchResult.group(2)
  142. # Attempt to locate the file (in case it is a relative spec)
  143. fileNameSpec = fileName
  144. fileName = scriptutils.LocatePythonFile(fileName)
  145. if fileName is None:
  146. # Dont force update, so it replaces the idle prompt.
  147. win32ui.SetStatusText("Cant locate the file '%s'" % (fileNameSpec), 0)
  148. return 1
  149. win32ui.SetStatusText("Jumping to line "+lineNoString+" of file "+fileName,1)
  150. if not scriptutils.JumpToDocument(fileName, int(lineNoString)):
  151. win32ui.SetStatusText("Could not open %s" % fileName)
  152. return 1 # still was an error message.
  153. return 1
  154. return 0 # not an error line
  155. def write(self, msg):
  156. return self.template.write(msg)
  157. def writelines(self, lines):
  158. for line in lines:
  159. self.write(line)
  160. def flush(self):
  161. self.template.flush()
  162. class WindowOutputViewRTF(docview.RichEditView, WindowOutputViewImpl):
  163. def __init__(self, doc):
  164. docview.RichEditView.__init__(self, doc)
  165. WindowOutputViewImpl.__init__(self)
  166. def OnInitialUpdate(self):
  167. WindowOutputViewImpl.OnInitialUpdate(self)
  168. return docview.RichEditView.OnInitialUpdate(self)
  169. def OnDestroy(self, msg):
  170. WindowOutputViewImpl.OnDestroy(self, msg)
  171. docview.RichEditView.OnDestroy(self, msg)
  172. def HookHandlers(self):
  173. WindowOutputViewImpl.HookHandlers(self)
  174. # Hook for finding and locating error messages
  175. self.HookMessage(self.OnLDoubleClick,win32con.WM_LBUTTONDBLCLK)
  176. # docview.RichEditView.HookHandlers(self)
  177. def OnLDoubleClick(self,params):
  178. if self.HandleSpecialLine():
  179. return 0 # dont pass on
  180. return 1 # pass it on by default.
  181. def RestoreKillBuffer(self):
  182. if len(self.template.killBuffer):
  183. self.StreamIn(win32con.SF_RTF, self._StreamRTFIn)
  184. self.template.killBuffer = []
  185. def SaveKillBuffer(self):
  186. self.StreamOut(win32con.SF_RTFNOOBJS, self._StreamRTFOut)
  187. def _StreamRTFOut(self, data):
  188. self.template.killBuffer.append(data)
  189. return 1 # keep em coming!
  190. def _StreamRTFIn(self, bytes):
  191. try:
  192. item = self.template.killBuffer[0]
  193. self.template.killBuffer.remove(item)
  194. if bytes < len(item):
  195. print("Warning - output buffer not big enough!")
  196. return item
  197. except IndexError:
  198. return None
  199. def dowrite(self, str):
  200. self.SetSel(-2)
  201. self.ReplaceSel(str)
  202. import pywin.scintilla.view
  203. class WindowOutputViewScintilla(pywin.scintilla.view.CScintillaView, WindowOutputViewImpl):
  204. def __init__(self, doc):
  205. pywin.scintilla.view.CScintillaView.__init__(self, doc)
  206. WindowOutputViewImpl.__init__(self)
  207. def OnInitialUpdate(self):
  208. pywin.scintilla.view.CScintillaView.OnInitialUpdate(self)
  209. self.SCISetMarginWidth(3)
  210. WindowOutputViewImpl.OnInitialUpdate(self)
  211. def OnDestroy(self, msg):
  212. WindowOutputViewImpl.OnDestroy(self, msg)
  213. pywin.scintilla.view.CScintillaView.OnDestroy(self, msg)
  214. def HookHandlers(self):
  215. WindowOutputViewImpl.HookHandlers(self)
  216. pywin.scintilla.view.CScintillaView.HookHandlers(self)
  217. self.GetParent().HookNotify(self.OnScintillaDoubleClick, scintillacon.SCN_DOUBLECLICK)
  218. ## self.HookMessage(self.OnLDoubleClick,win32con.WM_LBUTTONDBLCLK)
  219. def OnScintillaDoubleClick(self, std, extra):
  220. self.HandleSpecialLine()
  221. ## def OnLDoubleClick(self,params):
  222. ## return 0 # never dont pass on
  223. def RestoreKillBuffer(self):
  224. assert len(self.template.killBuffer) in [0,1], "Unexpected killbuffer contents"
  225. if self.template.killBuffer:
  226. self.SCIAddText(self.template.killBuffer[0])
  227. self.template.killBuffer = []
  228. def SaveKillBuffer(self):
  229. self.template.killBuffer = [self.GetTextRange(0,-1)]
  230. def dowrite(self, str):
  231. end = self.GetTextLength()
  232. atEnd = end==self.GetSel()[0]
  233. self.SCIInsertText(str, end)
  234. if atEnd:
  235. self.SetSel(self.GetTextLength())
  236. def SetWordWrap(self, bWrapOn = 1):
  237. if bWrapOn:
  238. wrap_mode = scintillacon.SC_WRAP_WORD
  239. else:
  240. wrap_mode = scintillacon.SC_WRAP_NONE
  241. self.SCISetWrapMode(wrap_mode)
  242. def _MakeColorizer(self):
  243. return None # No colorizer for me!
  244. WindowOutputView = WindowOutputViewScintilla
  245. # The WindowOutput class is actually an MFC template. This is a conventient way of
  246. # making sure that my state can exist beyond the life of the windows themselves.
  247. # This is primarily to support the functionality of a WindowOutput window automatically
  248. # being recreated if necessary when written to.
  249. class WindowOutput(docview.DocTemplate):
  250. """ Looks like a general Output Window - text can be written by the 'write' method.
  251. Will auto-create itself on first write, and also on next write after being closed """
  252. softspace=1
  253. def __init__(self, title=None, defSize=None, queueing = flags.WQ_LINE, \
  254. bAutoRestore = 1, style=None,
  255. makeDoc = None, makeFrame = None, makeView = None):
  256. """ init the output window -
  257. Params
  258. title=None -- What is the title of the window
  259. defSize=None -- What is the default size for the window - if this
  260. is a string, the size will be loaded from the ini file.
  261. queueing = flags.WQ_LINE -- When should output be written
  262. bAutoRestore=1 -- Should a minimized window be restored.
  263. style -- Style for Window, or None for default.
  264. makeDoc, makeFrame, makeView -- Classes for frame, view and window respectively.
  265. """
  266. if makeDoc is None: makeDoc = WindowOutputDocument
  267. if makeFrame is None: makeFrame = WindowOutputFrame
  268. if makeView is None: makeView = WindowOutputViewScintilla
  269. docview.DocTemplate.__init__(self, win32ui.IDR_PYTHONTYPE, \
  270. makeDoc, makeFrame, makeView)
  271. self.SetDocStrings("\nOutput\n\nText Documents (*.txt)\n.txt\n\n\n")
  272. win32ui.GetApp().AddDocTemplate(self)
  273. self.writeQueueing = queueing
  274. self.errorCantRecreate = 0
  275. self.killBuffer=[]
  276. self.style = style
  277. self.bAutoRestore = bAutoRestore
  278. self.title = title
  279. self.bCreating = 0
  280. self.interruptCount = 0
  281. if type(defSize)==type(''): # is a string - maintain size pos from ini file.
  282. self.iniSizeSection = defSize
  283. self.defSize = app.LoadWindowSize(defSize)
  284. self.loadedSize = self.defSize
  285. else:
  286. self.iniSizeSection = None
  287. self.defSize=defSize
  288. self.currentView = None
  289. self.outputQueue = queue.Queue(-1)
  290. self.mainThreadId = win32api.GetCurrentThreadId()
  291. self.idleHandlerSet = 0
  292. self.SetIdleHandler()
  293. def __del__(self):
  294. self.Close()
  295. def Create(self, title=None, style = None):
  296. self.bCreating = 1
  297. if title: self.title = title
  298. if style: self.style = style
  299. doc=self.OpenDocumentFile()
  300. if doc is None: return
  301. self.currentView = doc.GetFirstView()
  302. self.bCreating = 0
  303. if self.title: doc.SetTitle(self.title)
  304. def Close(self):
  305. self.RemoveIdleHandler()
  306. try:
  307. parent = self.currentView.GetParent()
  308. except (AttributeError, win32ui.error): # Already closed
  309. return
  310. parent.DestroyWindow()
  311. def SetTitle(self, title):
  312. self.title = title
  313. if self.currentView: self.currentView.GetDocument().SetTitle(self.title)
  314. def OnViewDestroy(self, view):
  315. self.currentView.SaveKillBuffer()
  316. self.currentView = None
  317. def OnFrameDestroy(self, frame):
  318. if self.iniSizeSection:
  319. # use GetWindowPlacement(), as it works even when min'd or max'd
  320. newSize = frame.GetWindowPlacement()[4]
  321. if self.loadedSize!=newSize:
  322. app.SaveWindowSize(self.iniSizeSection, newSize)
  323. def SetIdleHandler(self):
  324. if not self.idleHandlerSet:
  325. debug("Idle handler set\n")
  326. win32ui.GetApp().AddIdleHandler(self.QueueIdleHandler)
  327. self.idleHandlerSet = 1
  328. def RemoveIdleHandler(self):
  329. if self.idleHandlerSet:
  330. debug("Idle handler reset\n")
  331. if (win32ui.GetApp().DeleteIdleHandler(self.QueueIdleHandler)==0):
  332. debug('Error deleting idle handler\n')
  333. self.idleHandlerSet = 0
  334. def RecreateWindow(self):
  335. if self.errorCantRecreate:
  336. debug("Error = not trying again")
  337. return 0
  338. try:
  339. # This will fail if app shutting down
  340. win32ui.GetMainFrame().GetSafeHwnd()
  341. self.Create()
  342. return 1
  343. except (win32ui.error, AttributeError):
  344. self.errorCantRecreate = 1
  345. debug("Winout can not recreate the Window!\n")
  346. return 0
  347. # this handles the idle message, and does the printing.
  348. def QueueIdleHandler(self,handler,count):
  349. try:
  350. bEmpty = self.QueueFlush(20)
  351. # If the queue is empty, then we are back to idle and restart interrupt logic.
  352. if bEmpty: self.interruptCount = 0
  353. except KeyboardInterrupt:
  354. # First interrupt since idle we just pass on.
  355. # later ones we dump the queue and give up.
  356. self.interruptCount = self.interruptCount + 1
  357. if self.interruptCount > 1:
  358. # Drop the queue quickly as the user is already annoyed :-)
  359. self.outputQueue = queue.Queue(-1)
  360. print("Interrupted.")
  361. bEmpty = 1
  362. else:
  363. raise # re-raise the error so the users exception filters up.
  364. return not bEmpty # More to do if not empty.
  365. # Returns true if the Window needs to be recreated.
  366. def NeedRecreateWindow(self):
  367. try:
  368. if self.currentView is not None and self.currentView.IsWindow():
  369. return 0
  370. except (win32ui.error, AttributeError): # Attribute error if the win32ui object has died.
  371. pass
  372. return 1
  373. # Returns true if the Window is OK (either cos it was, or because it was recreated
  374. def CheckRecreateWindow(self):
  375. if self.bCreating: return 1
  376. if not self.NeedRecreateWindow():
  377. return 1
  378. if self.bAutoRestore:
  379. if self.RecreateWindow():
  380. return 1
  381. return 0
  382. def QueueFlush(self, max = None):
  383. # Returns true if the queue is empty after the flush
  384. # debug("Queueflush - %d, %d\n" % (max, self.outputQueue.qsize()))
  385. if self.bCreating: return 1
  386. items = []
  387. rc = 0
  388. while max is None or max > 0:
  389. try:
  390. item = self.outputQueue.get_nowait()
  391. items.append(item)
  392. except queue.Empty:
  393. rc = 1
  394. break
  395. if max is not None:
  396. max = max - 1
  397. if len(items) != 0:
  398. if not self.CheckRecreateWindow():
  399. debug(":Recreate failed!\n")
  400. return 1 # In trouble - so say we have nothing to do.
  401. win32ui.PumpWaitingMessages() # Pump paint messages
  402. self.currentView.dowrite(''.join(items))
  403. return rc
  404. def HandleOutput(self,message):
  405. # debug("QueueOutput on thread %d, flags %d with '%s'...\n" % (win32api.GetCurrentThreadId(), self.writeQueueing, message ))
  406. self.outputQueue.put(message)
  407. if win32api.GetCurrentThreadId() != self.mainThreadId:
  408. pass
  409. # debug("not my thread - ignoring queue options!\n")
  410. elif self.writeQueueing==flags.WQ_LINE:
  411. pos = message.rfind('\n')
  412. if pos>=0:
  413. # debug("Line queueing - forcing flush\n")
  414. self.QueueFlush()
  415. return
  416. elif self.writeQueueing==flags.WQ_NONE:
  417. # debug("WQ_NONE - flushing!\n")
  418. self.QueueFlush()
  419. return
  420. # Let our idle handler get it - wake it up
  421. try:
  422. win32ui.GetMainFrame().PostMessage(win32con.WM_USER) # Kick main thread off.
  423. except win32ui.error:
  424. # This can happen as the app is shutting down, so we send it to the C++ debugger
  425. win32api.OutputDebugString(message)
  426. # delegate certain fns to my view.
  427. def writelines(self, lines):
  428. for line in lines:
  429. self.write(line)
  430. def write(self,message):
  431. self.HandleOutput(message)
  432. def flush(self):
  433. self.QueueFlush()
  434. def HandleSpecialLine(self):
  435. self.currentView.HandleSpecialLine()
  436. def RTFWindowOutput(*args, **kw):
  437. kw['makeView'] = WindowOutputViewRTF
  438. return WindowOutput(*args, **kw)
  439. def thread_test(o):
  440. for i in range(5):
  441. o.write("Hi from thread %d\n" % (win32api.GetCurrentThreadId()))
  442. win32api.Sleep(100)
  443. def test():
  444. w = WindowOutput(queueing=flags.WQ_IDLE)
  445. w.write("First bit of text\n")
  446. import _thread
  447. for i in range(5):
  448. w.write("Hello from the main thread\n")
  449. _thread.start_new(thread_test, (w,))
  450. for i in range(2):
  451. w.write("Hello from the main thread\n")
  452. win32api.Sleep(50)
  453. return w
  454. if __name__=='__main__':
  455. test()