]> git.saurik.com Git - wxWidgets.git/blob - wxPython/demo/Main.py
4cc8d92819671b7bd8da522ab6480b72be2128aa
[wxWidgets.git] / wxPython / demo / Main.py
1 #!/bin/env python
2 #----------------------------------------------------------------------------
3 # Name: Main.py
4 # Purpose: Testing lots of stuff, controls, window types, etc.
5 #
6 # Author: Robin Dunn
7 #
8 # Created: A long time ago, in a galaxy far, far away...
9 # RCS-ID: $Id$
10 # Copyright: (c) 1999 by Total Control Software
11 # Licence: wxWindows license
12 #----------------------------------------------------------------------------
13
14 import sys, os, time, string
15 from wxPython.wx import *
16 from wxPython.html import wxHtmlWindow
17
18 import images
19
20 #---------------------------------------------------------------------------
21
22
23 _treeList = [
24 # new stuff
25 ('New since last release', [
26 'RowColSizer',
27 'Unicode',
28 'wxFileHistory',
29 'wxGenericDirCtrl',
30 'wxImageFromStream',
31 ]),
32
33 # managed windows == things with a caption you can close
34 ('Base Frames and Dialogs', [
35 'wxDialog',
36 'wxFrame',
37 'wxMDIWindows',
38 'wxMiniFrame',
39 ]),
40
41 # the common dialogs
42 ('Common Dialogs', [
43 'wxColourDialog',
44 'wxDirDialog',
45 'wxFileDialog',
46 'wxFindReplaceDialog',
47 'wxFontDialog',
48 'wxMessageDialog',
49 'wxPageSetupDialog',
50 'wxPrintDialog',
51 'wxProgressDialog',
52 'wxSingleChoiceDialog',
53 'wxTextEntryDialog',
54 ]),
55
56 # dialogs form libraries
57 ('More Dialogs', [
58 'ErrorDialogs',
59 'ImageBrowser',
60 'wxMultipleChoiceDialog',
61 'wxScrolledMessageDialog',
62 ]),
63
64 # core controls
65 ('Core Windows/Controls', [
66 'VirtualListCtrl',
67 'wxButton',
68 'wxCheckBox',
69 'wxCheckListBox',
70 'wxChoice',
71 'wxComboBox',
72 'wxGauge',
73 'wxGenericDirCtrl',
74 'wxGrid',
75 'wxListBox',
76 'wxListCtrl',
77 'wxNotebook',
78 'wxPopupWindow',
79 'wxRadioBox',
80 'wxSashWindow',
81 'wxSlider',
82 'wxScrolledWindow',
83 'wxSplitterWindow',
84 'wxSpinButton',
85 'wxSpinCtrl',
86 'wxStaticText',
87 'wxStaticBitmap',
88 'wxStatusBar',
89 'wxTextCtrl',
90 'wxToggleButton',
91 'wxToolBar',
92 'wxTreeCtrl',
93 'wxValidator',
94 ]),
95
96 # controls coming from other librairies
97 ('More Windows/Controls', [
98 'ColourSelect',
99 'ContextHelp',
100 'FancyText',
101 'FileBrowseButton',
102 'GenericButtons',
103 'PyCrust',
104 'PyCrustWithFilling',
105 'SplitTree',
106 'TablePrint',
107 'wxCalendar',
108 'wxCalendarCtrl',
109 'wxDynamicSashWindow',
110 'wxEditableListBox',
111 'wxEditor',
112 'wxFloatBar',
113 'wxHtmlWindow',
114 'wxLEDNumberCtrl',
115 'wxMimeTypesManager',
116 'wxMVCTree',
117 'wxStyledTextCtrl_1',
118 'wxStyledTextCtrl_2',
119 'wxRightTextCtrl',
120 ]),
121
122 # How to lay out the controls in a frame/dialog
123 ('Window Layout', [
124 'LayoutAnchors',
125 'Layoutf',
126 'RowColSizer',
127 'Sizers',
128 'wxLayoutConstraints',
129 'XML_Resource',
130 ]),
131
132 # ditto
133 ('Process and Events', [
134 'infoframe',
135 'OOR',
136 'PythonEvents',
137 'Threads',
138 'wxProcess',
139 'wxTimer',
140 ]),
141
142 # Clipboard and DnD
143 ('Clipboard and DnD', [
144 'CustomDragAndDrop',
145 'DragAndDrop',
146 'URLDragAndDrop',
147 ]),
148
149 # Images
150 ('Images', [
151 'wxDragImage',
152 'wxImage',
153 'wxImageFromStream',
154 'wxMask',
155 ]),
156
157 # Other stuff
158 ('Miscellaneous', [
159 'ColourDB',
160 'DialogUnits',
161 'DrawXXXList',
162 'FontEnumerator',
163 'PrintFramework',
164 'Unicode',
165 'wxFileHistory',
166 'wxJoystick',
167 'wxOGL',
168 'wxWave',
169 ]),
170
171 # need libs not coming with the demo
172 ('Objects using an external library', [
173 'ActiveXWrapper_Acrobat',
174 'ActiveXWrapper_IE',
175 'wxGLCanvas',
176 'wxPlotCanvas',
177 ]),
178
179 # pyTree, hangman, ... in the samples dir
180 ('Check out the samples dir too', [
181 ]),
182
183 ]
184
185
186
187 #---------------------------------------------------------------------------
188
189 class MyLog(wxPyLog):
190 def __init__(self, textCtrl, logTime=0):
191 wxPyLog.__init__(self)
192 self.tc = textCtrl
193 self.logTime = logTime
194
195 def DoLogString(self, message, timeStamp):
196 if self.logTime:
197 message = time.strftime("%X", time.localtime(timeStamp)) + \
198 ": " + message
199 self.tc.AppendText(message + '\n')
200
201
202 #---------------------------------------------------------------------------
203
204 def opj(path):
205 """Convert paths to the platform-specific separator"""
206 return apply(os.path.join, tuple(string.split(path, '/')))
207
208
209 #---------------------------------------------------------------------------
210
211 class wxPythonDemo(wxFrame):
212 overviewText = "wxPython Overview"
213
214 def __init__(self, parent, id, title):
215 wxFrame.__init__(self, parent, -1, title, size = (800, 600),
216 style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE)
217
218 self.cwd = os.getcwd()
219 self.curOverview = ""
220
221 icon = images.getMondrianIcon()
222 self.SetIcon(icon)
223
224 if wxPlatform == '__WXMSW__':
225 # setup a taskbar icon, and catch some events from it
226 self.tbicon = wxTaskBarIcon()
227 self.tbicon.SetIcon(icon, "wxPython Demo")
228 EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
229 EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
230 EVT_MENU(self.tbicon, self.TBMENU_RESTORE, self.OnTaskBarActivate)
231 EVT_MENU(self.tbicon, self.TBMENU_CLOSE, self.OnTaskBarClose)
232
233
234 self.otherWin = None
235 self.showTip = true
236 EVT_IDLE(self, self.OnIdle)
237 EVT_CLOSE(self, self.OnCloseWindow)
238 EVT_ICONIZE(self, self.OnIconfiy)
239 EVT_MAXIMIZE(self, self.OnMaximize)
240
241 self.Centre(wxBOTH)
242 self.CreateStatusBar(1, wxST_SIZEGRIP)
243
244 splitter = wxSplitterWindow(self, -1, style=wxNO_3D|wxSP_3D)
245 splitter2 = wxSplitterWindow(splitter, -1, style=wxNO_3D|wxSP_3D)
246
247 def EmptyHandler(evt): pass
248 EVT_ERASE_BACKGROUND(splitter, EmptyHandler)
249 EVT_ERASE_BACKGROUND(splitter2, EmptyHandler)
250
251 # Prevent TreeCtrl from displaying all items after destruction when true
252 self.dying = false
253
254 # Make a File menu
255 self.mainmenu = wxMenuBar()
256 menu = wxMenu()
257 exitID = wxNewId()
258 menu.Append(exitID, 'E&xit\tAlt-X', 'Get the heck outta here!')
259 EVT_MENU(self, exitID, self.OnFileExit)
260 self.mainmenu.Append(menu, '&File')
261
262 # Make a Demo menu
263 menu = wxMenu()
264 for item in _treeList:
265 submenu = wxMenu()
266 for childItem in item[1]:
267 mID = wxNewId()
268 submenu.Append(mID, childItem)
269 EVT_MENU(self, mID, self.OnDemoMenu)
270 menu.AppendMenu(wxNewId(), item[0], submenu)
271 self.mainmenu.Append(menu, '&Demo')
272
273
274 # Make a Help menu
275 helpID = wxNewId()
276 menu = wxMenu()
277 menu.Append(helpID, '&About\tCtrl-H', 'wxPython RULES!!!')
278 EVT_MENU(self, helpID, self.OnHelpAbout)
279 self.mainmenu.Append(menu, '&Help')
280 self.SetMenuBar(self.mainmenu)
281
282 # set the menu accellerator table...
283 aTable = wxAcceleratorTable([(wxACCEL_ALT, ord('X'), exitID),
284 (wxACCEL_CTRL, ord('H'), helpID)])
285 self.SetAcceleratorTable(aTable)
286
287
288 # Create a TreeCtrl
289 tID = wxNewId()
290 self.treeMap = {}
291 self.tree = wxTreeCtrl(splitter, tID,
292 style=wxTR_HAS_BUTTONS |
293 wxTR_EDIT_LABELS |
294 wxTR_HAS_VARIABLE_ROW_HEIGHT)
295
296 #self.tree.SetBackgroundColour(wxNamedColour("Pink"))
297 root = self.tree.AddRoot("wxPython Overview")
298 firstChild = None
299 for item in _treeList:
300 child = self.tree.AppendItem(root, item[0])
301 if not firstChild: firstChild = child
302 for childItem in item[1]:
303 theDemo = self.tree.AppendItem(child, childItem)
304 self.treeMap[childItem] = theDemo
305
306 self.tree.Expand(root)
307 self.tree.Expand(firstChild)
308 EVT_TREE_ITEM_EXPANDED (self.tree, tID, self.OnItemExpanded)
309 EVT_TREE_ITEM_COLLAPSED (self.tree, tID, self.OnItemCollapsed)
310 EVT_TREE_SEL_CHANGED (self.tree, tID, self.OnSelChanged)
311 EVT_LEFT_DOWN (self.tree, self.OnTreeLeftDown)
312
313 # Create a Notebook
314 self.nb = wxNotebook(splitter2, -1, style=wxCLIP_CHILDREN)
315
316 # Set up a wxHtmlWindow on the Overview Notebook page
317 # we put it in a panel first because there seems to be a
318 # refresh bug of some sort (wxGTK) when it is directly in
319 # the notebook...
320 if 0: # the old way
321 self.ovr = wxHtmlWindow(self.nb, -1, size=(400, 400))
322 self.nb.AddPage(self.ovr, self.overviewText)
323
324 else: # hopefully I can remove this hacky code soon, see bug #216861
325 panel = wxPanel(self.nb, -1, style=wxCLIP_CHILDREN)
326 self.ovr = wxHtmlWindow(panel, -1, size=(400, 400))
327 self.nb.AddPage(panel, self.overviewText)
328
329 def OnOvrSize(evt, ovr=self.ovr):
330 ovr.SetSize(evt.GetSize())
331
332 EVT_SIZE(panel, OnOvrSize)
333 EVT_ERASE_BACKGROUND(panel, EmptyHandler)
334
335
336 self.SetOverview(self.overviewText, overview)
337
338
339 # Set up a TextCtrl on the Demo Code Notebook page
340 self.txt = wxTextCtrl(self.nb, -1,
341 style = wxTE_MULTILINE|wxTE_READONLY|wxHSCROLL)
342 self.nb.AddPage(self.txt, "Demo Code")
343
344
345 # Set up a log on the View Log Notebook page
346 self.log = wxTextCtrl(splitter2, -1,
347 style = wxTE_MULTILINE|wxTE_READONLY|wxHSCROLL)
348
349 # Set the wxWindows log target to be this textctrl
350 #wxLog_SetActiveTarget(wxLogTextCtrl(self.log))
351
352 # But instead of the above we want to show how to use our own wxLog class
353 wxLog_SetActiveTarget(MyLog(self.log))
354
355
356
357 self.Show(true)
358
359 # add the windows to the splitter and split it.
360 splitter2.SplitHorizontally(self.nb, self.log)
361 splitter.SplitVertically(self.tree, splitter2)
362
363 splitter.SetSashPosition(180, true)
364 splitter.SetMinimumPaneSize(20)
365 splitter2.SetSashPosition(450, true)
366 splitter2.SetMinimumPaneSize(20)
367
368
369
370 # select initial items
371 self.nb.SetSelection(0)
372 self.tree.SelectItem(root)
373
374 if len(sys.argv) == 2:
375 try:
376 selectedDemo = self.treeMap[sys.argv[1]]
377 except:
378 selectedDemo = None
379 if selectedDemo:
380 self.tree.SelectItem(selectedDemo)
381 self.tree.EnsureVisible(selectedDemo)
382
383
384 wxLogMessage('window handle: %s' % self.GetHandle())
385
386
387 #---------------------------------------------
388 def WriteText(self, text):
389 if text[-1:] == '\n':
390 text = text[:-1]
391 wxLogMessage(text)
392
393
394 def write(self, txt):
395 self.WriteText(txt)
396
397 #---------------------------------------------
398 def OnItemExpanded(self, event):
399 item = event.GetItem()
400 wxLogMessage("OnItemExpanded: %s" % self.tree.GetItemText(item))
401 event.Skip()
402
403 #---------------------------------------------
404 def OnItemCollapsed(self, event):
405 item = event.GetItem()
406 wxLogMessage("OnItemCollapsed: %s" % self.tree.GetItemText(item))
407 event.Skip()
408
409 #---------------------------------------------
410 def OnTreeLeftDown(self, event):
411 pt = event.GetPosition();
412 item, flags = self.tree.HitTest(pt)
413 if item == self.tree.GetSelection():
414 self.SetOverview(self.tree.GetItemText(item)+" Overview", self.curOverview)
415 event.Skip()
416
417 #---------------------------------------------
418 def OnSelChanged(self, event):
419 if self.dying:
420 return
421
422 item = event.GetItem()
423 itemText = self.tree.GetItemText(item)
424 self.RunDemo(itemText)
425
426
427 #---------------------------------------------
428 def RunDemo(self, itemText):
429 os.chdir(self.cwd)
430 if self.nb.GetPageCount() == 3:
431 if self.nb.GetSelection() == 2:
432 self.nb.SetSelection(0)
433 self.nb.DeletePage(2)
434
435 if itemText == self.overviewText:
436 self.GetDemoFile('Main.py')
437 self.SetOverview(self.overviewText, overview)
438 self.nb.Refresh();
439 self.window = None
440
441 else:
442 if os.path.exists(itemText + '.py'):
443 wxBeginBusyCursor()
444 wxLogMessage("Running demo %s.py..." % itemText)
445 try:
446 self.GetDemoFile(itemText + '.py')
447 module = __import__(itemText, globals())
448 self.SetOverview(itemText + " Overview", module.overview)
449 finally:
450 wxEndBusyCursor()
451
452 # in case runTest is modal, make sure things look right...
453 self.nb.Refresh();
454 wxYield()
455
456 self.window = module.runTest(self, self.nb, self) ###
457 if self.window:
458 self.nb.AddPage(self.window, 'Demo')
459 #wxYield() TODO: Is this still needed?
460 self.nb.SetSelection(2)
461 self.nb.Refresh() # without this wxMac has troubles showing the just added page
462
463 else:
464 self.ovr.SetPage("")
465 self.txt.Clear()
466 self.window = None
467
468
469
470 #---------------------------------------------
471 # Get the Demo files
472 def GetDemoFile(self, filename):
473 self.txt.Clear()
474 try:
475 self.txt.SetValue(open(filename).read())
476 except IOError:
477 self.txt.WriteText("Cannot open %s file." % filename)
478
479 self.txt.SetInsertionPoint(0)
480 self.txt.ShowPosition(0)
481
482 #---------------------------------------------
483 def SetOverview(self, name, text):
484 self.curOverview = text
485 lead = text[:6]
486 if lead != '<html>' and lead != '<HTML>':
487 text = string.join(string.split(text, '\n'), '<br>')
488 self.ovr.SetPage(text)
489 self.nb.SetPageText(0, name)
490
491 #---------------------------------------------
492 # Menu methods
493 def OnFileExit(self, *event):
494 self.Close()
495
496
497 def OnHelpAbout(self, event):
498 from About import MyAboutBox
499 about = MyAboutBox(self)
500 about.ShowModal()
501 about.Destroy()
502
503
504 #---------------------------------------------
505 def OnCloseWindow(self, event):
506 self.dying = true
507 self.window = None
508 self.mainmenu = None
509 if hasattr(self, "tbicon"):
510 del self.tbicon
511 self.Destroy()
512
513
514 #---------------------------------------------
515 def OnIdle(self, event):
516 if self.otherWin:
517 self.otherWin.Raise()
518 self.window = self.otherWin
519 self.otherWin = None
520
521 if self.showTip:
522 self.ShowTip()
523 self.showTip = false
524
525
526 #---------------------------------------------
527 def ShowTip(self):
528 try:
529 showTipText = open(opj("data/showTips")).read()
530 showTip, index = eval(showTipText)
531 except IOError:
532 showTip, index = (1, 0)
533 if showTip:
534 tp = wxCreateFileTipProvider(opj("data/tips.txt"), index)
535 showTip = wxShowTip(self, tp)
536 index = tp.GetCurrentTip()
537 open(opj("data/showTips"), "w").write(str( (showTip, index) ))
538
539
540 #---------------------------------------------
541 def OnDemoMenu(self, event):
542 try:
543 selectedDemo = self.treeMap[self.mainmenu.GetLabel(event.GetId())]
544 except:
545 selectedDemo = None
546 if selectedDemo:
547 self.tree.SelectItem(selectedDemo)
548 self.tree.EnsureVisible(selectedDemo)
549
550
551 #---------------------------------------------
552 def OnTaskBarActivate(self, evt):
553 if self.IsIconized():
554 self.Iconize(false)
555 if not self.IsShown():
556 self.Show(true)
557 self.Raise()
558
559 #---------------------------------------------
560
561 TBMENU_RESTORE = 1000
562 TBMENU_CLOSE = 1001
563
564 def OnTaskBarMenu(self, evt):
565 menu = wxMenu()
566 menu.Append(self.TBMENU_RESTORE, "Restore wxPython Demo")
567 menu.Append(self.TBMENU_CLOSE, "Close")
568 self.tbicon.PopupMenu(menu)
569 menu.Destroy()
570
571 #---------------------------------------------
572 def OnTaskBarClose(self, evt):
573 self.Close()
574
575 # because of the way wxTaskBarIcon.PopupMenu is implemented we have to
576 # prod the main idle handler a bit to get the window to actually close
577 wxGetApp().ProcessIdle()
578
579
580 #---------------------------------------------
581 def OnIconfiy(self, evt):
582 wxLogMessage("OnIconfiy")
583 evt.Skip()
584
585 #---------------------------------------------
586 def OnMaximize(self, evt):
587 wxLogMessage("OnMaximize")
588 evt.Skip()
589
590
591
592
593 #---------------------------------------------------------------------------
594 #---------------------------------------------------------------------------
595
596 class MySplashScreen(wxSplashScreen):
597 def __init__(self):
598 bmp = wxImage(opj("bitmaps/splash.gif")).ConvertToBitmap()
599 wxSplashScreen.__init__(self, bmp,
600 wxSPLASH_CENTRE_ON_SCREEN|wxSPLASH_TIMEOUT,
601 4000, None, -1)
602 EVT_CLOSE(self, self.OnClose)
603
604 def OnClose(self, evt):
605 frame = wxPythonDemo(None, -1, "wxPython: (A Demonstration)")
606 frame.Show(true)
607 evt.Skip() # Make sure the default handler runs too...
608
609
610 class MyApp(wxApp):
611 def OnInit(self):
612 """
613 Create and show the splash screen. It will then create and show
614 the main frame when it is time to do so.
615 """
616 wxInitAllImageHandlers()
617 splash = MySplashScreen()
618 splash.Show()
619 return true
620
621
622
623 #---------------------------------------------------------------------------
624
625 def main():
626 try:
627 demoPath = os.path.dirname(__file__)
628 os.chdir(demoPath)
629 except:
630 pass
631 app = MyApp(0)
632 app.MainLoop()
633
634
635 #---------------------------------------------------------------------------
636
637
638
639 overview = """<html><body>
640 <h2>Python</h2>
641
642 Python is an interpreted, interactive, object-oriented programming
643 language often compared to Tcl, Perl, Scheme, or Java.
644
645 <p> Python combines remarkable power with very clear syntax. It has
646 modules, classes, exceptions, very high level dynamic data types, and
647 dynamic typing. There are interfaces to many system calls and
648 libraries, and new built-in modules are easily written in C or
649 C++. Python is also usable as an extension language for applications
650 that need a programmable interface. <p>
651
652 <h2>wxWindows</h2>
653
654 wxWindows is a free C++ framework designed to make cross-platform
655 programming child's play. Well, almost. wxWindows 2 supports Windows
656 3.1/95/98/NT, Unix with GTK/Motif/Lesstif, with a Mac version
657 underway. Other ports are under consideration. <p>
658
659 wxWindows is a set of libraries that allows C++ applications to
660 compile and run on several different types of computers, with minimal
661 source code changes. There is one library per supported GUI (such as
662 Motif, or Windows). As well as providing a common API (Application
663 Programming Interface) for GUI functionality, it provides
664 functionality for accessing some commonly-used operating system
665 facilities, such as copying or deleting files. wxWindows is a
666 'framework' in the sense that it provides a lot of built-in
667 functionality, which the application can use or replace as required,
668 thus saving a great deal of coding effort. Basic data structures such
669 as strings, linked lists and hash tables are also supported.
670
671 <p>
672 <h2>wxPython</h2>
673
674 wxPython is a Python extension module that encapsulates the wxWindows
675 GUI classes. Currently it is only available for the Win32 and GTK
676 ports of wxWindows, but as soon as the other ports are brought up to
677 the same level as Win32 and GTK, it should be fairly trivial to
678 enable wxPython to be used with the new GUI.
679
680 <p>
681
682 The wxPython extension module attempts to mirror the class heiarchy
683 of wxWindows as closely as possible. This means that there is a
684 wxFrame class in wxPython that looks, smells, tastes and acts almost
685 the same as the wxFrame class in the C++ version. Unfortunately,
686 because of differences in the languages, wxPython doesn't match
687 wxWindows exactly, but the differences should be easy to absorb
688 because they are natural to Python. For example, some methods that
689 return multiple values via argument pointers in C++ will return a
690 tuple of values in Python.
691
692 <p>
693
694 There is still much to be done for wxPython, many classes still need
695 to be mirrored. Also, wxWindows is still somewhat of a moving target
696 so it is a bit of an effort just keeping wxPython up to date. On the
697 other hand, there are enough of the core classes completed that
698 useful applications can be written.
699
700 <p>
701
702 wxPython is close enough to the C++ version that the majority of
703 the wxPython documentation is actually just notes attached to the C++
704 documents that describe the places where wxPython is different. There
705 is also a series of sample programs included, and a series of
706 documentation pages that assist the programmer in getting started
707 with wxPython.
708
709 """
710
711
712 #----------------------------------------------------------------------------
713 #----------------------------------------------------------------------------
714
715 if __name__ == '__main__':
716 main()
717
718 #----------------------------------------------------------------------------
719
720
721
722
723
724
725