]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/lib/infoframe.py
Added wxAutoNSAutoreleasePool to Create(Tool|Status)Bar
[wxWidgets.git] / wxPython / wx / lib / infoframe.py
1 """
2 infoframe.py
3 Released under wxWindows license etc.
4
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...
11
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
23 echoed].
24
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...
28
29 Typical usage:
30 from wxPython.lib.infoframe import *
31 ... # ... modify your wxApp as follows:
32 class myApp(wxApp):
33 outputWindowClass = wxPyInformationalMessagesFrame
34 ...
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).
38
39 If you don't want to redirect stdout/stderr, but use the class directly: do
40 it this way:
41
42 InformationalMessagesFrame = wxPyInformationalMessagesFrame\
43 ([options from progname (default ""),
44 txt (default "informational
45 messages"])
46 #^^^^ early in the program
47 ...
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'
52 command])
53
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.
64
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.
70
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,
76
77 if __debug__:
78 InformationalMessagesFrame("... with lots of %<Character> constructs"
79 % TUPLE)
80
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...)
85
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...
96
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.
102
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...
112
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.
116
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.
120
121 """
122
123 from wxPython.wx import *
124 import sys, tempfile, os
125
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)
130
131 self.SetStatusText("",0)
132
133 ID = wxNewId()
134 self.button1 = wxButton(self,ID,"Dismiss",
135 style=wxTAB_TRAVERSAL)
136 EVT_BUTTON(self,ID,self.OnButton1)
137
138 ID = wxNewId()
139 if not useopenbutton:
140 self.button2 = wxButton(self,ID,"Close File",
141 style=wxTAB_TRAVERSAL)
142 else:
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
148
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')
153 h = int(h * 1.8)
154 self.SetSize(wxSize(100, h))
155 self.OnSize("dummy")
156 EVT_SIZE(self,self.OnSize)
157
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))
167
168 # widths........
169 def CalculateSizes(self):
170 dc = wxClientDC(self.button1)
171 dc.SetFont(self.button1.GetFont())
172 (w1,h) = dc.GetTextExtent(self.button1.GetLabel())
173
174 dc = wxClientDC(self.button2)
175 dc.SetFont(self.button2.GetFont())
176 (w2,h) = dc.GetTextExtent(self.button2.GetLabel())
177
178 self.SetStatusWidths([-1,w1+15,w2+15])
179
180 def OnButton1(self,event):
181 self.callbacks[0] ()
182
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
189 self.OnSize("")
190 self.button2.Refresh(True)
191 self.Refresh()
192
193
194
195 class wxPyInformationalMessagesFrame:
196 def __init__(self,
197 progname="",
198 text="informational messages",
199 dir='.',
200 menuname="Debug",
201 enableitem="Enable output",
202 disableitem="Disable output",
203 othermenubar=None):
204
205 self.SetOtherMenuBar(othermenubar,
206 menuname=menuname,
207 enableitem=enableitem,
208 disableitem=disableitem)
209
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)
215
216 self.frame = None
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
220 if dir:
221 self.SetOutputDirectory(dir)
222
223
224 def SetParent(self, parent):
225 self.parent = parent
226
227
228 def SetOtherMenuBar(self,
229 othermenu,
230 menuname="Debug",
231 enableitem="Enable output",
232 disableitem="Disable output"):
233 self.othermenu = othermenu
234 self.menuname = menuname
235 self.enableitem = enableitem
236 self.disableitem = disableitem
237
238
239 f = None
240
241
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()
247
248 if self.Enabled:
249 if self.f:
250 self.f.write(string)
251 self.f.flush()
252
253 move = 1
254 if (hasattr(self,"text")
255 and self.text is not None
256 and self.text.GetInsertionPoint() != self.text.GetLastPosition()):
257 move = 0
258
259 if not self.frame:
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)
264
265 self.frame.sb = _MyStatusBar(self.frame,
266 callbacks=[self.DisableOutput,
267 self.CloseFile,
268 self.OpenNewFile],
269 useopenbutton=hasattr(self,
270 "nofile"))
271 self.frame.SetStatusBar(self.frame.sb)
272 self.frame.Show(True)
273 EVT_CLOSE(self.frame, self.OnCloseWindow)
274
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 "
283 "new file...\n\n")
284 else:
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)
296 try:
297 self.f = open(filename, 'w')
298 self.frame.sb.SetStatusText("File '%s' opened..."
299 % filename,
300 0)
301 except EnvironmentError:
302 self.frame.sb.SetStatusText("File creation failed "
303 "(filename '%s')..."
304 % filename,
305 0)
306 self.text.AppendText(string)
307
308 if move:
309 self.text.ShowPosition(self.text.GetLastPosition())
310
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
315
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)
321
322
323 Enabled = 1
324
325 def OnCloseWindow(self, event, exiting=0):
326 if self.f:
327 self.f.close()
328 self.f = None
329
330 if (hasattr(self,"othermenu") and self.othermenu is not None
331 and self.frame is not None
332 and not exiting):
333
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)
338
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
343
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...
349 frame = self.frame
350 self.frame = self.text = None
351 frame.Destroy()
352 self.Enabled = 1
353
354
355 def EnableOutput(self,
356 event=None,# event must be the first optional argument...
357 othermenubar=None,
358 menuname="Debug",
359 enableitem="Enable output",
360 disableitem="Disable output"):
361
362 if othermenubar is not None:
363 self.SetOtherMenuBar(othermenubar,
364 menuname=menuname,
365 enableitem=enableitem,
366 disableitem=disableitem)
367 self.Enabled = 1
368 if self.f:
369 self.f.close()
370 self.f = None
371 self.write("")
372
373
374 def CloseFile(self):
375 if self.f:
376 if self.frame:
377 self.frame.sb.SetStatusText("File '%s' closed..."
378 % os.path.abspath(self.f.name),
379 0)
380 self.f.close ()
381 self.f = None
382 else:
383 if self.frame:
384 self.frame.sb.SetStatusText("")
385 if self.frame:
386 self.frame.sb.Refresh()
387 return 1
388
389
390 def OpenNewFile(self):
391 self.CloseFile()
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:
396 dlg.Destroy()
397 return 0
398 else:
399 try:
400 self.f = open(os.path.abspath(dlg.GetPath()),'w')
401 except EnvironmentError:
402 dlg.Destroy()
403 return 0
404 dlg.Destroy()
405 if self.frame:
406 self.frame.sb.SetStatusText("File '%s' opened..."
407 % os.path.abspath(self.f.name),
408 0)
409 if hasattr(self,"nofile"):
410 self.frame.sb = _MyStatusBar(self.frame,
411 callbacks=[self.DisableOutput,
412 self.CloseFile,
413 self.OpenNewFile])
414 self.frame.SetStatusBar(self.frame.sb)
415 if hasattr(self,"nofile"):
416 delattr(self,"nofile")
417 return 1
418
419
420 def DisableOutput(self,
421 event=None,# event must be the first optional argument...
422 exiting=0):
423 self.write("<InformationalMessagesFrame>.DisableOutput()\n")
424 if hasattr(self,"frame") \
425 and self.frame is not None:
426 self.OnCloseWindow("Dummy",exiting=exiting)
427 self.Enabled = 0
428
429
430 def close(self):
431 self.DisableOutput()
432
433
434 def flush(self):
435 if self.text:
436 self.text.SetInsertionPointEnd()
437 wxYield()
438
439
440 def __call__(self,* args):
441 for s in args:
442 self.write (str (s))
443
444
445 def SetOutputDirectory(self,dir):
446 self.dir = os.path.abspath(dir)
447 ## sys.__stderr__.write("Directory: os.path.abspath(%s) = %s\n"
448 ## % (dir,self.dir))
449
450
451
452 class Dummy_wxPyInformationalMessagesFrame:
453 def __init__(self,progname=""):
454 self.softspace = 1
455 def __call__(self,*args):
456 pass
457 def write(self,s):
458 pass
459 def flush(self):
460 pass
461 def close(self):
462 pass
463 def EnableOutput(self):
464 pass
465 def __call__(self,* args):
466 pass
467 def DisableOutput(self,exiting=0):
468 pass
469 def SetParent(self,wX):
470 pass
471