3 Released under wxWindows license etc.
5 This is a fairly rudimentary, but slightly fancier tha
6 wxPyOnDemandOutputWindow (on which it's based; thanks Robin), version
7 of the same sort of thing: a file-like class called
8 wxInformationalMessagesFrame. This window also has a status bar with a
9 couple of buttons for controlling the echoing of all output to a file
10 with a randomly-chosen filename...
12 The class behaves similarly to wxPyOnDemandOutputWindow in that (at
13 least by default) the frame does not appear until written to, but is
14 somewhat different in that, either under programmatic (the
15 DisableOutput method) or user (the frame's close button, it's status
16 bar's "Dismiss" button, or a "Disable output" item of some menu,
17 perhaps of some other frame), the frame will be destroyed, an
18 associated file closed, and writing to it will then do nothing. This
19 can be reversed: either under programmatic (the EnableOutput method)
20 or user (an "Enable output" item of some menu), a new frame will be
21 opened,And an associated file (with a "randomly"selected filename)
22 opened for writing [to which all subsequent displayed messages will be
25 Please note that, like wxPyOnDemandOutputWindow, the instance is not
26 itself a subclass of wxWindow: when the window is open (and ONLY
27 then), it's "frame" attribute is the actual instance of wFrame...
30 from wxPython.lib.infoframe import *
31 ... # ... modify your wxApp as follows:
33 outputWindowClass = wxPyInformationalMessagesFrame
35 If you're running on Linux, you'll also have to supply an argument 1 to your
36 constructor of myApp to redirect stdout/stderr to this window (it's done
37 automatically for you on Windows).
39 If you don't want to redirect stdout/stderr, but use the class directly: do
42 InformationalMessagesFrame = wxPyInformationalMessagesFrame\
43 ([options from progname (default ""),
44 txt (default "informational
46 #^^^^ early in the program
48 InformationalMessagesFrame([comma-separated list of items to
49 display. Note that these will never
50 be separated by spaces as they may
51 be when used in the Python 'print'
54 The latter statement, of course, may be repeated arbitrarily often.
55 The window will not appear until it is written to, and it may be
56 manually closed by the user, after which it will reappear again until
57 written to... Also note that all output is echoed to a file with a
58 randomly-generated name [see the mktemp module in the standard
59 library], in the directory given as the 'dir' keyword argument to the
60 InformationalMessagesFrame constructor [which has a default value of
61 '.'), or set via the method SetOutputDirectory... This file will be
62 closed with the window--a new one will be created [by default] upon
63 each subsequent reopening.
65 Please also note the methods EnableOutput and DisableOutput, and the
66 possible arguments for the constructor in the code below... (* TO DO:
67 explain this here...*) Neither of these methods need be used at all,
68 and in this case the frame will only be displayed once it has been
69 written to, like wxPyOnDemandOutputWindow.
71 The former, EnableOutput, displays the frame with an introductory
72 message, opens a random file to which future displayed output also
73 goes (unless the nofile attribute is present), and sets the __debug__
74 variable of each module to 1 (unless the no __debug__ attribute is
75 present]. This is so that you can say, in any module whatsoever,
78 InformationalMessagesFrame("... with lots of %<Character> constructs"
81 without worrying about the overhead of evaluating the arguments, and
82 calling the wxInformationalMessagesFrame instance, in the case where
83 debugging is not turned on. (This won't happen if the instance has an
84 attribute no__debug__; you can arrange this by sub-classing...)
86 "Debug mode" can also be turned on by selecting the item-"Enable
87 output" from the "Debug" menu [the default--see the optional arguments
88 to the SetOtherMenuBar method] of a frame which has been either passed
89 appropriately to the constructor of the wxInformationalMessagesFrame
90 (see the code), or set via the SetOtherMenuBar method thereof. This
91 also writes an empty string to the instance, meaning that the frame
92 will open (unless DisablOutput has been called) with an appropriate
93 introductory message (which will vary according to whether the
94 instance/class has the "no __debug__" attribute)^ I have found this to
95 be an extremely useful tool, in lieu of a full wxPython debugger...
97 Following this, the menu item is also disabled, and an item "Disable
98 output" (again, by default) is enabled. Note that these need not be
99 done: e.g., you don't NEED to have a menu with appropriate items; in
100 this case simply do not call the SetOtherMenuBar method or use the
101 othermenubar keyword argument of the class instance constructor.
103 The DisableOutput method does the reverse of this; it closes the
104 window (and associated file), and sets the __debug__ variable of each
105 module whose name begins with a capital letter {this happens to be the
106 author's personal practice; all my python module start with capital
107 letters} to 0. It also enables/disabled the appropriate menu items,
108 if this was done previously (or SetOtherMenuBar has been called...).
109 Note too that after a call to DisableOutput, nothing further will be
110 done upon subsequent write()'s, until the EnableOutput method is
111 called, either explicitly or by the menu selection above...
113 Finally, note that the file-like method close() destroys the window
114 (and closes any associated file) and there is a file-like method
115 write() which displays it's argument.
117 All (well, most) of this is made clear by the example code at the end
118 of this file, which is run if the file is run by itself; otherwise,
119 see the appropriate "stub" file in the wxPython demo.
123 from wxPython
.wx
import *
124 import sys
, tempfile
, os
126 class _MyStatusBar(wxStatusBar
):
127 def __init__(self
, parent
,callbacks
=None,useopenbutton
=0):
128 wxStatusBar
.__init
__(self
, parent
, -1, style
=wxTAB_TRAVERSAL
)
129 self
.SetFieldsCount(3)
131 self
.SetStatusText("",0)
134 self
.button1
= wxButton(self
,ID
,"Dismiss",
135 style
=wxTAB_TRAVERSAL
)
136 EVT_BUTTON(self
,ID
,self
.OnButton1
)
139 if not useopenbutton
:
140 self
.button2
= wxButton(self
,ID
,"Close File",
141 style
=wxTAB_TRAVERSAL
)
143 self
.button2
= wxButton(self
,ID
,"Open New File",
144 style
=wxTAB_TRAVERSAL
)
145 EVT_BUTTON(self
,ID
,self
.OnButton2
)
146 self
.useopenbutton
= useopenbutton
147 self
.callbacks
= callbacks
149 # figure out how tall to make the status bar
150 dc
= wxClientDC(self
)
151 dc
.SetFont(self
.GetFont())
152 (w
,h
) = dc
.GetTextExtent('X')
154 self
.SetSize(wxSize(100, h
))
156 EVT_SIZE(self
,self
.OnSize
)
158 # reposition things...
159 def OnSize(self
, event
):
160 self
.CalculateSizes()
161 rect
= self
.GetFieldRect(1)
162 self
.button1
.SetPosition(wxPoint(rect
.x
+5, rect
.y
+2))
163 self
.button1
.SetSize(wxSize(rect
.width
-10, rect
.height
-4))
164 rect
= self
.GetFieldRect(2)
165 self
.button2
.SetPosition(wxPoint(rect
.x
+5, rect
.y
+2))
166 self
.button2
.SetSize(wxSize(rect
.width
-10, rect
.height
-4))
169 def CalculateSizes(self
):
170 dc
= wxClientDC(self
.button1
)
171 dc
.SetFont(self
.button1
.GetFont())
172 (w1
,h
) = dc
.GetTextExtent(self
.button1
.GetLabel())
174 dc
= wxClientDC(self
.button2
)
175 dc
.SetFont(self
.button2
.GetFont())
176 (w2
,h
) = dc
.GetTextExtent(self
.button2
.GetLabel())
178 self
.SetStatusWidths([-1,w1
+15,w2
+15])
180 def OnButton1(self
,event
):
183 def OnButton2(self
,event
):
184 if self
.useopenbutton
and self
.callbacks
[2] ():
185 self
.button2
.SetLabel ("Close File")
186 elif self
.callbacks
[1] ():
187 self
.button2
.SetLabel ("Open New File")
188 self
.useopenbutton
= 1 - self
.useopenbutton
190 self
.button2
.Refresh(True)
195 class wxPyInformationalMessagesFrame
:
198 text
="informational messages",
201 enableitem
="Enable output",
202 disableitem
="Disable output",
205 self
.SetOtherMenuBar(othermenubar
,
207 enableitem
=enableitem
,
208 disableitem
=disableitem
)
210 if hasattr(self
,"othermenu") and self
.othermenu
is not None:
211 i
= self
.othermenu
.FindMenuItem(self
.menuname
,self
.disableitem
)
212 self
.othermenu
.Enable(i
,0)
213 i
= self
.othermenu
.FindMenuItem(self
.menuname
,self
.enableitem
)
214 self
.othermenu
.Enable(i
,1)
217 self
.title
= "%s %s" % (progname
,text
)
218 self
.parent
= None # use the SetParent method if desired...
219 self
.softspace
= 1 # of rather limited use
221 self
.SetOutputDirectory(dir)
224 def SetParent(self
, parent
):
228 def SetOtherMenuBar(self
,
231 enableitem
="Enable output",
232 disableitem
="Disable output"):
233 self
.othermenu
= othermenu
234 self
.menuname
= menuname
235 self
.enableitem
= enableitem
236 self
.disableitem
= disableitem
242 def write(self
,string
):
243 if not wxThread_IsMain():
244 # Aquire the GUI mutex before making GUI calls. Mutex is released
245 # when locker is deleted at the end of this function.
246 locker
= wxMutexGuiLocker()
254 if (hasattr(self
,"text")
255 and self
.text
is not None
256 and self
.text
.GetInsertionPoint() != self
.text
.GetLastPosition()):
260 self
.frame
= wxFrame(self
.parent
, -1, self
.title
, size
=(450, 300),
261 style
=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE
)
262 self
.text
= wxTextCtrl(self
.frame
, -1, "",
263 style
= wxTE_MULTILINE|wxTE_READONLY|wxTE_RICH
)
265 self
.frame
.sb
= _MyStatusBar(self
.frame
,
266 callbacks
=[self
.DisableOutput
,
269 useopenbutton
=hasattr(self
,
271 self
.frame
.SetStatusBar(self
.frame
.sb
)
272 self
.frame
.Show(True)
273 EVT_CLOSE(self
.frame
, self
.OnCloseWindow
)
275 if hasattr(self
,"nofile"):
276 self
.text
.AppendText(
277 "Please close this window (or select the "
278 "'Dismiss' button below) when desired. By "
279 "default all messages written to this window "
280 "will NOT be written to a file--you "
281 "may change this by selecting 'Open New File' "
282 "below, allowing you to select a "
285 tempfile
.tempdir
= self
.dir
286 filename
= os
.path
.abspath(tempfile
.mktemp ())
287 self
.text
.AppendText(
288 "Please close this window (or select the "
289 "'Dismiss' button below) when desired. By "
290 "default all messages written to this window "
291 "will also be written to the file '%s'--you "
292 "may close this file by selecting 'Close "
293 "File' below, whereupon this button will be "
294 "replaced with one allowing you to select a "
295 "new file...\n\n" % filename
)
297 self
.f
= open(filename
, 'w')
298 self
.frame
.sb
.SetStatusText("File '%s' opened..."
301 except EnvironmentError:
302 self
.frame
.sb
.SetStatusText("File creation failed "
306 self
.text
.AppendText(string
)
309 self
.text
.ShowPosition(self
.text
.GetLastPosition())
311 if not hasattr(self
,"no__debug__"):
312 for m
in sys
.modules
.values():
313 if m
is not None:# and m.__dict__.has_key("__debug__"):
314 m
.__dict
__["__debug__"] = 1
316 if hasattr(self
,"othermenu") and self
.othermenu
is not None:
317 i
= self
.othermenu
.FindMenuItem(self
.menuname
,self
.disableitem
)
318 self
.othermenu
.Enable(i
,1)
319 i
= self
.othermenu
.FindMenuItem(self
.menuname
,self
.enableitem
)
320 self
.othermenu
.Enable(i
,0)
325 def OnCloseWindow(self
, event
, exiting
=0):
330 if (hasattr(self
,"othermenu") and self
.othermenu
is not None
331 and self
.frame
is not None
334 i
= self
.othermenu
.FindMenuItem(self
.menuname
,self
.disableitem
)
335 self
.othermenu
.Enable(i
,0)
336 i
= self
.othermenu
.FindMenuItem(self
.menuname
,self
.enableitem
)
337 self
.othermenu
.Enable(i
,1)
339 if not hasattr(self
,"no__debug__"):
340 for m
in sys
.modules
.values():
341 if m
is not None:# and m.__dict__.has_key("__debug__"):
342 m
.__dict
__["__debug__"] = 0
344 if self
.frame
is not None: # typically True, but, e.g., allows
345 # DisableOutput method (which calls this
346 # one) to be called when the frame is not
347 # actually open, so that it is always safe
348 # to call this method...
350 self
.frame
= self
.text
= None
355 def EnableOutput(self
,
356 event
=None,# event must be the first optional argument...
359 enableitem
="Enable output",
360 disableitem
="Disable output"):
362 if othermenubar
is not None:
363 self
.SetOtherMenuBar(othermenubar
,
365 enableitem
=enableitem
,
366 disableitem
=disableitem
)
377 self
.frame
.sb
.SetStatusText("File '%s' closed..."
378 % os
.path
.abspath(self
.f
.name
),
384 self
.frame
.sb
.SetStatusText("")
386 self
.frame
.sb
.Refresh()
390 def OpenNewFile(self
):
392 dlg
= wxFileDialog(self
.frame
,
393 "Choose a new log file", self
.dir,"","*",
394 wxSAVE | wxHIDE_READONLY | wxOVERWRITE_PROMPT
)
395 if dlg
.ShowModal() == wxID_CANCEL
:
400 self
.f
= open(os
.path
.abspath(dlg
.GetPath()),'w')
401 except EnvironmentError:
406 self
.frame
.sb
.SetStatusText("File '%s' opened..."
407 % os
.path
.abspath(self
.f
.name
),
409 if hasattr(self
,"nofile"):
410 self
.frame
.sb
= _MyStatusBar(self
.frame
,
411 callbacks
=[self
.DisableOutput
,
414 self
.frame
.SetStatusBar(self
.frame
.sb
)
415 if hasattr(self
,"nofile"):
416 delattr(self
,"nofile")
420 def DisableOutput(self
,
421 event
=None,# event must be the first optional argument...
423 self
.write("<InformationalMessagesFrame>.DisableOutput()\n")
424 if hasattr(self
,"frame") \
425 and self
.frame
is not None:
426 self
.OnCloseWindow("Dummy",exiting
=exiting
)
436 self
.text
.SetInsertionPointEnd()
440 def __call__(self
,* args
):
445 def SetOutputDirectory(self
,dir):
446 self
.dir = os
.path
.abspath(dir)
447 ## sys.__stderr__.write("Directory: os.path.abspath(%s) = %s\n"
452 class Dummy_wxPyInformationalMessagesFrame
:
453 def __init__(self
,progname
=""):
455 def __call__(self
,*args
):
463 def EnableOutput(self
):
465 def __call__(self
,* args
):
467 def DisableOutput(self
,exiting
=0):
469 def SetParent(self
,wX
):