]> git.saurik.com Git - wxWidgets.git/commitdiff
Added docview modules from Peter Yared and Morgan Hua
authorRobin Dunn <robin@alldunn.com>
Fri, 25 Feb 2005 23:50:26 +0000 (23:50 +0000)
committerRobin Dunn <robin@alldunn.com>
Fri, 25 Feb 2005 23:50:26 +0000 (23:50 +0000)
git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@32374 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775

wxPython/docs/CHANGES.txt
wxPython/samples/docview/DocViewDemo.py [new file with mode: 0644]
wxPython/samples/docview/PyDocViewDemo.py [new file with mode: 0644]
wxPython/samples/docview/activegrid/__init__.py [new file with mode: 0644]
wxPython/samples/docview/activegrid/tool/FindService.py [new file with mode: 0644]
wxPython/samples/docview/activegrid/tool/TextEditor.py [new file with mode: 0644]
wxPython/samples/docview/activegrid/tool/__init__.py [new file with mode: 0644]
wxPython/samples/docview/activegrid/tool/data/tips.txt [new file with mode: 0644]
wxPython/samples/docview/activegrid/tool/images/splash.jpg [new file with mode: 0644]
wxPython/wx/lib/docview.py [new file with mode: 0644]
wxPython/wx/lib/pydocview.py [new file with mode: 0644]

index 65a889e69daac50bac0928ab3102a03c2fabd69b..5926b209654b9697b4a264dc5e40ff884d9be2db 100644 (file)
@@ -232,6 +232,11 @@ controls.
 wxMSW:  "Alt" key (VK_MENU) now results in WXK_ALT keyboard event, not
 WXK_MENU
 
+Added modules from Peter Yared and Morgan Hua that implement the wx
+Doc/View framework in pure Python code.  See wx.lib.docview for the
+base implementation and wx.lib.pydocview for Python-specific
+extensions.  There are also a couple sample applications located in
+samples/docview. 
 
 
 
diff --git a/wxPython/samples/docview/DocViewDemo.py b/wxPython/samples/docview/DocViewDemo.py
new file mode 100644 (file)
index 0000000..55eb2a1
--- /dev/null
@@ -0,0 +1,323 @@
+#----------------------------------------------------------------------------
+# Name:         DocViewDemo.py
+# Purpose:      Port of the wxWindows docview sample classes
+#
+# Author:       Peter Yared
+#
+# Created:      8/1/03
+# CVS-ID:       $Id$
+# Copyright:    (c) 2003, 2004 ActiveGrid, Inc. (Port of wxWindows classes by Julian Smart et al)
+# License:      wxWindows license
+#----------------------------------------------------------------------------
+
+
+
+#----------------------------------------------------------------------
+# This isn't the most object oriented code (it is somewhat repetitive,
+# but it is true to the wxWindows C++ demos.
+#----------------------------------------------------------------------
+
+
+import wx
+import wx.lib.docview
+_ = wx.GetTranslation
+
+
+#----------------------------------------------------------------------
+#----------------------------------------------------------------------
+# TextEdit document and view classes
+
+class TextEditDocument(wx.lib.docview.Document):
+
+
+    def OnSaveDocument(self, filename):
+        view = self.GetFirstView()
+        if not view.GetTextSW().SaveFile(filename):
+            return False
+        self.Modify(False)
+        self.SetDocumentSaved(True)
+##        if wx.Platform == "__WXMAC__":
+##            fn = wx.Filename(filename)
+##            fn.MacSetDefaultTypeAndCreator()
+        return True
+
+
+    def OnOpenDocument(self, filename):
+        view = self.GetFirstView()
+        if not view.GetTextSW().LoadFile(filename):
+            return False
+        self.SetFilename(filename, True)
+        self.Modify(False)
+        self.UpdateAllViews()
+        self._savedYet = True
+        return True
+
+
+    def IsModified(self):
+        view = self.GetFirstView()
+        if view:
+            return wx.lib.docview.Document.IsModified(self) or (view.GetTextSW() and view.GetTextSW().IsModified())
+        else:
+            return wx.lib.docview.Document.IsModified(self)
+
+
+    def Modify(self, mod):
+        view = self.GetFirstView()
+        wx.lib.docview.Document.Modify(self, mod)
+        if not mod and view and view.GetTextSW():
+            view.GetTextSW().DiscardEdits()
+
+
+class TextEditView(wx.lib.docview.View):
+
+
+    def OnCreate(self, doc, flags):
+        flags = doc.GetDocumentManager().GetFlags()
+        if flags & wx.lib.docview.DOC_SDI and doc.GetDocumentManager().GetMaxDocsOpen() == 1:
+            self._frame = wx.GetApp().GetMainFrame()
+            self.SetFrame(self._frame)
+            sizer = wx.BoxSizer()
+            self._textsw = MyTextWindow(self, self._frame, wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE)
+            sizer.Add(self._textsw, 1, wx.EXPAND, 0)
+            self._frame.SetSizer(sizer)
+            self._frame.Layout()
+            self.Activate(True)
+            return True
+        elif flags & wx.lib.docview.DOC_MDI:
+            self._frame = wx.lib.docview.DocMDIChildFrame(doc, self, wx.GetApp().GetMainFrame(), -1, wx.GetApp().GetAppName(), (10, 10), (300, 300), wx.DEFAULT_FRAME_STYLE)
+            self.SetFrame(self._frame)
+            sizer = wx.BoxSizer()
+            self._textsw = MyTextWindow(self, self._frame, wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE)
+            sizer.Add(self._textsw, 1, wx.EXPAND, 0)
+            self._frame.SetSizer(sizer)
+            self._frame.Layout()
+            self.Activate(True)
+            return True
+        else:  # flags & wx.lib.docview.DOC_SDI
+            self._frame = wx.GetApp().CreateChildFrame(doc, self)
+            width, height = self._frame.GetClientSize()
+            self._textsw = MyTextWindow(self, self._frame, (0, 0), (width, height), wx.TE_MULTILINE)
+            self._frame.SetTitle(_("TextEditView"))
+            self._frame.Show(True)
+            self.Activate(True)
+            return True
+
+
+    # Since ProcessEvent is not virtual, we have to trap the relevant events using this pseudo-ProcessEvent instead of EVT_MENU
+    def ProcessEvent(self, event):
+        id = event.GetId()
+        if id == wx.ID_UNDO:
+            self._textsw.Undo()
+            return True
+        elif id == wx.ID_REDO:
+            self._textsw.Redo()
+            return True
+        else:
+            return wx.lib.docview.View.ProcessEvent(self, event)
+
+
+    def GetTextSW(self):
+        return self._textsw
+
+
+    def OnDraw(self, dc):
+        pass
+
+
+    def OnClose(self, deleteWindow = True):
+        if not self.GetDocument().Close():
+            return False
+        self.Activate(False)
+        if deleteWindow:
+            if self.GetDocument().GetDocumentManager().GetMaxDocsOpen() == 1 and self.GetDocument().GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI:
+                if self._textsw:
+                    self._textsw.Destroy()
+                return True
+            else:
+                self._frame.Destroy()
+                return True
+        return True
+
+
+class MyTextWindow(wx.TextCtrl):
+
+
+    def __init__(self, view, frame, pos, size, style):
+        wx.TextCtrl.__init__(self, frame, -1, "", pos, size, style)
+        self._view = view
+
+
+
+#----------------------------------------------------------------------
+#----------------------------------------------------------------------
+# TextEdit Sample Application
+
+
+class MyApp(wx.PySimpleApp):
+
+
+    def OnInit(self):
+
+
+        demoMode = wx.GetSingleChoiceIndex(_("Select the demo mode"),
+                                           _("wxPython DocView Demo"),
+                                           [_("SDI Single Document"), _("SDI"), _("MDI")])
+
+        if demoMode == 0 or demoMode == 1:
+            flags = wx.lib.docview.DOC_SDI
+        elif demoMode == 2:
+            flags = wx.lib.docview.DOC_MDI
+        else:
+            return False
+
+        self.SetAppName(_("DocView Demo"))
+
+        docManager = wx.lib.docview.DocManager(flags = flags)
+        docManager.AssociateTemplate(wx.lib.docview.DocTemplate(docManager,
+                                                         _("Text"),
+                                                         "*.text;*.txt",
+                                                         _("Text"),
+                                                         _(".txt"),
+                                                         _("Text Document"),
+                                                         _("Text View"),
+                                                         TextEditDocument,
+                                                         TextEditView))
+        #if wx.Platform == "__WXMAC__":
+        #     wx.FileName.MacRegisterDefaultTypeAndCreator("txt", 'TEXT', 'WXMA')
+
+        if demoMode == 0:
+            docManager.SetMaxDocsOpen(1)
+
+        if demoMode == 2:  # MDI
+            self._frame = MyMDIFrame(docManager, None, -1, _("DocView Demo"), (0, 0), (500, 400), wx.DEFAULT_FRAME_STYLE)
+        else:  # SDI
+            self._frame = MyFrame(docManager, None, -1, _("DocView Demo"), (0, 0), (500, 400), wx.DEFAULT_FRAME_STYLE)
+
+        fileMenu = wx.Menu()
+        editMenu = None
+
+        fileMenu.Append(wx.ID_NEW, _("&New..."))
+        fileMenu.Append(wx.ID_OPEN, _("&Open..."))
+
+        if demoMode == 2:  # MDI
+            fileMenu.Append(wx.ID_CLOSE, _("&Close"))
+            fileMenu.AppendSeparator()
+
+        if demoMode == 0 or demoMode == 2:  # Single Doc or MDI
+            fileMenu.Append(wx.ID_SAVE, _("&Save"))
+            fileMenu.Append(wx.ID_SAVEAS, _("Save &As"))
+            fileMenu.AppendSeparator()
+            fileMenu.Append(wx.ID_PRINT, _("&Print"))
+            fileMenu.Append(wx.ID_PRINT_SETUP, _("Page &Setup"))
+            fileMenu.Append(wx.ID_PREVIEW, _("Print Pre&view"))
+
+            editMenu = wx.Menu()
+            editMenu.Append(wx.ID_UNDO, _("&Undo"))
+            editMenu.Append(wx.ID_REDO, _("&Redo"))
+
+            self._frame.editMenu = editMenu
+
+        fileMenu.AppendSeparator()
+        fileMenu.Append(wx.ID_EXIT, _("E&xit"))
+
+        docManager.FileHistoryUseMenu(fileMenu)
+
+        helpMenu = wx.Menu()
+        helpMenu.Append(wx.ID_ABOUT, _("&About"))
+
+        menuBar = wx.MenuBar()
+        menuBar.Append(fileMenu, _("&File"))
+        if editMenu:
+            menuBar.Append(editMenu, _("&Edit"))
+        menuBar.Append(helpMenu, _("&Help"))
+
+        self._frame.SetMenuBar(menuBar)
+        self._frame.Centre(wx.BOTH)
+        self._frame.Show(True)
+
+        self.SetTopWindow(self._frame)
+
+        if demoMode == 0:  # Single doc
+            docManager.OnFileNew(None)
+
+        return True
+
+
+    def GetMainFrame(self):
+        return self._frame
+
+
+    def GetDemoMode(self):
+        return self._demoMode
+
+
+    def CreateChildFrame(self, doc, view):
+        subframe = wx.lib.docview.DocChildFrame(doc, view, self.GetMainFrame(), -1, wx.GetApp().GetAppName(), (10, 10), (300, 300), wx.DEFAULT_FRAME_STYLE)
+
+        fileMenu = wx.Menu()
+        fileMenu.Append(wx.ID_NEW, _("&New"))
+        fileMenu.Append(wx.ID_OPEN, _("&Open"))
+        fileMenu.Append(wx.ID_CLOSE, _("&Close"))
+        fileMenu.AppendSeparator()
+        fileMenu.Append(wx.ID_SAVE, _("&Save"))
+        fileMenu.Append(wx.ID_SAVEAS, _("Save &As"))
+        fileMenu.AppendSeparator()
+        fileMenu.Append(wx.ID_PRINT, _("&Print"))
+        fileMenu.Append(wx.ID_PRINT_SETUP, _("Page &Setup"))
+        fileMenu.Append(wx.ID_PREVIEW, _("Print Pre&view"))
+
+        editMenu = wx.Menu()
+        editMenu.Append(wx.ID_UNDO, _("&Undo"))
+        editMenu.Append(wx.ID_REDO, _("&Redo"))
+
+        helpMenu = wx.Menu()
+        helpMenu.Append(wx.ID_ABOUT, _("&About"))
+
+        menuBar = wx.MenuBar()
+
+        menuBar.Append(fileMenu, _("&File"))
+        menuBar.Append(editMenu, _("&Edit"))
+        menuBar.Append(helpMenu, _("&Help"))
+
+        subframe.SetMenuBar(menuBar)
+        subframe.Centre(wx.BOTH)
+        return subframe
+
+
+class MyFrame(wx.lib.docview.DocParentFrame):
+
+
+    def __init__(self, manager, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"):
+        wx.lib.docview.DocParentFrame.__init__(self, manager, frame, id, title, pos, size, style, name)
+        self._frame = frame
+        wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
+
+
+    def OnAbout(self, event):
+        wx.MessageBox(wx.GetApp().GetAppName(), _("About DocView"))
+
+
+    def GetMainFrame(self):
+        return self._frame
+
+
+class MyMDIFrame(wx.lib.docview.DocMDIParentFrame):
+
+    def __init__(self, manager, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"):
+        wx.lib.docview.DocMDIParentFrame.__init__(self, manager, frame, id, title, pos, size, style, name)
+        self._frame = frame
+        wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
+
+
+    def OnAbout(self, event):
+        wx.MessageBox(wx.GetApp().GetAppName(), _("About DocView"))
+
+
+    def GetMainFrame(self):
+        return self._frame
+
+
+app = MyApp()
+app.MainLoop()
+
+
diff --git a/wxPython/samples/docview/PyDocViewDemo.py b/wxPython/samples/docview/PyDocViewDemo.py
new file mode 100644 (file)
index 0000000..92bb8d4
--- /dev/null
@@ -0,0 +1,168 @@
+#----------------------------------------------------------------------------
+# Name:         PyDocViewDemo.py
+# Purpose:      Demo of Python extensions to the wxWindows docview framework
+#
+# Author:       Peter Yared, Morgan Hua
+#
+# Created:      5/15/03
+# CVS-ID:       $Id$
+# Copyright:    (c) 2003 ActiveGrid, Inc.
+# License:      wxWindows license
+#----------------------------------------------------------------------------
+
+
+import sys
+import wx
+import wx.lib.docview
+import wx.lib.pydocview
+import activegrid.tool.TextEditor as TextEditor
+import activegrid.tool.FindService as FindService
+import wx.lib.pydocview as WindowMenuService
+
+#----------------------------------------------------------------------------
+# Classes
+#----------------------------------------------------------------------------
+
+class TextEditorApplication(wx.lib.pydocview.DocApp):
+
+
+    def OnInit(self):
+        wx.lib.pydocview.DocApp.OnInit(self)
+
+        wx.lib.pydocview.DocApp.ShowSplash(self, "activegrid/tool/images/splash.jpg")
+
+        self.SetAppName(wx.GetTranslation("wxPython DocView Demo"))
+        config = wx.Config(self.GetAppName(), style = wx.CONFIG_USE_LOCAL_FILE)
+
+        docManager = wx.lib.docview.DocManager(flags = self.GetDefaultDocManagerFlags())
+        self.SetDocumentManager(docManager)
+
+        textTemplate = wx.lib.docview.DocTemplate(docManager,
+                                              wx.GetTranslation("Text"),
+                                              "*.text;*.txt",
+                                              wx.GetTranslation("Text"),
+                                              wx.GetTranslation(".txt"),
+                                              wx.GetTranslation("Text Document"),
+                                              wx.GetTranslation("Text View"),
+                                              TextEditor.TextDocument,
+                                              TextEditor.TextView)
+        docManager.AssociateTemplate(textTemplate)
+
+        textService       = self.InstallService(TextEditor.TextService())
+        findService       = self.InstallService(FindService.FindService())
+        optionsService    = self.InstallService(wx.lib.pydocview.DocOptionsService())
+        windowMenuService = self.InstallService(WindowMenuService.WindowMenuService())
+        optionsService.AddOptionsPanel(TextEditor.TextOptionsPanel)
+        filePropertiesService = self.InstallService(wx.lib.pydocview.FilePropertiesService())
+
+        self.SetDefaultIcon(getDocIcon())
+
+        if docManager.GetFlags() & wx.lib.docview.DOC_MDI:
+            frame = wx.lib.pydocview.DocMDIParentFrame(docManager, None, -1, wx.GetApp().GetAppName())
+            frame.Show(True)
+
+        wx.lib.pydocview.DocApp.CloseSplash(self)
+        
+        self.OpenCommandLineArgs()
+
+        if not docManager.GetDocuments() and docManager.GetFlags() & wx.lib.docview.DOC_SDI:
+            textTemplate.CreateDocument('', wx.lib.docview.DOC_NEW).OnNewDocument()
+
+        wx.CallAfter(self.ShowTip, docManager.FindSuitableParent(), wx.CreateFileTipProvider("activegrid/tool/data/tips.txt", 0))
+
+        return True
+
+
+#----------------------------------------------------------------------------
+# Menu Bitmaps - generated by encode_bitmaps.py
+#----------------------------------------------------------------------------
+from wx import ImageFromStream, BitmapFromImage
+from wx import EmptyIcon
+import cStringIO
+
+
+def getDocData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00 \x08\x06\x00\
+\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\x05cID\
+ATX\x85\xed\x97\xcbo\x1b\xd7\x15\xc6\x7fw^\x1c\x92C\x8a\xa4DQ\xa2)\xd9\xb2%?\
+\xe0\xa7\x82\xc0\x85\x83"\xa8\x1b\x17AwYtQtU\xb4\x8b\xa2\x7fH\xfe\x8c\xee\
+\x8b\xac\x124\xab\x02E\n\x17h\x01\x17\x86Q7\xaac7~I\xb2hZ\xe2sH\xce\x83s\xef\
+\xedB\xa6dI~))\x90E\xf2\x01\x17\x98\xb9s\xe7\x9c\xef\x9c\xf9\xce\xb9w\x840L\
+\xbeK\x18\xdf\xa9\xf7\x1f\x08\x00\xa2\xd5ji!\x04\xe3\xf1ma\x9a\x02!\x0c\xe0\
+\xa0-\xa55O\xb6\x06t\xfb\x11\xa0\x98\xca\x99\x880\x0c5\xf0R\xe7B\x08\xb4\xde\
+\xbd6\xc4\xd8\xee\x0bk\xb5\xde3\'\x84f\x10J\x06aB4R\xd8\x96\xc1\x97\x8f{\xfc\
+\xfbq\x97-?\xa2\xe49\x9c\x9d\xf38u\xc4\xa3\x945\xb0\xc6\x8e\r!`\x1f\t!\xd8C\
+\x004\x89\xd4\x04\xb1$\x88%#\xa9(f,\xd6\xdb!\xab\x9b\x01\x9b\xbd\x98 \x96\
+\xb4z\x11\xa6\x80\xea\x94K\x9ch\xfe\xf5\xa0\xcb\xfa\xd6\x90\xea\xa4\xcb\x99Z\
+\x8e\xead\x96\xa2\x97\xc2\x14\t\xd6s\xf3h\x04JC"\xf5\xf3\xa1\x00M.c\xd1\xe9\
+\'\xf4\x82\x11\xc3H\xd2\x0f\x13\xda~L\xcb\x8fI\x12\xc9\x953\x93\\\xff\xaa\
+\xc9\x17\xb7\xb7\xf8j\xdd\xa7\x13J\x82aB\xad\x94\xe2\x83\xe5)\xba\xc3\x84\
+\xde a\xa6\x98\xe2\xc3wf\xb8\xbcX\xa2\xe89(\xa5\x08\x82\xd1\x98\x00\x04qB/\
+\x1c\xd1\xf6Gl\xf6"\x9euc\x84\xd0\xfc\xf4\\\x99Oo\xd4\xf9\xe2\xf6\x16w\x9f\
+\x0chG\t\xbe\x1f\x13\xf9#\xa63\x16\x1f\xff\xee\x027\xefw\xb9\xf5\xb0K\xc7\
+\x8f\x11\xa6`a\xc6\xe5\xdc\xbc\xc7\xfcT\x06/msa~\x82\xa5\xd9\x1c\x8em`\x08\
+\xd0Z\xa1\x94\x02\xc0\xb2,\x8b\x8d\xe6\x90\xcfnl\xf0\xf9\xcd\x06\xf1H\x13E\
+\x92h0\xa2\x906\xe9\x0eF\xf4#I<\x88\xb9w\xa7I\x9cs\xc8\xa5-\xcae\x97\xa3\x93\
+i\xdc\x94\xa0\xe4\xd9\x143\x16\xfd~\xc4\xf4D\x8ak\x17\xa6\xb9z\xae\xcc\xd1r\
+\x06\xc76)dm\xb2)\x03\xa5\xf7jLk\xb0\xc6\x9f~\xbd\x19r}\xa5\xc9\xb0\x9fl?\
+\x1d)&2\x16n\xe9\x19?_.sf>\xcf\xbd\xc7>x6\xaeka\n0S&~\x980\x88\x12l[\xb08\
+\x9b\xe1\xda\xa5\nW\xcfW8;\x9f\'\xefZ;\x02\xd5Z\xa3\xb5~\xae\xa5\xdd\xaa\xb3\
+\x94R\x94<\x87\xc5\xaa\xc7\xe9#9V\xee\xb61\x1d\x13\xc7\xb3I\xa7L\xfe[\x1f\
+\xf0\xd1\xe5\x19\x96O\x97\x08\x84\xa6\xd1\x0c\xe9\r\x136\xfd\x98F7f\xbd\x19Q\
+\xefD\xa4]\x93\xf7O\x95\xf9\xed\xb5\x05\xa6\x0bi\xd0\xa0\xb5\x06\xa5w\x8a\
+\xe6\xc5J\x13B`Y\x16\x96\x94\n\xc76\xf9\xd9\xc5il\x03>\x1e\xc6\x94\x8b.\xc7g\
+2\xcc\x16]\xc2(a\xbd\x19\xa2\xd0,U\xb2\xfc\xf1\xcf\xab\xb4\xba#\xd2\x9eM\xed\
+H\x96 N\xa8\xe4m~\xb4X\xe47W\x8f\x92\xcf\xd8\xe8\xfd\xb9~\x05l\xdb\xde\x16\
+\xa1R\x8a\xa9\xbc\xc3\xd5\xf3\x15\x8a\x9e\xc3\xadG\x1dV\xd6|\xfe\xfa\xe5\x16\
+\x83@"\xa4f\xf9D\x9eKKE\xe6k9\xaa\x15I\xca1\xc9y\x16\xbd0ay\xa1\xc0\xf2B\x91\
+B\xd6\xd9\x8ez\x7f-\xbf\x04\xe3lX\xdb\xcdF\xe3\x98\x06\xd5\x92Kmj\x96l\xc6\
+\xa4\xd1\x89\xf8\xc7\x9d6O\x9e\x05\xa8 \xc1\x16P\x9b\xcd\xf2\xd1{U\xfe\xb3\
+\xda\xe5\xd1\xd3!A?\xa1\x92Oq\xf1X\x81\x93\xd5\xdc[E\xbd\x1f;e8f\xae\xb5\xe0\
+lm\x82\xa7\xa7c\xd67CB\x7fD\xa4!\x1a):\xc3\x84_\xfd\xf8\x08\x1b\xad!\x8f\x1a\
+CD\xa4x\xf7x\x81\xc5\x19\x8fl\xcaDJu\xe8v.\xe28\xd6cu\x8e\xb3\xa1\x81`\xa4y\
+\xd8\x18\xf0\xc9\xdf\xd6ht\x02\x0c\xd3`\xc2\xb3\t\xa5\xa2\xde\x8eX\xdb\n0\
+\x81?\xfc\xfe"\x8b3y,\xcb\xf8F\x04,8\xb8\x0f\x18B\xe0\xa5\x04K\xb3Y~\xf9\xfe\
+\x1c\xc3(\xe1\xc6\xd7m>\xffg\x9d\x87\xf7{,\x1d\xcfsr6K\xde5\x01\x81T\x1a\xeb\
+%v\xde\x9a\xc0\x9e\x94<7\xa2\xb5&e\x19\x9c\x9d\xcbo\xef\th\xee\xac\xf6xp\xb7\
+\x8b\x1f\x8c\xa8\x98i\xe6\xa6\\6\xfd\x98\xf2\xc4\xb6(w\xeb\xfc[\x10x\x81\xca\
+\x9e\xe6qy\xb1Dm2\x83e\x18\xdcZ\xed\xd2\xe8\x84,L\xbb\xdc\xaf\x0f\xa8\x163L\
+\xe6R\x87\x0b}\xec%\x8e\xe3\x9d\xba\xd9\xcf~,\xcc\xf1\xbc\xd2\xb0\xd9\r\xb8\
+\xf9\xa0\xc3\xdf\xef5Yy\xd2\xe7|-\xc7/\xae\xd4\xb8t\xac\x88\x94\xf2\xff\x99\
+\x81\x83\x84L\x01\xd5R\x1a\xcb2\t\x13\xcd\xd7\x8d!\xd7\xef\xb4x\xf7D\x89ss\
+\x13\x98\xc6\xee\xf9\xe1M\xd0Z\x93$\xc9\xe1\x8edZk\x94\x86r>\xc5\x85\xa3\x05\
+\xde;9\x89\xd2\xb0\xb2\xd6\xe3\xee\x86\x8fa\x18\xe3\x85oM\xe0\xb5\x198\x00!P\
+J\x03\x9a\xc5J\x86_\xff\xe4\x18\x00\xb7\x1ev\xf8\xd3\xcd\xa7,\xcd\xe6\xb0\
+\x0e\x11\x92R\xea\xf5\x1ax\x15\xf3\x9dk\xa0\xd9O\xf8\xcb\xed\x06\x1b\xed\x80\
+\x13\x95,\x1f\x9c\x9f\xc6s\xdf\x1c\xd7\xf6\x81$\xc08\xd0\xbb\xdf\x80=;\x1a0\
+\x9dw\xb8rj\x92w\x16\nH\xa9h\xf9\x11\xe1H\x1e \xfb*[\x96\x94r\xe7\xe6\xb0\n\
+\xd6Z\xa3\x94b\xae\x94"\x97\x12<\xde2\x08\xa2\x98 2\xb0\r\xe7\xb5}AJ\xb9]5\
+\xf5z]\x03\xbb\x02\xfa\x06\x10\x80m\x1b\x18\xa6\xc9\xda3\x1f\xd71\xc9\xb9\
+\xf6k\xdf\x91R\x12E\x11\xe2\x87\x7f\xc3\xef=\x81\xff\x01\x1d\xae\x83\xc3q\
+\xb9\xc6\x9f\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+
+
+def getDocBitmap():
+    return BitmapFromImage(getDocImage())
+
+
+def getDocImage():
+    stream = cStringIO.StringIO(getDocData())
+    return ImageFromStream(stream)
+
+
+def getDocIcon():
+    icon = EmptyIcon()
+    icon.CopyFromBitmap(getDocBitmap())
+    return icon
+
+
+#----------------------------------------------------------------------------
+# Main
+#----------------------------------------------------------------------------
+
+sys.stdout = sys.stderr
+
+app = TextEditorApplication(redirect = False)
+app.MainLoop()
diff --git a/wxPython/samples/docview/activegrid/__init__.py b/wxPython/samples/docview/activegrid/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/wxPython/samples/docview/activegrid/tool/FindService.py b/wxPython/samples/docview/activegrid/tool/FindService.py
new file mode 100644 (file)
index 0000000..4606a67
--- /dev/null
@@ -0,0 +1,521 @@
+#----------------------------------------------------------------------------
+# Name:         FindService.py
+# Purpose:      Find Service for pydocview
+#
+# Author:       Peter Yared, Morgan Hua
+#
+# Created:      8/15/03
+# CVS-ID:       $Id$
+# Copyright:    (c) 2003-2004 ActiveGrid, Inc.
+# License:      wxWindows license
+#----------------------------------------------------------------------------
+
+import wx
+import wx.lib.docview
+import wx.lib.pydocview
+import re
+_ = wx.GetTranslation
+
+
+#----------------------------------------------------------------------------
+# Constants
+#----------------------------------------------------------------------------
+FIND_MATCHPATTERN = "FindMatchPattern"
+FIND_MATCHREPLACE = "FindMatchReplace"
+FIND_MATCHCASE = "FindMatchCase"
+FIND_MATCHWHOLEWORD = "FindMatchWholeWordOnly"
+FIND_MATCHREGEXPR = "FindMatchRegularExpr"
+FIND_MATCHWRAP = "FindMatchWrap"
+FIND_MATCHUPDOWN = "FindMatchUpDown"
+
+FIND_SYNTAXERROR = -2
+
+SPACE = 10
+HALF_SPACE = 5
+
+
+#----------------------------------------------------------------------------
+# Classes
+#----------------------------------------------------------------------------
+
+class FindService(wx.lib.pydocview.DocService):
+
+    #----------------------------------------------------------------------------
+    # Constants
+    #----------------------------------------------------------------------------
+    FIND_ID = wx.NewId()            # for bringing up Find dialog box
+    FINDONE_ID = wx.NewId()         # for doing Find
+    FIND_PREVIOUS_ID = wx.NewId()   # for doing Find Next
+    FIND_NEXT_ID = wx.NewId()       # for doing Find Prev
+    REPLACE_ID = wx.NewId()         # for bringing up Replace dialog box
+    REPLACEONE_ID = wx.NewId()      # for doing a Replace
+    REPLACEALL_ID = wx.NewId()      # for doing Replace All
+    GOTO_LINE_ID = wx.NewId()       # for bringing up Goto dialog box
+
+    # Extending bitmasks: wx.FR_WHOLEWORD, wx.FR_MATCHCASE, and wx.FR_DOWN
+    FR_REGEXP = max([wx.FR_WHOLEWORD, wx.FR_MATCHCASE, wx.FR_DOWN]) << 1
+    FR_WRAP = FR_REGEXP << 1
+
+
+    def __init__(self):
+        self._replaceDialog = None
+        self._findDialog = None
+        self._findReplaceData = wx.FindReplaceData()
+        self._findReplaceData.SetFlags(wx.FR_DOWN)
+
+
+    def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
+        """ Install Find Service Menu Items """
+        editMenu = menuBar.GetMenu(menuBar.FindMenu(_("&Edit")))
+        editMenu.AppendSeparator()
+        editMenu.Append(FindService.FIND_ID, _("&Find...\tCtrl+F"), _("Finds the specified text"))
+        wx.EVT_MENU(frame, FindService.FIND_ID, frame.ProcessEvent)
+        wx.EVT_UPDATE_UI(frame, FindService.FIND_ID, frame.ProcessUpdateUIEvent)
+        editMenu.Append(FindService.FIND_PREVIOUS_ID, _("Find &Previous\tShift+F3"), _("Finds the specified text"))
+        wx.EVT_MENU(frame, FindService.FIND_PREVIOUS_ID, frame.ProcessEvent)
+        wx.EVT_UPDATE_UI(frame, FindService.FIND_PREVIOUS_ID, frame.ProcessUpdateUIEvent)
+        editMenu.Append(FindService.FIND_NEXT_ID, _("Find &Next\tF3"), _("Finds the specified text"))
+        wx.EVT_MENU(frame, FindService.FIND_NEXT_ID, frame.ProcessEvent)
+        wx.EVT_UPDATE_UI(frame, FindService.FIND_NEXT_ID, frame.ProcessUpdateUIEvent)
+        editMenu.Append(FindService.REPLACE_ID, _("R&eplace...\tCtrl+H"), _("Replaces specific text with different text"))
+        wx.EVT_MENU(frame, FindService.REPLACE_ID, frame.ProcessEvent)
+        wx.EVT_UPDATE_UI(frame, FindService.REPLACE_ID, frame.ProcessUpdateUIEvent)
+        editMenu.Append(FindService.GOTO_LINE_ID, _("&Go to Line...\tCtrl+G"), _("Goes to a certain line in the file"))
+        wx.EVT_MENU(frame, FindService.GOTO_LINE_ID, frame.ProcessEvent)
+        wx.EVT_UPDATE_UI(frame, FindService.GOTO_LINE_ID, frame.ProcessUpdateUIEvent)
+
+        # wxBug: wxToolBar::GetToolPos doesn't exist, need it to find cut tool and then insert find in front of it.
+        toolBar.InsertTool(6, FindService.FIND_ID, getFindBitmap(), shortHelpString = _("Find"), longHelpString = _("Finds the specified text"))
+        toolBar.InsertSeparator(6)
+        toolBar.Realize()
+
+        frame.Bind(wx.EVT_FIND, frame.ProcessEvent)
+        frame.Bind(wx.EVT_FIND_NEXT, frame.ProcessEvent)
+        frame.Bind(wx.EVT_FIND_REPLACE, frame.ProcessEvent)
+        frame.Bind(wx.EVT_FIND_REPLACE_ALL, frame.ProcessEvent)
+
+
+    def ProcessUpdateUIEvent(self, event):
+        id = event.GetId()
+        if id == FindService.FIND_ID:
+            event.Enable(False)
+            return True
+        elif id == FindService.FIND_PREVIOUS_ID:
+            event.Enable(False)
+            return True
+        elif id == FindService.FIND_NEXT_ID:
+            event.Enable(False)
+            return True
+        elif id == FindService.REPLACE_ID:
+            event.Enable(False)
+            return True
+        elif id == FindService.GOTO_LINE_ID:
+            event.Enable(False)
+            return True
+        else:
+            return False
+
+
+    def ShowFindReplaceDialog(self, findString="", replace = False):
+        """ Display find/replace dialog box.
+        
+            Parameters: findString is the default value shown in the find/replace dialog input field.
+            If replace is True, the replace dialog box is shown, otherwise only the find dialog box is shown. 
+        """
+        if replace:
+            if self._findDialog != None:
+                # No reason to have both find and replace dialogs up at the same time
+                self._findDialog.DoClose()
+                self._findDialog = None
+
+            self._replaceDialog = FindReplaceDialog(self.GetDocumentManager().FindSuitableParent(), -1, _("Replace"), size=(320,200), findString=findString)
+            self._replaceDialog.Show(True)
+        else:
+            if self._replaceDialog != None:
+                # No reason to have both find and replace dialogs up at the same time
+                self._replaceDialog.DoClose()
+                self._replaceDialog = None
+
+            self._findDialog = FindDialog(self.GetDocumentManager().FindSuitableParent(), -1, _("Find"), size=(320,200), findString=findString)
+            self._findDialog.Show(True)
+
+
+
+    def OnFindClose(self, event):
+        """ Cleanup handles when find/replace dialog is closed """
+        if self._findDialog != None:
+            self._findDialog = None
+        elif self._replaceDialog != None:
+            self._replaceDialog = None
+
+
+    def GetCurrentDialog(self):
+        """ return handle to either the find or replace dialog """
+        if self._findDialog != None:
+            return self._findDialog
+        return self._replaceDialog
+
+
+    def GetLineNumber(self, parent):
+        """ Display Goto Line Number dialog box """
+        line = -1
+        dialog = wx.TextEntryDialog(parent, _("Enter line number to go to:"), _("Go to Line"))
+        if dialog.ShowModal() == wx.ID_OK:
+            try:
+                line = int(dialog.GetValue())
+                if line > 65535:
+                    line = 65535
+            except:
+                pass
+        dialog.Destroy()
+        # This one is ugly:  wx.GetNumberFromUser("", _("Enter line number to go to:"), _("Go to Line"), 1, min = 1, max = 65535, parent = parent)
+        return line
+
+
+    def DoFind(self, findString, replaceString, text, startLoc, endLoc, down, matchCase, wholeWord, regExpr = False, replace = False, replaceAll = False, wrap = False):
+        """ Do the actual work of the find/replace.
+        
+            Returns the tuple (count, start, end, newText).
+            count = number of string replacements
+            start = start position of found string
+            end = end position of found string
+            newText = new replaced text 
+        """
+        flags = 0
+        if regExpr:
+            pattern = findString
+        else:
+            pattern = re.escape(findString)  # Treat the strings as a literal string
+        if not matchCase:
+            flags = re.IGNORECASE
+        if wholeWord:
+            pattern = r"\b%s\b" % pattern
+            
+        try:
+            reg = re.compile(pattern, flags)
+        except:
+            # syntax error of some sort
+            import sys
+            msgTitle = wx.GetApp().GetAppName()
+            if not msgTitle:
+                msgTitle = _("Regular Expression Search")
+            wx.MessageBox(_("Invalid regular expression \"%s\". %s") % (pattern, sys.exc_value),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          self.GetView())
+            return FIND_SYNTAXERROR, None, None, None
+
+        if replaceAll:
+            newText, count = reg.subn(replaceString, text)
+            if count == 0:
+                return -1, None, None, None
+            else:
+                return count, None, None, newText
+
+        start = -1
+        if down:
+            match = reg.search(text, endLoc)
+            if match == None:
+                if wrap:  # try again, but this time from top of file
+                    match = reg.search(text, 0)
+                    if match == None:
+                        return -1, None, None, None
+                else:
+                    return -1, None, None, None
+            start = match.start()
+            end = match.end()
+        else:
+            match = reg.search(text)
+            if match == None:
+                return -1, None, None, None
+            found = None
+            i, j = match.span()
+            while i < startLoc and j <= startLoc:
+                found = match
+                if i == j:
+                    j = j + 1
+                match = reg.search(text, j)
+                if match == None:
+                    break
+                i, j = match.span()
+            if found == None:
+                if wrap:  # try again, but this time from bottom of file
+                    match = reg.search(text, startLoc)
+                    if match == None:
+                        return -1, None, None, None
+                    found = None
+                    i, j = match.span()
+                    end = len(text)
+                    while i < end and j <= end:
+                        found = match
+                        if i == j:
+                            j = j + 1
+                        match = reg.search(text, j)
+                        if match == None:
+                            break
+                        i, j = match.span()
+                    if found == None:
+                        return -1, None, None, None
+                else:
+                    return -1, None, None, None
+            start = found.start()
+            end = found.end()
+
+        if replace and start != -1:
+            newText, count = reg.subn(replaceString, text, 1)
+            return count, start, end, newText
+
+        return 0, start, end, None
+
+
+    def SaveFindConfig(self, findString, wholeWord, matchCase, regExpr = None, wrap = None, upDown = None, replaceString = None):
+        """ Save find/replace patterns and search flags to registry.
+        
+            findString = search pattern
+            wholeWord = match whole word only
+            matchCase = match case
+            regExpr = use regular expressions in search pattern
+            wrap = return to top/bottom of file on search
+            upDown = search up or down from current cursor position
+            replaceString = replace string
+        """
+        config = wx.ConfigBase_Get()
+
+        config.Write(FIND_MATCHPATTERN, findString)
+        config.WriteInt(FIND_MATCHCASE, matchCase)
+        config.WriteInt(FIND_MATCHWHOLEWORD, wholeWord)
+        if replaceString != None:
+            config.Write(FIND_MATCHREPLACE, replaceString)
+        if regExpr != None:
+            config.WriteInt(FIND_MATCHREGEXPR, regExpr)
+        if wrap != None:
+            config.WriteInt(FIND_MATCHWRAP, wrap)
+        if upDown != None:
+            config.WriteInt(FIND_MATCHUPDOWN, upDown)
+
+
+    def GetFindString(self):
+        """ Load the search pattern from registry """
+        return wx.ConfigBase_Get().Read(FIND_MATCHPATTERN, "")
+
+
+    def GetReplaceString(self):
+        """ Load the replace pattern from registry """
+        return wx.ConfigBase_Get().Read(FIND_MATCHREPLACE, "")
+
+
+    def GetFlags(self):
+        """ Load search parameters from registry """
+        config = wx.ConfigBase_Get()
+
+        flags = 0
+        if config.ReadInt(FIND_MATCHWHOLEWORD, False):
+            flags = flags | wx.FR_WHOLEWORD
+        if config.ReadInt(FIND_MATCHCASE, False):
+            flags = flags | wx.FR_MATCHCASE
+        if config.ReadInt(FIND_MATCHUPDOWN, False):
+            flags = flags | wx.FR_DOWN
+        if config.ReadInt(FIND_MATCHREGEXPR, False):
+            flags = flags | FindService.FR_REGEXP
+        if config.ReadInt(FIND_MATCHWRAP, False):
+            flags = flags | FindService.FR_WRAP
+        return flags
+
+
+class FindDialog(wx.Dialog):
+    """ Find Dialog with regular expression matching and wrap to top/bottom of file. """
+
+    def __init__(self, parent, id, title, size, findString=None):
+        wx.Dialog.__init__(self, parent, id, title, size=size)
+
+        config = wx.ConfigBase_Get()
+        borderSizer = wx.BoxSizer(wx.VERTICAL)
+        gridSizer = wx.GridBagSizer(SPACE, SPACE)
+
+        lineSizer = wx.BoxSizer(wx.HORIZONTAL)
+        lineSizer.Add(wx.StaticText(self, -1, _("Find what:")), 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, SPACE)
+        if not findString:
+            findString = config.Read(FIND_MATCHPATTERN, "")
+        self._findCtrl = wx.TextCtrl(self, -1, findString, size=(200,-1))
+        lineSizer.Add(self._findCtrl, 0)
+        gridSizer.Add(lineSizer, pos=(0,0), span=(1,2))
+        choiceSizer = wx.BoxSizer(wx.VERTICAL)
+        self._wholeWordCtrl = wx.CheckBox(self, -1, _("Match whole word only"))
+        self._wholeWordCtrl.SetValue(config.ReadInt(FIND_MATCHWHOLEWORD, False))
+        self._matchCaseCtrl = wx.CheckBox(self, -1, _("Match case"))
+        self._matchCaseCtrl.SetValue(config.ReadInt(FIND_MATCHCASE, False))
+        self._regExprCtrl = wx.CheckBox(self, -1, _("Regular expression"))
+        self._regExprCtrl.SetValue(config.ReadInt(FIND_MATCHREGEXPR, False))
+        self._wrapCtrl = wx.CheckBox(self, -1, _("Wrap"))
+        self._wrapCtrl.SetValue(config.ReadInt(FIND_MATCHWRAP, False))
+        choiceSizer.Add(self._wholeWordCtrl, 0, wx.BOTTOM, SPACE)
+        choiceSizer.Add(self._matchCaseCtrl, 0, wx.BOTTOM, SPACE)
+        choiceSizer.Add(self._regExprCtrl, 0, wx.BOTTOM, SPACE)
+        choiceSizer.Add(self._wrapCtrl, 0)
+        gridSizer.Add(choiceSizer, pos=(1,0), span=(2,1))
+
+        self._radioBox = wx.RadioBox(self, -1, _("Direction"), choices = ["Up", "Down"])
+        self._radioBox.SetSelection(config.ReadInt(FIND_MATCHUPDOWN, 1))
+        gridSizer.Add(self._radioBox, pos=(1,1), span=(2,1))
+
+        buttonSizer = wx.BoxSizer(wx.VERTICAL)
+        findBtn = wx.Button(self, FindService.FINDONE_ID, _("Find Next"))
+        findBtn.SetDefault()
+        wx.EVT_BUTTON(self, FindService.FINDONE_ID, self.OnActionEvent)
+        cancelBtn = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
+        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnClose)
+        buttonSizer.Add(findBtn, 0, wx.BOTTOM, HALF_SPACE)
+        buttonSizer.Add(cancelBtn, 0)
+        gridSizer.Add(buttonSizer, pos=(0,2), span=(3,1))
+
+        borderSizer.Add(gridSizer, 0, wx.ALL, SPACE)
+
+        self.Bind(wx.EVT_CLOSE, self.OnClose)
+
+        self.SetSizer(borderSizer)
+        self.Fit()
+        self._findCtrl.SetFocus()
+
+    def SaveConfig(self):
+        """ Save find patterns and search flags to registry. """
+        findService = wx.GetApp().GetService(FindService)
+        if findService:
+            findService.SaveFindConfig(self._findCtrl.GetValue(),
+                                       self._wholeWordCtrl.IsChecked(),
+                                       self._matchCaseCtrl.IsChecked(),
+                                       self._regExprCtrl.IsChecked(),
+                                       self._wrapCtrl.IsChecked(),
+                                       self._radioBox.GetSelection(),
+                                       )
+
+
+    def DoClose(self):
+        self.SaveConfig()
+        self.Destroy()
+
+
+    def OnClose(self, event):
+        findService = wx.GetApp().GetService(FindService)
+        if findService:
+            findService.OnFindClose(event)
+        self.DoClose()
+
+
+    def OnActionEvent(self, event):
+        self.SaveConfig()
+
+        if wx.GetApp().GetDocumentManager().GetFlags() & wx.lib.docview.DOC_MDI:
+            if wx.GetApp().GetTopWindow().ProcessEvent(event):
+                return True
+        else:
+            view = wx.GetApp().GetDocumentManager().GetLastActiveView()
+            if view and view.ProcessEvent(event):
+                return True
+        return False
+
+
+class FindReplaceDialog(FindDialog):
+    """ Find/Replace Dialog with regular expression matching and wrap to top/bottom of file. """
+
+    def __init__(self, parent, id, title, size, findString=None):
+        wx.Dialog.__init__(self, parent, id, title, size=size)
+
+        config = wx.ConfigBase_Get()
+        borderSizer = wx.BoxSizer(wx.VERTICAL)
+        gridSizer = wx.GridBagSizer(SPACE, SPACE)
+
+        gridSizer2 = wx.GridBagSizer(SPACE, SPACE)
+        gridSizer2.Add(wx.StaticText(self, -1, _("Find what:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(0,0))
+        if not findString:
+            findString = config.Read(FIND_MATCHPATTERN, "")
+        self._findCtrl = wx.TextCtrl(self, -1, findString, size=(200,-1))
+        gridSizer2.Add(self._findCtrl, pos=(0,1))
+        gridSizer2.Add(wx.StaticText(self, -1, _("Replace with:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(1,0))
+        self._replaceCtrl = wx.TextCtrl(self, -1, config.Read(FIND_MATCHREPLACE, ""), size=(200,-1))
+        gridSizer2.Add(self._replaceCtrl, pos=(1,1))
+        gridSizer.Add(gridSizer2, pos=(0,0), span=(1,2))
+        choiceSizer = wx.BoxSizer(wx.VERTICAL)
+        self._wholeWordCtrl = wx.CheckBox(self, -1, _("Match whole word only"))
+        self._wholeWordCtrl.SetValue(config.ReadInt(FIND_MATCHWHOLEWORD, False))
+        self._matchCaseCtrl = wx.CheckBox(self, -1, _("Match case"))
+        self._matchCaseCtrl.SetValue(config.ReadInt(FIND_MATCHCASE, False))
+        self._regExprCtrl = wx.CheckBox(self, -1, _("Regular expression"))
+        self._regExprCtrl.SetValue(config.ReadInt(FIND_MATCHREGEXPR, False))
+        self._wrapCtrl = wx.CheckBox(self, -1, _("Wrap"))
+        self._wrapCtrl.SetValue(config.ReadInt(FIND_MATCHWRAP, False))
+        choiceSizer.Add(self._wholeWordCtrl, 0, wx.BOTTOM, SPACE)
+        choiceSizer.Add(self._matchCaseCtrl, 0, wx.BOTTOM, SPACE)
+        choiceSizer.Add(self._regExprCtrl, 0, wx.BOTTOM, SPACE)
+        choiceSizer.Add(self._wrapCtrl, 0)
+        gridSizer.Add(choiceSizer, pos=(1,0), span=(2,1))
+
+        self._radioBox = wx.RadioBox(self, -1, _("Direction"), choices = ["Up", "Down"])
+        self._radioBox.SetSelection(config.ReadInt(FIND_MATCHUPDOWN, 1))
+        gridSizer.Add(self._radioBox, pos=(1,1), span=(2,1))
+
+        buttonSizer = wx.BoxSizer(wx.VERTICAL)
+        findBtn = wx.Button(self, FindService.FINDONE_ID, _("Find Next"))
+        findBtn.SetDefault()
+        wx.EVT_BUTTON(self, FindService.FINDONE_ID, self.OnActionEvent)
+        cancelBtn = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
+        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnClose)
+        replaceBtn = wx.Button(self, FindService.REPLACEONE_ID, _("Replace"))
+        wx.EVT_BUTTON(self, FindService.REPLACEONE_ID, self.OnActionEvent)
+        replaceAllBtn = wx.Button(self, FindService.REPLACEALL_ID, _("Replace All"))
+        wx.EVT_BUTTON(self, FindService.REPLACEALL_ID, self.OnActionEvent)
+        buttonSizer.Add(findBtn, 0, wx.BOTTOM, HALF_SPACE)
+        buttonSizer.Add(replaceBtn, 0, wx.BOTTOM, HALF_SPACE)
+        buttonSizer.Add(replaceAllBtn, 0, wx.BOTTOM, HALF_SPACE)
+        buttonSizer.Add(cancelBtn, 0)
+        gridSizer.Add(buttonSizer, pos=(0,2), span=(3,1))
+
+        borderSizer.Add(gridSizer, 0, wx.ALL, SPACE)
+
+        self.Bind(wx.EVT_CLOSE, self.OnClose)
+
+        self.SetSizer(borderSizer)
+        self.Fit()
+        self._findCtrl.SetFocus()
+        
+
+    def SaveConfig(self):
+        """ Save find/replace patterns and search flags to registry. """
+        findService = wx.GetApp().GetService(FindService)
+        if findService:
+            findService.SaveFindConfig(self._findCtrl.GetValue(),
+                                       self._wholeWordCtrl.IsChecked(),
+                                       self._matchCaseCtrl.IsChecked(),
+                                       self._regExprCtrl.IsChecked(),
+                                       self._wrapCtrl.IsChecked(),
+                                       self._radioBox.GetSelection(),
+                                       self._replaceCtrl.GetValue()
+                                       )
+
+
+#----------------------------------------------------------------------------
+# Menu Bitmaps - generated by encode_bitmaps.py
+#----------------------------------------------------------------------------
+from wx import ImageFromStream, BitmapFromImage
+import cStringIO
+
+
+def getFindData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00\x81IDAT8\x8d\xa5S\xc1\x16\xc0\x10\x0ckk\xff\xff\xc7d\x87\xad^U\r\
+\x93S\xe5U$\n\xb3$:\xc1e\x17(\x19Z\xb3$\x9e\xf1DD\xe2\x15\x01x\xea\x93\xef\
+\x04\x989\xea\x1b\xf2U\xc0\xda\xb4\xeb\x11\x1f:\xd8\xb5\xff8\x93\xd4\xa9\xae\
+@/S\xaaUwJ3\x85\xc0\x81\xee\xeb.q\x17C\x81\xd5XU \x1a\x93\xc6\x18\x8d\x90\
+\xe8}\x89\x00\x9a&\x9b_k\x94\x0c\xdf\xd78\xf8\x0b\x99Y\xb4\x08c\x9e\xfe\xc6\
+\xe3\x087\xf9\xd0D\x180\xf1#\x8e\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+
+def getFindBitmap():
+    return BitmapFromImage(getFindImage())
+
+
+def getFindImage():
+    stream = cStringIO.StringIO(getFindData())
+    return ImageFromStream(stream)
+
diff --git a/wxPython/samples/docview/activegrid/tool/TextEditor.py b/wxPython/samples/docview/activegrid/tool/TextEditor.py
new file mode 100644 (file)
index 0000000..9f0517e
--- /dev/null
@@ -0,0 +1,551 @@
+#----------------------------------------------------------------------------
+# Name:         TextEditor.py
+# Purpose:      Text Editor for pydocview
+#
+# Author:       Peter Yared
+#
+# Created:      8/15/03
+# CVS-ID:       $Id$
+# Copyright:    (c) 2003-2004 ActiveGrid, Inc.
+# License:      wxWindows license
+#----------------------------------------------------------------------------
+import wx
+import wx.lib.docview
+import wx.lib.pydocview
+import string
+import FindService
+_ = wx.GetTranslation
+
+class TextDocument(wx.lib.docview.Document):
+
+
+    def OnSaveDocument(self, filename):
+        view = self.GetFirstView()
+        if not view.GetTextCtrl().SaveFile(filename):
+            return False
+        self.Modify(False)
+        self.SetDocumentSaved(True)
+        #if wx.Platform == "__WXMAC__":
+        #    fn = wx.Filename(filename)
+        #    fn.MacSetDefaultTypeAndCreator()
+        return True
+
+
+    def OnOpenDocument(self, filename):
+        view = self.GetFirstView()
+        if not view.GetTextCtrl().LoadFile(filename):
+            return False
+        self.SetFilename(filename, True)
+        self.Modify(False)
+        self.UpdateAllViews()
+        self._savedYet = True
+        return True
+
+
+    def IsModified(self):
+        view = self.GetFirstView()
+        if view and view.GetTextCtrl():
+            return wx.lib.docview.Document.IsModified(self) or view.GetTextCtrl().IsModified()
+        else:
+            return wx.lib.docview.Document.IsModified(self)
+
+
+    def Modify(self, mod):
+        view = self.GetFirstView()
+        wx.lib.docview.Document.Modify(self, mod)
+        if not mod and view and view.GetTextCtrl():
+            view.GetTextCtrl().DiscardEdits()
+
+
+class TextView(wx.lib.docview.View):
+
+
+    #----------------------------------------------------------------------------
+    # Overridden methods
+    #----------------------------------------------------------------------------
+
+    def __init__(self):
+        wx.lib.docview.View.__init__(self)
+        self._textCtrl = None
+        self._wordWrap = wx.ConfigBase_Get().ReadInt("TextEditorWordWrap", True)
+
+
+    def OnCreate(self, doc, flags):
+        frame = wx.GetApp().CreateDocumentFrame(self, doc, flags)
+        sizer = wx.BoxSizer()
+        font, color = self._GetFontAndColorFromConfig()
+        self._textCtrl = self._BuildTextCtrl(frame, font, color = color)
+        sizer.Add(self._textCtrl, 1, wx.EXPAND, 0)
+        frame.SetSizer(sizer)
+        frame.Layout()
+        frame.Show(True)
+        self.Activate()
+        return True
+
+
+    def _BuildTextCtrl(self, parent, font, color = wx.BLACK, value = "", selection = [0, 0]):
+        if self._wordWrap:
+            wordWrapStyle = wx.TE_WORDWRAP
+        else:
+            wordWrapStyle = wx.TE_DONTWRAP
+        textCtrl = wx.TextCtrl(parent, -1, pos = wx.DefaultPosition, size = parent.GetClientSize(), style = wx.TE_MULTILINE | wordWrapStyle)
+        textCtrl.SetFont(font)
+        textCtrl.SetForegroundColour(color)
+        textCtrl.SetValue(value)
+        return textCtrl
+
+
+    def _GetFontAndColorFromConfig(self):
+        font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
+        config = wx.ConfigBase_Get()
+        fontData = config.Read("TextEditorFont", "")
+        if fontData:
+            nativeFont = wx.NativeFontInfo()
+            nativeFont.FromString(fontData)
+            font.SetNativeFontInfo(nativeFont)
+        color = wx.BLACK
+        colorData = config.Read("TextEditorColor", "")
+        if colorData:
+            red = int("0x" + colorData[0:2], 16)
+            green = int("0x" + colorData[2:4], 16)
+            blue = int("0x" + colorData[4:6], 16)
+            color = wx.Color(red, green, blue)
+        return font, color
+
+
+    def OnCreateCommandProcessor(self):
+        # Don't create a command processor, it has its own
+        pass
+
+
+    def OnActivateView(self, activate, activeView, deactiveView):
+        if activate and self._textCtrl:
+            # In MDI mode just calling set focus doesn't work and in SDI mode using CallAfter causes an endless loop
+            if self.GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI:
+                self._textCtrl.SetFocus()
+            else:
+                def SetFocusToTextCtrl():
+                    if self._textCtrl:  # Need to make sure it is there in case we are in the closeall mode of the MDI window
+                        self._textCtrl.SetFocus()
+                wx.CallAfter(SetFocusToTextCtrl)
+
+
+    def OnUpdate(self, sender = None, hint = None):
+        if hint == "Word Wrap":
+            self.SetWordWrap(wx.ConfigBase_Get().ReadInt("TextEditorWordWrap", True))
+        elif hint == "Font":
+            font, color = self._GetFontAndColorFromConfig()
+            self.SetFont(font, color)
+
+
+    def OnClose(self, deleteWindow = True):
+        if not wx.lib.docview.View.OnClose(self, deleteWindow):
+            return False
+        self.Activate(False)
+        if deleteWindow:
+            self.GetFrame().Destroy()
+        return True
+
+
+    # Since ProcessEvent is not virtual, we have to trap the relevant events using this pseudo-ProcessEvent instead of EVT_MENU
+    def ProcessEvent(self, event):
+        id = event.GetId()
+        if id == wx.ID_UNDO:
+            if not self._textCtrl:
+                return False
+            self._textCtrl.Undo()
+            return True
+        elif id == wx.ID_REDO:
+            if not self._textCtrl:
+                return False
+            self._textCtrl.Redo()
+            return True
+        elif id == wx.ID_CUT:
+            if not self._textCtrl:
+                return False
+            self._textCtrl.Cut()
+            return True
+        elif id == wx.ID_COPY:
+            if not self._textCtrl:
+                return False
+            self._textCtrl.Copy()
+            return True
+        elif id == wx.ID_PASTE:
+            if not self._textCtrl:
+                return False
+            self._textCtrl.Paste()
+            return True
+        elif id == wx.ID_CLEAR:
+            if not self._textCtrl:
+                return False
+            self._textCtrl.Replace(self._textCtrl.GetSelection()[0], self._textCtrl.GetSelection()[1], '')
+            return True
+        elif id == wx.ID_SELECTALL:
+            if not self._textCtrl:
+                return False
+            self._textCtrl.SetSelection(-1, -1)
+            return True
+        elif id == TextService.CHOOSE_FONT_ID:
+            if not self._textCtrl:
+                return False
+            self.OnChooseFont(event)
+            return True
+        elif id == TextService.WORD_WRAP_ID:
+            if not self._textCtrl:
+                return False
+            self.OnWordWrap(event)
+            return True
+        elif id == FindService.FindService.FIND_ID:
+            self.OnFind()
+            return True
+        elif id == FindService.FindService.FIND_PREVIOUS_ID:
+            self.DoFind(forceFindPrevious = True)
+            return True
+        elif id == FindService.FindService.FIND_NEXT_ID:
+            self.DoFind(forceFindNext = True)
+            return True
+        elif id == FindService.FindService.REPLACE_ID:
+            self.OnFind(replace = True)
+            return True
+        elif id == FindService.FindService.FINDONE_ID:
+            self.DoFind()
+            return True
+        elif id == FindService.FindService.REPLACEONE_ID:
+            self.DoFind(replace = True)
+            return True
+        elif id == FindService.FindService.REPLACEALL_ID:
+            self.DoFind(replaceAll = True)
+            return True
+        elif id == FindService.FindService.GOTO_LINE_ID:
+            self.OnGotoLine(event)
+            return True
+        else:
+            return wx.lib.docview.View.ProcessEvent(self, event)
+
+
+    def ProcessUpdateUIEvent(self, event):
+        if not self._textCtrl:
+            return False
+
+        hasText = len(self._textCtrl.GetValue()) > 0
+
+        id = event.GetId()
+        if id == wx.ID_UNDO:
+            event.Enable(self._textCtrl.CanUndo())
+            return True
+        elif id == wx.ID_REDO:
+            event.Enable(self._textCtrl.CanRedo())
+            return True
+        if id == wx.ID_CUT:
+            event.Enable(self._textCtrl.CanCut())
+            return True
+        elif id == wx.ID_COPY:
+            event.Enable(self._textCtrl.CanCopy())
+            return True
+        elif id == wx.ID_PASTE:
+            event.Enable(self._textCtrl.CanPaste())
+            return True
+        elif id == wx.ID_CLEAR:
+            event.Enable(True)  # wxBug: No matter what we do, the wxTextCtrl disables the Clear menu item and the menu item traps the Del key and the wxTextCtrl doesn't get it and can't delete the next character
+            return True
+        elif id == wx.ID_SELECTALL:
+            event.Enable(hasText)
+            return True
+        elif id == TextService.CHOOSE_FONT_ID:
+            event.Enable(True)
+            return True
+        elif id == TextService.WORD_WRAP_ID:
+            event.Enable(True)
+            return True
+        elif id == FindService.FindService.FIND_ID:
+            event.Enable(hasText)
+            return True
+        elif id == FindService.FindService.FIND_PREVIOUS_ID:
+            event.Enable(hasText and
+                         self._FindServiceHasString() and
+                         self._textCtrl.GetSelection()[0] > 0)
+            return True
+        elif id == FindService.FindService.FIND_NEXT_ID:
+            event.Enable(hasText and
+                         self._FindServiceHasString() and
+                         self._textCtrl.GetSelection()[0] < len(self._textCtrl.GetValue()))
+            return True
+        elif id == FindService.FindService.REPLACE_ID:
+            event.Enable(hasText)
+            return True
+        elif id == FindService.FindService.GOTO_LINE_ID:
+            event.Enable(True)
+            return True
+        else:
+            return wx.lib.docview.View.ProcessUpdateUIEvent(self, event)
+
+
+    #----------------------------------------------------------------------------
+    # Methods for TextDocument to call
+    #----------------------------------------------------------------------------
+
+    def GetTextCtrl(self):
+        return self._textCtrl
+
+
+    #----------------------------------------------------------------------------
+    # Format methods
+    #----------------------------------------------------------------------------
+
+    def OnChooseFont(self, event):
+        data = wx.FontData()
+        data.EnableEffects(True)
+        data.SetInitialFont(self._textCtrl.GetFont())
+        data.SetColour(self._textCtrl.GetForegroundColour())
+        fontDialog = wx.FontDialog(self.GetFrame(), data)
+        if fontDialog.ShowModal() == wx.ID_OK:
+            data = fontDialog.GetFontData()
+            self.SetFont(data.GetChosenFont(), data.GetColour())
+        fontDialog.Destroy()
+
+
+    def SetFont(self, font, color):
+        self._textCtrl.SetFont(font)
+        self._textCtrl.SetForegroundColour(color)
+        self._textCtrl.Refresh()
+        self._textCtrl.Layout()
+
+
+    def OnWordWrap(self, event):
+        self.SetWordWrap(not self.GetWordWrap())
+
+
+    def GetWordWrap(self):
+        return self._wordWrap
+
+
+    def SetWordWrap(self, wordWrap = True):
+        self._wordWrap = wordWrap
+        temp = self._textCtrl
+        self._textCtrl = self._BuildTextCtrl(temp.GetParent(),
+                                             font = temp.GetFont(),
+                                             color = temp.GetForegroundColour(),
+                                             value = temp.GetValue(),
+                                             selection = temp.GetSelection())
+        self.GetDocument().Modify(temp.IsModified())
+        temp.Destroy()
+
+
+    #----------------------------------------------------------------------------
+    # Find methods
+    #----------------------------------------------------------------------------
+
+    def OnFind(self, replace = False):
+        findService = wx.GetApp().GetService(FindService.FindService)
+        if findService:
+            findService.ShowFindReplaceDialog(findString = self._textCtrl.GetStringSelection(), replace = replace)
+
+
+    def DoFind(self, forceFindNext = False, forceFindPrevious = False, replace = False, replaceAll = False):
+        findService = wx.GetApp().GetService(FindService.FindService)
+        if not findService:
+            return
+        findString = findService.GetFindString()
+        if len(findString) == 0:
+            return -1
+        replaceString = findService.GetReplaceString()
+        flags = findService.GetFlags()
+        startLoc, endLoc = self._textCtrl.GetSelection()
+
+        wholeWord = flags & wx.FR_WHOLEWORD > 0
+        matchCase = flags & wx.FR_MATCHCASE > 0
+        regExp = flags & FindService.FindService.FR_REGEXP > 0
+        down = flags & wx.FR_DOWN > 0
+        wrap = flags & FindService.FindService.FR_WRAP > 0
+
+        if forceFindPrevious:   # this is from function keys, not dialog box
+            down = False
+            wrap = False        # user would want to know they're at the end of file
+        elif forceFindNext:
+            down = True
+            wrap = False        # user would want to know they're at the end of file
+
+        # On replace dialog operations, user is allowed to replace the currently highlighted text to determine if it should be replaced or not.
+        # Typically, it is the text from a previous find operation, but we must check to see if it isn't, user may have moved the cursor or selected some other text accidentally.
+        # If the text is a match, then replace it.
+        if replace:
+            result, start, end, replText = findService.DoFind(findString, replaceString, self._textCtrl.GetStringSelection(), 0, 0, True, matchCase, wholeWord, regExp, replace)
+            if result > 0:
+                self._textCtrl.Replace(startLoc, endLoc, replaceString)
+                self.GetDocument().Modify(True)
+                wx.GetApp().GetTopWindow().PushStatusText(_("1 occurrence of \"%s\" replaced") % findString)
+                if down:
+                    startLoc += len(replText)  # advance start location past replacement string to new text
+                endLoc = startLoc
+
+        text = self._textCtrl.GetValue()
+        if wx.Platform == "__WXMSW__":
+            text = string.replace(text, '\n', '\r\n')
+
+        # Find the next matching text occurance or if it is a ReplaceAll, replace all occurances
+        # Even if the user is Replacing, we should replace here, but only select the text and let the user replace it with the next Replace operation
+        result, start, end, text = findService.DoFind(findString, replaceString, text, startLoc, endLoc, down, matchCase, wholeWord, regExp, False, replaceAll, wrap)
+        if result > 0:
+            self._textCtrl.SetValue(text)
+            self.GetDocument().Modify(True)
+            if result == 1:
+                wx.GetApp().GetTopWindow().PushStatusText(_("1 occurrence of \"%s\" replaced") % findString)
+            else:
+                wx.GetApp().GetTopWindow().PushStatusText(_("%i occurrences of \"%s\" replaced") % (result, findString))
+        elif result == 0:
+            self._textCtrl.SetSelection(start, end)
+            self._textCtrl.SetFocus()
+            wx.GetApp().GetTopWindow().PushStatusText(_("Found \"%s\"") % findString)
+        else:
+            wx.GetApp().GetTopWindow().PushStatusText(_("Can't find \"%s\"") % findString)
+
+
+    def _FindServiceHasString(self):
+        findService = wx.GetApp().GetService(FindService.FindService)
+        if not findService or not findService.GetFindString():
+            return False
+        return True
+
+
+    def OnGotoLine(self, event):
+        findService = wx.GetApp().GetService(FindService.FindService)
+        if findService:
+            line = findService.GetLineNumber(self.GetDocumentManager().FindSuitableParent())
+            if line > -1:
+                pos = self._textCtrl.XYToPosition(0, line - 1)
+                self._textCtrl.SetSelection(pos, pos)
+
+
+class TextService(wx.lib.pydocview.DocService):
+
+
+    WORD_WRAP_ID = wx.NewId()
+    CHOOSE_FONT_ID = wx.NewId()
+
+
+    def __init__(self):
+        wx.lib.pydocview.DocService.__init__(self)
+
+
+    def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
+        if document and document.GetDocumentTemplate().GetDocumentType() != TextDocument:
+            return
+        config = wx.ConfigBase_Get()
+
+        formatMenuIndex = menuBar.FindMenu(_("&Format"))
+        if formatMenuIndex > -1:
+            formatMenu = menuBar.GetMenu(formatMenuIndex)
+        else:
+            formatMenu = wx.Menu()
+        formatMenu = wx.Menu()
+        if not menuBar.FindItemById(TextService.WORD_WRAP_ID):
+            formatMenu.AppendCheckItem(TextService.WORD_WRAP_ID, _("Word Wrap"), _("Wraps text horizontally when checked"))
+            formatMenu.Check(TextService.WORD_WRAP_ID, config.ReadInt("TextEditorWordWrap", True))
+            wx.EVT_MENU(frame, TextService.WORD_WRAP_ID, frame.ProcessEvent)
+            wx.EVT_UPDATE_UI(frame, TextService.WORD_WRAP_ID, frame.ProcessUpdateUIEvent)
+        if not menuBar.FindItemById(TextService.CHOOSE_FONT_ID):
+            formatMenu.Append(TextService.CHOOSE_FONT_ID, _("Font..."), _("Sets the font to use"))
+            wx.EVT_MENU(frame, TextService.CHOOSE_FONT_ID, frame.ProcessEvent)
+            wx.EVT_UPDATE_UI(frame, TextService.CHOOSE_FONT_ID, frame.ProcessUpdateUIEvent)
+        if formatMenuIndex == -1:
+            viewMenuIndex = menuBar.FindMenu(_("&View"))
+            menuBar.Insert(viewMenuIndex + 1, formatMenu, _("&Format"))
+
+
+    def ProcessUpdateUIEvent(self, event):
+        id = event.GetId()
+        if id == TextService.CHOOSE_FONT_ID:
+            event.Enable(False)
+            return True
+        elif id == TextService.WORD_WRAP_ID:
+            event.Enable(False)
+            return True
+        else:
+            return False
+
+
+class TextOptionsPanel(wx.Panel):
+
+
+    def __init__(self, parent, id):
+        wx.Panel.__init__(self, parent, id)
+        SPACE = 10
+        HALF_SPACE   = 5
+        config = wx.ConfigBase_Get()
+        self._textFont = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
+        fontData = config.Read("TextEditorFont", "")
+        if fontData:
+            nativeFont = wx.NativeFontInfo()
+            nativeFont.FromString(fontData)
+            self._textFont.SetNativeFontInfo(nativeFont)
+        self._originalTextFont = self._textFont
+        self._textColor = wx.BLACK
+        colorData = config.Read("TextEditorColor", "")
+        if colorData:
+            red = int("0x" + colorData[0:2], 16)
+            green = int("0x" + colorData[2:4], 16)
+            blue = int("0x" + colorData[4:6], 16)
+            self._textColor = wx.Color(red, green, blue)
+        self._originalTextColor = self._textColor
+        parent.AddPage(self, _("Text"))
+        fontLabel = wx.StaticText(self, -1, _("Font:"))
+        self._sampleTextCtrl = wx.TextCtrl(self, -1, "", size = (125, -1))
+        self._sampleTextCtrl.SetEditable(False)
+        chooseFontButton = wx.Button(self, -1, _("Choose Font..."))
+        wx.EVT_BUTTON(self, chooseFontButton.GetId(), self.OnChooseFont)
+        self._wordWrapCheckBox = wx.CheckBox(self, -1, _("Wrap words inside text area"))
+        self._wordWrapCheckBox.SetValue(wx.ConfigBase_Get().ReadInt("TextEditorWordWrap", True))
+        textPanelBorderSizer = wx.BoxSizer(wx.VERTICAL)
+        textPanelSizer = wx.BoxSizer(wx.VERTICAL)
+        textFontSizer = wx.BoxSizer(wx.HORIZONTAL)
+        textFontSizer.Add(fontLabel, 0, wx.ALIGN_LEFT | wx.RIGHT | wx.TOP, HALF_SPACE)
+        textFontSizer.Add(self._sampleTextCtrl, 0, wx.ALIGN_LEFT | wx.EXPAND | wx.RIGHT, HALF_SPACE)
+        textFontSizer.Add(chooseFontButton, 0, wx.ALIGN_RIGHT | wx.LEFT, HALF_SPACE)
+        textPanelSizer.Add(textFontSizer, 0, wx.ALL, HALF_SPACE)
+        textPanelSizer.Add(self._wordWrapCheckBox, 0, wx.ALL, HALF_SPACE)
+        textPanelBorderSizer.Add(textPanelSizer, 0, wx.ALL, SPACE)
+        self.SetSizer(textPanelBorderSizer)
+        self.UpdateSampleFont()
+
+
+    def UpdateSampleFont(self):
+        nativeFont = wx.NativeFontInfo()
+        nativeFont.FromString(self._textFont.GetNativeFontInfoDesc())
+        font = wx.NullFont
+        font.SetNativeFontInfo(nativeFont)
+        font.SetPointSize(self._sampleTextCtrl.GetFont().GetPointSize())  # Use the standard point size
+        self._sampleTextCtrl.SetFont(font)
+        self._sampleTextCtrl.SetForegroundColour(self._textColor)
+        self._sampleTextCtrl.SetValue(_("%d pt. %s") % (self._textFont.GetPointSize(), self._textFont.GetFaceName()))
+        self._sampleTextCtrl.Refresh()
+        self.Layout()
+
+
+    def OnChooseFont(self, event):
+        data = wx.FontData()
+        data.EnableEffects(True)
+        data.SetInitialFont(self._textFont)
+        data.SetColour(self._textColor)
+        fontDialog = wx.FontDialog(self, data)
+        if fontDialog.ShowModal() == wx.ID_OK:
+            data = fontDialog.GetFontData()
+            self._textFont = data.GetChosenFont()
+            self._textColor = data.GetColour()
+            self.UpdateSampleFont()
+        fontDialog.Destroy()
+
+
+    def OnOK(self, optionsDialog):
+        config = wx.ConfigBase_Get()
+        doWordWrapUpdate = config.ReadInt("TextEditorWordWrap", True) != self._wordWrapCheckBox.GetValue()
+        config.WriteInt("TextEditorWordWrap", self._wordWrapCheckBox.GetValue())
+        doFontUpdate = self._originalTextFont != self._textFont or self._originalTextColor != self._textColor
+        config.Write("TextEditorFont", self._textFont.GetNativeFontInfoDesc())
+        config.Write("TextEditorColor", "%02x%02x%02x" % (self._textColor.Red(), self._textColor.Green(), self._textColor.Blue()))
+        if doWordWrapUpdate or doFontUpdate:
+            for document in optionsDialog.GetDocManager().GetDocuments():
+                if document.GetDocumentTemplate().GetDocumentType() == TextDocument:
+                    if doWordWrapUpdate:
+                        document.UpdateAllViews(hint = "Word Wrap")
+                    if doFontUpdate:
+                        document.UpdateAllViews(hint = "Font")
diff --git a/wxPython/samples/docview/activegrid/tool/__init__.py b/wxPython/samples/docview/activegrid/tool/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/wxPython/samples/docview/activegrid/tool/data/tips.txt b/wxPython/samples/docview/activegrid/tool/data/tips.txt
new file mode 100644 (file)
index 0000000..f102916
--- /dev/null
@@ -0,0 +1,3 @@
+Tips for PyDocViewDemo App
+wxWindows rules!
+Use the source, Luke!
\ No newline at end of file
diff --git a/wxPython/samples/docview/activegrid/tool/images/splash.jpg b/wxPython/samples/docview/activegrid/tool/images/splash.jpg
new file mode 100644 (file)
index 0000000..2416247
Binary files /dev/null and b/wxPython/samples/docview/activegrid/tool/images/splash.jpg differ
diff --git a/wxPython/wx/lib/docview.py b/wxPython/wx/lib/docview.py
new file mode 100644 (file)
index 0000000..8f5f038
--- /dev/null
@@ -0,0 +1,3033 @@
+#----------------------------------------------------------------------------
+# Name:         docview.py
+# Purpose:      Port of the wxWindows docview classes
+#
+# Author:       Peter Yared
+#
+# Created:      5/15/03
+# CVS-ID:       $Id$
+# Copyright:    (c) 2003-2004 ActiveGrid, Inc. (Port of wxWindows classes by Julian Smart et al)
+# License:      wxWindows license
+#----------------------------------------------------------------------------
+
+
+import os
+import os.path
+import wx
+import sys
+_ = wx.GetTranslation
+
+
+#----------------------------------------------------------------------
+# docview globals
+#----------------------------------------------------------------------
+
+DOC_SDI = 1
+DOC_MDI = 2
+DOC_NEW = 4
+DOC_SILENT = 8
+DOC_OPEN_ONCE = 16
+DEFAULT_DOCMAN_FLAGS = DOC_SDI & DOC_OPEN_ONCE
+
+TEMPLATE_VISIBLE = 1
+TEMPLATE_INVISIBLE = 2
+DEFAULT_TEMPLATE_FLAGS = TEMPLATE_VISIBLE
+
+MAX_FILE_HISTORY = 9
+
+
+#----------------------------------------------------------------------
+# Convenience functions from wxWindows used in docview
+#----------------------------------------------------------------------
+
+
+def FileNameFromPath(path):
+    """
+    Returns the filename for a full path.
+    """
+    return os.path.split(path)[1]
+
+def FindExtension(path):
+    """
+    Returns the extension of a filename for a full path.
+    """
+    return os.path.splitext(path)[1].lower()
+
+def FileExists(path):
+    """
+    Returns True if the path exists.
+    """
+    return os.path.isfile(path)
+
+def PathOnly(path):
+    """
+    Returns the path of a full path without the filename.
+    """
+    return os.path.split(path)[0]
+
+
+#----------------------------------------------------------------------
+# Document/View Classes
+#----------------------------------------------------------------------
+
+
+class Document(wx.EvtHandler):
+    """
+    The document class can be used to model an application's file-based data. It
+    is part of the document/view framework supported by wxWindows, and cooperates
+    with the wxView, wxDocTemplate and wxDocManager classes.
+    """
+
+
+    def __init__(self, parent = None):
+        """
+        Constructor.  Define your own default constructor to initialize
+        application-specific data.
+        """
+        wx.EvtHandler.__init__(self)
+
+        self._documentModified = False
+        self._documentParent = parent
+        self._documentTemplate = None
+        self._commandProcessor = None
+        self._savedYet = False
+
+        self._documentTitle = None
+        self._documentFile = None
+        self._documentTypeName = None
+        self._documentModified = False
+        self._documentViews = []
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return False
+
+
+    def GetFilename(self):
+        """
+        Gets the filename associated with this document, or "" if none is
+        associated.
+        """
+        return self._documentFile
+
+
+    def GetTitle(self):
+        """
+        Gets the title for this document. The document title is used for an
+        associated frame (if any), and is usually constructed by the framework
+        from the filename.
+        """
+        return self._documentTitle
+
+
+    def SetTitle(self, title):
+        """
+        Sets the title for this document. The document title is used for an
+        associated frame (if any), and is usually constructed by the framework
+        from the filename.
+        """
+        self._documentTitle = title
+
+
+    def GetDocumentName(self):
+        """
+        The document type name given to the wxDocTemplate constructor,
+        copied to this document when the document is created. If several
+        document templates are created that use the same document type, this
+        variable is used in wxDocManager::CreateView to collate a list of
+        alternative view types that can be used on this kind of document.
+        """
+        return self._documentTypeName
+
+
+    def SetDocumentName(self, name):
+        """
+        Sets he document type name given to the wxDocTemplate constructor,
+        copied to this document when the document is created. If several
+        document templates are created that use the same document type, this
+        variable is used in wxDocManager::CreateView to collate a list of
+        alternative view types that can be used on this kind of document. Do
+        not change the value of this variable.
+        """
+        self._documentTypeName = name
+
+
+    def GetDocumentSaved(self):
+        """
+        Returns True if the document has been saved.  This method has been
+        added to wxPython and is not in wxWindows.
+        """
+        return self._savedYet
+
+
+    def SetDocumentSaved(self, saved = True):
+        """
+        Sets whether the document has been saved.  This method has been
+        added to wxPython and is not in wxWindows.
+        """
+        self._savedYet = saved
+
+
+    def GetCommandProcessor(self):
+        """
+        Returns the command processor associated with this document.
+        """
+        return self._commandProcessor
+
+
+    def SetCommandProcessor(self, processor):
+        """
+        Sets the command processor to be used for this document. The document
+        will then be responsible for its deletion. Normally you should not
+        call this; override OnCreateCommandProcessor instead.
+        """
+        self._commandProcessor = processor
+
+
+    def IsModified(self):
+        """
+        Returns true if the document has been modified since the last save,
+        false otherwise. You may need to override this if your document view
+        maintains its own record of being modified (for example if using
+        wxTextWindow to view and edit the document).
+        """
+        return self._documentModified
+
+
+    def Modify(self, modify):
+        """
+        Call with true to mark the document as modified since the last save,
+        false otherwise. You may need to override this if your document view
+        maintains its own record of being modified (for example if using
+        xTextWindow to view and edit the document).
+        """
+        self._documentModified = modify
+
+
+    def GetViews(self):
+        """
+        Returns the list whose elements are the views on the document.
+        """
+        return self._documentViews
+
+
+    def GetDocumentTemplate(self):
+        """
+        Returns the template that created the document.
+        """
+        return self._documentTemplate
+
+
+    def SetDocumentTemplate(self, template):
+        """
+        Sets the template that created the document. Should only be called by
+        the framework.
+        """
+        self._documentTemplate = template
+
+
+    def DeleteContents(self):
+        """
+        Deletes the contents of the document.  Override this method as
+        necessary.
+        """
+        return True
+
+
+    def Destroy(self):
+        """
+        Destructor. Removes itself from the document manager.
+        """
+        self.DeleteContents()
+        if self.GetDocumentManager():
+            self.GetDocumentManager().RemoveDocument(self)
+        wx.EvtHandler.Destroy(self)
+
+
+    def Close(self):
+        """
+        Closes the document, by calling OnSaveModified and then (if this true)
+        OnCloseDocument. This does not normally delete the document object:
+        use DeleteAllViews to do this implicitly.
+        """
+        if self.OnSaveModified():
+            if self.OnCloseDocument():
+                return True
+            else:
+                return False
+        else:
+            return False
+
+
+    def OnCloseDocument(self):
+        """
+        The default implementation calls DeleteContents (an empty
+        implementation) sets the modified flag to false. Override this to
+        supply additional behaviour when the document is closed with Close.
+        """
+        self.NotifyClosing()
+        self.DeleteContents()
+        self.Modify(False)
+        return True
+
+
+    def DeleteAllViews(self):
+        """
+        Calls wxView.Close and deletes each view. Deleting the final view will
+        implicitly delete the document itself, because the wxView destructor
+        calls RemoveView. This in turns calls wxDocument::OnChangedViewList,
+        whose default implemention is to save and delete the document if no
+        views exist.
+        """
+        manager = self.GetDocumentManager()
+        for view in self._documentViews:
+            if not view.Close():
+                return False
+        if self in manager.GetDocuments():
+            self.Destroy()
+        return True
+
+
+    def GetFirstView(self):
+        """
+        A convenience function to get the first view for a document, because
+        in many cases a document will only have a single view.
+        """
+        if len(self._documentViews) == 0:
+            return None
+        return self._documentViews[0]
+
+
+    def GetDocumentManager(self):
+        """
+        Returns the associated document manager.
+        """
+        if self._documentTemplate:
+            return self._documentTemplate.GetDocumentManager()
+        return None
+
+
+    def OnNewDocument(self):
+        """
+        The default implementation calls OnSaveModified and DeleteContents,
+        makes a default title for the document, and notifies the views that
+        the filename (in fact, the title) has changed.
+        """
+        if not self.OnSaveModified() or not self.OnCloseDocument():
+            return False
+        self.DeleteContents()
+        self.Modify(False)
+        self.SetDocumentSaved(False)
+        name = self.GetDocumentManager().MakeDefaultName()
+        self.SetTitle(name)
+        self.SetFilename(name, notifyViews = True)
+
+
+    def Save(self):
+        """
+        Saves the document by calling OnSaveDocument if there is an associated
+        filename, or SaveAs if there is no filename.
+        """
+        if not self.IsModified() and self._savedYet:
+            return True
+
+        if not self._documentFile or not self._savedYet:
+            return self.SaveAs()
+        return self.OnSaveDocument(self._documentFile)
+
+
+    def SaveAs(self):
+        """
+        Prompts the user for a file to save to, and then calls OnSaveDocument.
+        """
+        docTemplate = self.GetDocumentTemplate()
+        if not docTemplate:
+            return False
+
+        descr = docTemplate.GetDescription() + _(" (") + docTemplate.GetFileFilter() + _(") |") + docTemplate.GetFileFilter()  # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk
+        filename = wx.FileSelector(_("Save As"),
+                                   docTemplate.GetDirectory(),
+                                   FileNameFromPath(self.GetFilename()),
+                                   docTemplate.GetDefaultExtension(),
+                                   wildcard = descr,
+                                   flags = wx.SAVE | wx.OVERWRITE_PROMPT,
+                                   parent = self.GetDocumentWindow())
+        if filename == "":
+            return False
+
+        name, ext = os.path.splitext(filename)
+        if ext == "":
+            filename += '.' + docTemplate.GetDefaultExtension()
+
+        self.SetFilename(filename)
+        self.SetTitle(FileNameFromPath(filename))
+
+        for view in self._documentViews:
+            view.OnChangeFilename()
+
+        if not self.OnSaveDocument(filename):
+            return False
+
+        if docTemplate.FileMatchesTemplate(filename):
+            self.GetDocumentManager().AddFileToHistory(filename)
+            
+        return True
+
+
+    def OnSaveDocument(self, filename):
+        """
+        Constructs an output file for the given filename (which must
+        not be empty), and calls SaveObject. If SaveObject returns true, the
+        document is set to unmodified; otherwise, an error message box is
+        displayed.
+        """
+        if not filename:
+            return False
+
+        msgTitle = wx.GetApp().GetAppName()
+        if not msgTitle:
+            msgTitle = _("File Error")
+
+        backupFilename = None
+        try:
+            # if current file exists, move it to a safe place temporarily
+            if os.path.exists(filename):
+
+                # Check if read-only.
+                if not os.access(filename, os.W_OK):
+                    wx.MessageBox("Could not save '%s'.  No write permission to overwrite existing file." % FileNameFromPath(filename),
+                                  msgTitle,
+                                  wx.OK | wx.ICON_EXCLAMATION,
+                                  self.GetDocumentWindow())
+                    return False
+
+                i = 1
+                backupFilename = "%s.bak%s" % (filename, i)
+                while os.path.exists(backupFilename):
+                    i += 1
+                    backupFilename = "%s.bak%s" % (filename, i)
+                os.rename(filename, backupFilename)
+
+            fileObject = file(filename, 'w')
+            self.SaveObject(fileObject)
+
+            if backupFilename:
+                os.remove(backupFilename)
+        except:
+            # save failed, restore old file
+            if backupFilename:
+                os.remove(filename)
+                os.rename(backupFilename, filename)
+
+            wx.MessageBox("Could not save '%s'.  %s" % (FileNameFromPath(filename), sys.exc_value),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          self.GetDocumentWindow())
+            return False
+
+        self.SetFilename(filename, True)
+        self.Modify(False)
+        self.SetDocumentSaved(True)
+        #if wx.Platform == '__WXMAC__':  # Not yet implemented in wxPython
+        #    wx.FileName(file).MacSetDefaultTypeAndCreator()
+        return True
+
+
+    def OnOpenDocument(self, filename):
+        """
+        Constructs an input file for the given filename (which must not
+        be empty), and calls LoadObject. If LoadObject returns true, the
+        document is set to unmodified; otherwise, an error message box is
+        displayed. The document's views are notified that the filename has
+        changed, to give windows an opportunity to update their titles. All of
+        the document's views are then updated.
+        """
+        if not self.OnSaveModified():
+            return False
+
+        msgTitle = wx.GetApp().GetAppName()
+        if not msgTitle:
+            msgTitle = _("File Error")
+
+        fileObject = file(filename, 'r')
+        try:
+            self.LoadObject(fileObject)
+        except:
+            wx.MessageBox("Could not open '%s'.  %s" % (FileNameFromPath(filename), sys.exc_value),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          self.GetDocumentWindow())
+            return False
+
+        self.SetFilename(filename, True)
+        self.Modify(False)
+        self.SetDocumentSaved(True)
+        self.UpdateAllViews()
+        return True
+
+
+    def LoadObject(self, file):
+        """
+        Override this function and call it from your own LoadObject before
+        loading your own data. LoadObject is called by the framework
+        automatically when the document contents need to be loaded.
+
+        Note that the wxPython version simply sends you a Python file object,
+        so you can use pickle.
+        """
+        return True
+
+
+    def SaveObject(self, file):
+        """
+        Override this function and call it from your own SaveObject before
+        saving your own data. SaveObject is called by the framework
+        automatically when the document contents need to be saved.
+
+        Note that the wxPython version simply sends you a Python file object,
+        so you can use pickle.
+        """
+        return True
+
+
+    def Revert(self):
+        """
+        Override this function to revert the document to its last saved state.
+        """
+        return False
+
+
+    def GetPrintableName(self):
+        """
+        Copies a suitable document name into the supplied name buffer.
+        The default function uses the title, or if there is no title, uses the
+        filename; or if no filename, the string 'Untitled'.
+        """
+        if self._documentTitle:
+            return self._documentTitle
+        elif self._documentFile:
+            return FileNameFromPath(self._documentFile)
+        else:
+            return _("Untitled")
+
+
+    def GetDocumentWindow(self):
+        """
+        Intended to return a suitable window for using as a parent for
+        document-related dialog boxes. By default, uses the frame associated
+        with the first view.
+        """
+        if len(self._documentViews) > 0:
+            return self._documentViews[0].GetFrame()
+        else:
+            return wx.GetApp().GetTopWindow()
+
+
+    def OnCreateCommandProcessor(self):
+        """
+        Override this function if you want a different (or no) command
+        processor to be created when the document is created. By default, it
+        returns an instance of wxCommandProcessor.
+        """
+        return CommandProcessor()
+
+
+    def OnSaveModified(self):
+        """
+        If the document has been modified, prompts the user to ask if the
+        changes should be changed. If the user replies Yes, the Save function
+        is called. If No, the document is marked as unmodified and the
+        function succeeds. If Cancel, the function fails.
+        """
+        if not self.IsModified():
+            return True
+
+        msgTitle = wx.GetApp().GetAppName()
+        if not msgTitle:
+            msgTitle = _("Warning")
+
+        res = wx.MessageBox(_("Save changes to '%s'?") % self.GetPrintableName(),
+                            msgTitle,
+                            wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION,
+                            self.GetDocumentWindow())
+
+        if res == wx.NO:
+            self.Modify(False)
+            return True
+        elif res == wx.YES:
+            return self.Save()
+        else: # elif res == wx.CANCEL:
+            return False
+
+
+    def Draw(context):
+        """
+        Called by printing framework to draw the view.
+        """
+        return True
+
+
+    def AddView(self, view):
+        """
+        If the view is not already in the list of views, adds the view and
+        calls OnChangedViewList.
+        """
+        if not view in self._documentViews:
+            self._documentViews.append(view)
+            self.OnChangedViewList()
+        return True
+
+
+    def RemoveView(self, view):
+        """
+        Removes the view from the document's list of views, and calls
+        OnChangedViewList.
+        """
+        if view in self._documentViews:
+            self._documentViews.remove(view)
+            self.OnChangedViewList()
+        return True
+
+
+    def OnCreate(self, path, flags):
+        """
+        The default implementation calls DeleteContents (an empty
+        implementation) sets the modified flag to false. Override this to
+        supply additional behaviour when the document is closed with Close.
+        """
+        return self.GetDocumentTemplate().CreateView(self, flags)
+
+
+    def OnChangedViewList(self):
+        """
+        Called when a view is added to or deleted from this document. The
+        default implementation saves and deletes the document if no views
+        exist (the last one has just been removed).
+        """
+        if len(self._documentViews) == 0:
+            if self.OnSaveModified():
+                pass # C version does a delete but Python will garbage collect
+
+
+    def UpdateAllViews(self, sender = None, hint = None):
+        """
+        Updates all views. If sender is non-NULL, does not update this view.
+        hint represents optional information to allow a view to optimize its
+        update.
+        """
+        for view in self._documentViews:
+            if view != sender:
+                view.OnUpdate(sender, hint)
+
+
+    def NotifyClosing(self):
+        """
+        Notifies the views that the document is going to close.
+        """
+        for view in self._documentViews:
+            view.OnClosingDocument()
+
+
+    def SetFilename(self, filename, notifyViews = False):
+        """
+        Sets the filename for this document. Usually called by the framework.
+        If notifyViews is true, wxView.OnChangeFilename is called for all
+        views.
+        """
+        self._documentFile = filename
+        if notifyViews:
+            for view in self._documentViews:
+                view.OnChangeFilename()
+
+
+class View(wx.EvtHandler):
+    """
+    The view class can be used to model the viewing and editing component of
+    an application's file-based data. It is part of the document/view
+    framework supported by wxWindows, and cooperates with the wxDocument,
+    wxDocTemplate and wxDocManager classes.
+    """
+
+    def __init__(self):
+        """
+        Constructor. Define your own default constructor to initialize
+        application-specific data.
+        """
+        wx.EvtHandler.__init__(self)
+        self._viewDocument = None
+        self._viewFrame = None
+
+
+    def Destroy(self):
+        """
+        Destructor. Removes itself from the document's list of views.
+        """
+        if self._viewDocument:
+            self._viewDocument.RemoveView(self)
+        wx.EvtHandler.Destroy(self)
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if not self.GetDocument() or not self.GetDocument().ProcessEvent(event):
+            return False
+        else:
+            return True
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return False
+
+
+    def OnActivateView(self, activate, activeView, deactiveView):
+        """
+        Called when a view is activated by means of wxView::Activate. The
+        default implementation does nothing.
+        """
+        pass
+
+
+    def OnClosingDocument(self):
+        """
+        Override this to clean up the view when the document is being closed.
+        The default implementation does nothing.
+        """
+        pass
+
+
+    def OnDraw(self, dc):
+        """
+        Override this to draw the view for the printing framework.  The
+        default implementation does nothing.
+        """
+        pass
+
+
+    def OnPrint(self, dc, info):
+        """
+        Override this to print the view for the printing framework.  The
+        default implementation calls View.OnDraw.
+        """
+        self.OnDraw(dc)
+
+
+    def OnUpdate(self, sender, hint):
+        """
+        Called when the view should be updated. sender is a pointer to the
+        view that sent the update request, or NULL if no single view requested
+        the update (for instance, when the document is opened). hint is as yet
+        unused but may in future contain application-specific information for
+        making updating more efficient.
+        """
+        pass
+
+
+    def OnChangeFilename(self):
+        """
+        Called when the filename has changed. The default implementation
+        constructs a suitable title and sets the title of the view frame (if
+        any).
+        """
+        if self.GetFrame():
+            appName = wx.GetApp().GetAppName()
+            if not self.GetDocument():
+                if appName:
+                    title = appName
+                else:
+                    return
+            else:
+                if appName and not isinstance(self.GetFrame(), DocMDIChildFrame):  # Don't need appname in title for MDI
+                    title = appName + _(" - ")
+                else:
+                    title = ''
+                self.GetFrame().SetTitle(title + self.GetDocument().GetPrintableName())
+
+
+    def GetDocument(self):
+        """
+        Returns the document associated with the view.
+        """
+        return self._viewDocument
+
+
+    def SetDocument(self, doc):
+        """
+        Associates the given document with the view. Normally called by the
+        framework.
+        """
+        self._viewDocument = doc
+        if doc:
+            doc.AddView(self)
+
+
+    def GetViewName(self):
+        """
+        Gets the name associated with the view (passed to the wxDocTemplate
+        constructor). Not currently used by the framework.
+        """
+        return self._viewTypeName
+
+
+    def SetViewName(self, name):
+        """
+        Sets the view type name. Should only be called by the framework.
+        """
+        self._viewTypeName = name
+
+
+    def Close(self, deleteWindow = True):
+        """
+        Closes the view by calling OnClose. If deleteWindow is true, this
+        function should delete the window associated with the view.
+        """
+        if self.OnClose(deleteWindow = deleteWindow):
+            return True
+        else:
+            return False
+
+
+    def Activate(self, activate = True):
+        """
+        Call this from your view frame's OnActivate member to tell the
+        framework which view is currently active. If your windowing system
+        doesn't call OnActivate, you may need to call this function from
+        OnMenuCommand or any place where you know the view must be active, and
+        the framework will need to get the current view.
+
+        The prepackaged view frame wxDocChildFrame calls wxView.Activate from
+        its OnActivate member and from its OnMenuCommand member.
+        """
+        if self.GetDocument() and self.GetDocumentManager():
+            self.OnActivateView(activate, self, self.GetDocumentManager().GetCurrentView())
+            self.GetDocumentManager().ActivateView(self, activate)
+
+
+    def OnClose(self, deleteWindow = True):
+        """
+        Implements closing behaviour. The default implementation calls
+        wxDocument.Close to close the associated document. Does not delete the
+        view. The application may wish to do some cleaning up operations in
+        this function, if a call to wxDocument::Close succeeded. For example,
+        if your application's all share the same window, you need to
+        disassociate the window from the view and perhaps clear the window. If
+        deleteWindow is true, delete the frame associated with the view.
+        """
+        if self.GetDocument():
+            return self.GetDocument().Close()
+        else:
+            return True
+
+
+    def OnCreate(self, doc, flags):
+        """
+        wxDocManager or wxDocument creates a wxView via a wxDocTemplate. Just
+        after the wxDocTemplate creates the wxView, it calls wxView::OnCreate.
+        In its OnCreate member function, the wxView can create a
+        wxDocChildFrame or a derived class. This wxDocChildFrame provides user
+        interface elements to view and/or edit the contents of the wxDocument.
+
+        By default, simply returns true. If the function returns false, the
+        view will be deleted.
+        """
+        return True
+
+
+    def OnCreatePrintout(self):
+        """
+        Returns a wxPrintout object for the purposes of printing. It should
+        create a new object every time it is called; the framework will delete
+        objects it creates.
+
+        By default, this function returns an instance of wxDocPrintout, which
+        prints and previews one page by calling wxView.OnDraw.
+
+        Override to return an instance of a class other than wxDocPrintout.
+        """
+        return DocPrintout(self)
+
+
+    def GetFrame(self):
+        """
+        Gets the frame associated with the view (if any). Note that this
+        "frame" is not a wxFrame at all in the generic MDI implementation
+        which uses the notebook pages instead of the frames and this is why
+        this method returns a wxWindow and not a wxFrame.
+        """
+        return self._viewFrame
+
+
+    def SetFrame(self, frame):
+        """
+        Sets the frame associated with this view. The application should call
+        this if possible, to tell the view about the frame.  See GetFrame for
+        the explanation about the mismatch between the "Frame" in the method
+        name and the type of its parameter.
+        """
+        self._viewFrame = frame
+
+
+    def GetDocumentManager(self):
+        """
+        Returns the document manager instance associated with this view.
+        """
+        if self._viewDocument:
+            return self.GetDocument().GetDocumentManager()
+        else:
+            return None
+
+
+class DocTemplate(wx.Object):
+    """
+    The wxDocTemplate class is used to model the relationship between a
+    document class and a view class.
+    """
+
+
+    def __init__(self, manager, description, filter, dir, ext, docTypeName, viewTypeName, docType, viewType, flags = DEFAULT_TEMPLATE_FLAGS, icon = None):
+        """
+        Constructor. Create instances dynamically near the start of your
+        application after creating a wxDocManager instance, and before doing
+        any document or view operations.
+
+        manager is the document manager object which manages this template.
+
+        description is a short description of what the template is for. This
+        string will be displayed in the file filter list of Windows file
+        selectors.
+
+        filter is an appropriate file filter such as *.txt.
+
+        dir is the default directory to use for file selectors.
+
+        ext is the default file extension (such as txt).
+
+        docTypeName is a name that should be unique for a given type of
+        document, used for gathering a list of views relevant to a
+        particular document.
+
+        viewTypeName is a name that should be unique for a given view.
+
+        docClass is a Python class. If this is not supplied, you will need to
+        derive a new wxDocTemplate class and override the CreateDocument
+        member to return a new document instance on demand.
+
+        viewClass is a Python class. If this is not supplied, you will need to
+        derive a new wxDocTemplate class and override the CreateView member to
+        return a new view instance on demand.
+
+        flags is a bit list of the following:
+        wx.TEMPLATE_VISIBLE The template may be displayed to the user in
+        dialogs.
+
+        wx.TEMPLATE_INVISIBLE The template may not be displayed to the user in
+        dialogs.
+
+        wx.DEFAULT_TEMPLATE_FLAGS Defined as wxTEMPLATE_VISIBLE.
+        """
+        self._docManager = manager
+        self._description = description
+        self._fileFilter = filter
+        self._directory = dir
+        self._defaultExt = ext
+        self._docTypeName = docTypeName
+        self._viewTypeName = viewTypeName
+        self._docType = docType
+        self._viewType = viewType
+        self._flags = flags
+        self._icon = icon
+
+        self._docManager.AssociateTemplate(self)
+
+
+    def GetDefaultExtension(self):
+        """
+        Returns the default file extension for the document data, as passed to
+        the document template constructor.
+        """
+        return self._defaultExt
+
+
+    def SetDefaultExtension(self, defaultExt):
+        """
+        Sets the default file extension.
+        """
+        self._defaultExt = defaultExt
+
+
+    def GetDescription(self):
+        """
+        Returns the text description of this template, as passed to the
+        document template constructor.
+        """
+        return self._description
+
+
+    def SetDescription(self, description):
+        """
+        Sets the template description.
+        """
+        self._description = description
+
+
+    def GetDirectory(self):
+        """
+        Returns the default directory, as passed to the document template
+        constructor.
+        """
+        return self._directory
+
+
+    def SetDirectory(self, dir):
+        """
+        Sets the default directory.
+        """
+        self._directory = dir
+
+
+    def GetDocumentManager(self):
+        """
+        Returns the document manager instance for which this template was
+        created.
+        """
+        return self._docManager
+
+
+    def SetDocumentManager(self, manager):
+        """
+        Sets the document manager instance for which this template was
+        created. Should not be called by the application.
+        """
+        self._docManager = manager
+
+
+    def GetFileFilter(self):
+        """
+        Returns the file filter, as passed to the document template
+        constructor.
+        """
+        return self._fileFilter
+
+
+    def SetFileFilter(self, filter):
+        """
+        Sets the file filter.
+        """
+        self._fileFilter = filter
+
+
+    def GetFlags(self):
+        """
+        Returns the flags, as passed to the document template constructor.
+        (see the constructor description for more details).
+        """
+        return self._flags
+
+
+    def SetFlags(self, flags):
+        """
+        Sets the internal document template flags (see the constructor
+        description for more details).
+        """
+        self._flags = flags
+
+
+    def GetIcon(self):
+        """
+        Returns the icon, as passed to the document template
+        constructor.  This method has been added to wxPython and is
+        not in wxWindows.
+        """
+        return self._icon
+
+
+    def SetIcon(self, flags):
+        """
+        Sets the icon.  This method has been added to wxPython and is not
+        in wxWindows.
+        """
+        self._icon = icon
+
+
+    def GetDocumentType(self):
+        """
+        Returns the Python document class, as passed to the document template
+        constructor.
+        """
+        return self._docType
+
+
+    def GetViewType(self):
+        """
+        Returns the Python view class, as passed to the document template
+        constructor.
+        """
+        return self._viewType
+
+
+    def IsVisible(self):
+        """
+        Returns true if the document template can be shown in user dialogs,
+        false otherwise.
+        """
+        return (self._flags & TEMPLATE_VISIBLE) == TEMPLATE_VISIBLE
+
+
+    def GetDocumentName(self):
+        """
+        Returns the document type name, as passed to the document template
+        constructor.
+        """
+        return self._docTypeName
+
+
+    def GetViewName(self):
+        """
+        Returns the view type name, as passed to the document template
+        constructor.
+        """
+        return self._viewTypeName
+
+
+    def CreateDocument(self, path, flags):
+        """
+        Creates a new instance of the associated document class. If you have
+        not supplied a class to the template constructor, you will need to
+        override this function to return an appropriate document instance.
+        """
+        doc = self._docType()
+        doc.SetFilename(path)
+        doc.SetDocumentTemplate(self)
+        self.GetDocumentManager().AddDocument(doc)
+        doc.SetCommandProcessor(doc.OnCreateCommandProcessor())
+        if doc.OnCreate(path, flags):
+            return doc
+        else:
+            if doc in self.GetDocumentManager().GetDocuments():
+                doc.DeleteAllViews()
+            return None
+
+
+    def CreateView(self, doc, flags):
+        """
+        Creates a new instance of the associated document view. If you have
+        not supplied a class to the template constructor, you will need to
+        override this function to return an appropriate view instance.
+        """
+        view = self._viewType()
+        view.SetDocument(doc)
+        if view.OnCreate(doc, flags):
+            return view
+        else:
+            view.Destroy()
+            return None
+
+
+    def FileMatchesTemplate(self, path):
+        """
+        Returns True if the path's extension matches one of this template's
+        file filter extensions.
+        """
+        ext = FindExtension(path)
+        if not ext: return False
+        return ext in self.GetFileFilter()
+        # return self.GetDefaultExtension() == FindExtension(path)
+
+
+class DocManager(wx.EvtHandler):
+    """
+    The wxDocManager class is part of the document/view framework supported by
+    wxWindows, and cooperates with the wxView, wxDocument and wxDocTemplate
+    classes.
+    """
+
+    def __init__(self, flags = DEFAULT_DOCMAN_FLAGS, initialize = True):
+        """
+        Constructor. Create a document manager instance dynamically near the
+        start of your application before doing any document or view operations.
+
+        flags is used in the Python version to indicate whether the document
+        manager is in DOC_SDI or DOC_MDI mode.
+
+        If initialize is true, the Initialize function will be called to
+        create a default history list object. If you derive from wxDocManager,
+        you may wish to call the base constructor with false, and then call
+        Initialize in your own constructor, to allow your own Initialize or
+        OnCreateFileHistory functions to be called.
+        """
+
+        wx.EvtHandler.__init__(self)
+
+        self._defaultDocumentNameCounter = 1
+        self._flags = flags
+        self._currentView = None
+        self._lastActiveView = None
+        self._maxDocsOpen = 10000
+        self._fileHistory = None
+        self._templates = []
+        self._docs = []
+        self._lastDirectory = ""
+
+        if initialize:
+            self.Initialize()
+
+        wx.EVT_MENU(self, wx.ID_OPEN, self.OnFileOpen)
+        wx.EVT_MENU(self, wx.ID_CLOSE, self.OnFileClose)
+        wx.EVT_MENU(self, wx.ID_CLOSE_ALL, self.OnFileCloseAll)
+        wx.EVT_MENU(self, wx.ID_REVERT, self.OnFileRevert)
+        wx.EVT_MENU(self, wx.ID_NEW, self.OnFileNew)
+        wx.EVT_MENU(self, wx.ID_SAVE, self.OnFileSave)
+        wx.EVT_MENU(self, wx.ID_SAVEAS, self.OnFileSaveAs)
+        wx.EVT_MENU(self, wx.ID_UNDO, self.OnUndo)
+        wx.EVT_MENU(self, wx.ID_REDO, self.OnRedo)
+        wx.EVT_MENU(self, wx.ID_PRINT, self.OnPrint)
+        wx.EVT_MENU(self, wx.ID_PRINT_SETUP, self.OnPrintSetup)
+        wx.EVT_MENU(self, wx.ID_PREVIEW, self.OnPreview)
+
+        wx.EVT_UPDATE_UI(self, wx.ID_OPEN, self.OnUpdateFileOpen)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE, self.OnUpdateFileClose)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE_ALL, self.OnUpdateFileCloseAll)
+        wx.EVT_UPDATE_UI(self, wx.ID_REVERT, self.OnUpdateFileRevert)
+        wx.EVT_UPDATE_UI(self, wx.ID_NEW, self.OnUpdateFileNew)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVE, self.OnUpdateFileSave)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVEAS, self.OnUpdateFileSaveAs)
+        wx.EVT_UPDATE_UI(self, wx.ID_UNDO, self.OnUpdateUndo)
+        wx.EVT_UPDATE_UI(self, wx.ID_REDO, self.OnUpdateRedo)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT, self.OnUpdatePrint)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT_SETUP, self.OnUpdatePrintSetup)
+        wx.EVT_UPDATE_UI(self, wx.ID_PREVIEW, self.OnUpdatePreview)
+
+
+    def Destroy(self):
+        """
+        Destructor.
+        """
+        self.Clear()
+        wx.EvtHandler.Destroy(self)
+
+
+    def GetFlags(self):
+        """
+        Returns the document manager's flags.  This method has been
+        added to wxPython and is not in wxWindows.
+        """
+        return self._flags
+
+
+    def CloseDocument(self, doc, force = True):
+        """
+        Closes the specified document.
+        """
+        if doc.Close() or force:
+            doc.DeleteAllViews()
+            if doc in self._docs:
+                doc.Destroy()
+            return True
+        return False
+
+
+    def CloseDocuments(self, force = True):
+        """
+        Closes all currently opened documents.
+        """
+        for document in self._docs[::-1]:  # Close in lifo (reverse) order.  We clone the list to make sure we go through all docs even as they are deleted
+            if not self.CloseDocument(document, force):
+                return False
+            document.DeleteAllViews() # Implicitly delete the document when the last view is removed
+        return True
+
+
+    def Clear(self, force = True):
+        """
+        Closes all currently opened document by callling CloseDocuments and
+        clears the document manager's templates.
+        """
+        if not self.CloseDocuments(force):
+            return False
+        self._templates = []
+        return True
+
+
+    def Initialize(self):
+        """
+        Initializes data; currently just calls OnCreateFileHistory. Some data
+        cannot always be initialized in the constructor because the programmer
+        must be given the opportunity to override functionality. In fact
+        Initialize is called from the wxDocManager constructor, but this can
+        be vetoed by passing false to the second argument, allowing the
+        derived class's constructor to call Initialize, possibly calling a
+        different OnCreateFileHistory from the default.
+
+        The bottom line: if you're not deriving from Initialize, forget it and
+        construct wxDocManager with no arguments.
+        """
+        self.OnCreateFileHistory()
+        return True
+
+
+    def OnCreateFileHistory(self):
+        """
+        A hook to allow a derived class to create a different type of file
+        history. Called from Initialize.
+        """
+        self._fileHistory = wx.FileHistory()
+
+
+    def OnFileClose(self, event):
+        """
+        Closes and deletes the currently active document.
+        """
+        doc = self.GetCurrentDocument()
+        if doc:
+            doc.DeleteAllViews()
+            if doc in self._docs:
+                self._docs.remove(doc)
+
+
+    def OnFileCloseAll(self, event):
+        """
+        Closes and deletes all the currently opened documents.
+        """
+        return self.CloseDocuments(force = False)
+
+
+    def OnFileNew(self, event):
+        """
+        Creates a new document and reads in the selected file.
+        """
+        self.CreateDocument('', DOC_NEW)
+
+
+    def OnFileOpen(self, event):
+        """
+        Creates a new document and reads in the selected file.
+        """
+        if not self.CreateDocument('', 0):
+            self.OnOpenFileFailure()
+
+
+    def OnFileRevert(self, event):
+        """
+        Reverts the current document by calling wxDocument.Save for the current
+        document.
+        """
+        doc = self.GetCurrentDocument()
+        if not doc:
+            return
+        doc.Revert()
+
+
+    def OnFileSave(self, event):
+        """
+        Saves the current document by calling wxDocument.Save for the current
+        document.
+        """
+        doc = self.GetCurrentDocument()
+        if not doc:
+            return
+        doc.Save()
+
+
+    def OnFileSaveAs(self, event):
+        """
+        Calls wxDocument.SaveAs for the current document.
+        """
+        doc = self.GetCurrentDocument()
+        if not doc:
+            return
+        doc.SaveAs()
+
+
+    def OnPrint(self, event):
+        """
+        Prints the current document by calling its View's OnCreatePrintout
+        method.
+        """
+        view = self.GetCurrentView()
+        if not view:
+            return
+
+        printout = view.OnCreatePrintout()
+        if printout:
+            pdd = wx.PrintDialogData()
+            printer = wx.Printer(pdd)
+            printer.Print(view.GetFrame(), printout) # , True)
+
+
+    def OnPrintSetup(self, event):
+        """
+        Presents the print setup dialog.
+        """
+        view = self.GetCurrentView()
+        if view:
+            parentWin = view.GetFrame()
+        else:
+            parentWin = wx.GetApp().GetTopWindow()
+
+        data = wx.PrintDialogData()
+        printDialog = wx.PrintDialog(parentWin, data)
+        printDialog.GetPrintDialogData().SetSetupDialog(True)
+        printDialog.ShowModal()
+        # TODO: Confirm that we don't have to remember PrintDialogData
+
+
+    def OnPreview(self, event):
+        """
+        Previews the current document by calling its View's OnCreatePrintout
+        method.
+        """
+        view = self.GetCurrentView()
+        if not view:
+            return
+
+        printout = view.OnCreatePrintout()
+        if printout:
+            # Pass two printout objects: for preview, and possible printing.
+            preview = wx.PrintPreview(printout, view.OnCreatePrintout())
+            # wxWindows source doesn't use base frame's pos, size, and icon, but did it this way so it would work like MS Office etc.
+            mimicFrame =  wx.GetApp().GetTopWindow()
+            frame = wx.PreviewFrame(preview, mimicFrame, _("Print Preview"), mimicFrame.GetPosition(), mimicFrame.GetSize())
+            frame.SetIcon(mimicFrame.GetIcon())
+            frame.SetTitle(mimicFrame.GetTitle() + _(" - Preview"))
+            frame.Initialize()
+            frame.Show(True)
+
+
+    def OnUndo(self, event):
+        """
+        Issues an Undo command to the current document's command processor.
+        """
+        doc = self.GetCurrentDocument()
+        if not doc:
+            return
+        if doc.GetCommandProcessor():
+            doc.GetCommandProcessor().Undo()
+
+
+    def OnRedo(self, event):
+        """
+        Issues a Redo command to the current document's command processor.
+        """
+        doc = self.GetCurrentDocument()
+        if not doc:
+            return
+        if doc.GetCommandProcessor():
+            doc.GetCommandProcessor().Redo()
+
+
+    def OnUpdateFileOpen(self, event):
+        """
+        Updates the user interface for the File Open command.
+        """
+        event.Enable(True)
+
+
+    def OnUpdateFileClose(self, event):
+        """
+        Updates the user interface for the File Close command.
+        """
+        event.Enable(self.GetCurrentDocument() != None)
+
+
+    def OnUpdateFileCloseAll(self, event):
+        """
+        Updates the user interface for the File Close All command.
+        """
+        event.Enable(self.GetCurrentDocument() != None)
+
+
+    def OnUpdateFileRevert(self, event):
+        """
+        Updates the user interface for the File Revert command.
+        """
+        event.Enable(self.GetCurrentDocument() != None)
+
+
+    def OnUpdateFileNew(self, event):
+        """
+        Updates the user interface for the File New command.
+        """
+        return True
+
+
+    def OnUpdateFileSave(self, event):
+        """
+        Updates the user interface for the File Save command.
+        """
+        doc = self.GetCurrentDocument()
+        event.Enable(doc != None and doc.IsModified())
+
+
+    def OnUpdateFileSaveAs(self, event):
+        """
+        Updates the user interface for the File Save As command.
+        """
+        event.Enable(self.GetCurrentDocument() != None)
+
+
+    def OnUpdateUndo(self, event):
+        """
+        Updates the user interface for the Undo command.
+        """
+        doc = self.GetCurrentDocument()
+        event.Enable(doc != None and doc.GetCommandProcessor() != None and doc.GetCommandProcessor().CanUndo())
+        if doc and doc.GetCommandProcessor():
+            doc.GetCommandProcessor().SetMenuStrings()
+        else:
+            event.SetText(_("Undo") + '\t' + _('Ctrl+Z'))
+
+
+    def OnUpdateRedo(self, event):
+        """
+        Updates the user interface for the Redo command.
+        """
+        doc = self.GetCurrentDocument()
+        event.Enable(doc != None and doc.GetCommandProcessor() != None and doc.GetCommandProcessor().CanRedo())
+        if doc and doc.GetCommandProcessor():
+            doc.GetCommandProcessor().SetMenuStrings()
+        else:
+            event.SetText(_("Redo") + '\t' + _('Ctrl+Y'))
+
+
+    def OnUpdatePrint(self, event):
+        """
+        Updates the user interface for the Print command.
+        """
+        event.Enable(self.GetCurrentDocument() != None)
+
+
+    def OnUpdatePrintSetup(self, event):
+        """
+        Updates the user interface for the Print Setup command.
+        """
+        return True
+
+
+    def OnUpdatePreview(self, event):
+        """
+        Updates the user interface for the Print Preview command.
+        """
+        event.Enable(self.GetCurrentDocument() != None)
+
+
+    def GetCurrentView(self):
+        """
+        Returns the currently active view.
+        """
+        if self._currentView:
+            return self._currentView
+        if len(self._docs) == 1:
+            return self._docs[0].GetFirstView()
+        return None
+
+
+    def GetLastActiveView(self):
+        """
+        Returns the last active view.  This is used in the SDI framework where dialogs can be mistaken for a view
+        and causes the framework to deactivete the current view.  This happens when something like a custom dialog box used
+        to operate on the current view is shown.
+        """
+        if len(self._docs) >= 1:
+            return self._lastActiveView
+        else:
+            return None
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        view = self.GetCurrentView()
+        if view:
+            if view.ProcessEvent(event):
+                return True
+        id = event.GetId()
+        if id == wx.ID_OPEN:
+            self.OnFileOpen(event)
+            return True
+        elif id == wx.ID_CLOSE:
+            self.OnFileClose(event)
+            return True
+        elif id == wx.ID_CLOSE_ALL:
+            self.OnFileCloseAll(event)
+            return True
+        elif id == wx.ID_REVERT:
+            self.OnFileRevert(event)
+            return True
+        elif id == wx.ID_NEW:
+            self.OnFileNew(event)
+            return True
+        elif id == wx.ID_SAVE:
+            self.OnFileSave(event)
+            return True
+        elif id == wx.ID_SAVEAS:
+            self.OnFileSaveAs(event)
+            return True
+        elif id == wx.ID_UNDO:
+            self.OnUndo(event)
+            return True
+        elif id == wx.ID_REDO:
+            self.OnRedo(event)
+            return True
+        elif id == wx.ID_PRINT:
+            self.OnPrint(event)
+            return True
+        elif id == wx.ID_PRINT_SETUP:
+            self.OnPrintSetup(event)
+            return True
+        elif id == wx.ID_PREVIEW:
+            self.OnPreview(event)
+            return True
+        else:
+            return False
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        id = event.GetId()
+        view = self.GetCurrentView()
+        if view:
+            if view.ProcessUpdateUIEvent(event):
+                return True
+        if id == wx.ID_OPEN:
+            self.OnUpdateFileOpen(event)
+            return True
+        elif id == wx.ID_CLOSE:
+            self.OnUpdateFileClose(event)
+            return True
+        elif id == wx.ID_CLOSE_ALL:
+            self.OnUpdateFileCloseAll(event)
+            return True
+        elif id == wx.ID_REVERT:
+            self.OnUpdateFileRevert(event)
+            return True
+        elif id == wx.ID_NEW:
+            self.OnUpdateFileNew(event)
+            return True
+        elif id == wx.ID_SAVE:
+            self.OnUpdateFileSave(event)
+            return True
+        elif id == wx.ID_SAVEAS:
+            self.OnUpdateFileSaveAs(event)
+            return True
+        elif id == wx.ID_UNDO:
+            self.OnUpdateUndo(event)
+            return True
+        elif id == wx.ID_REDO:
+            self.OnUpdateRedo(event)
+            return True
+        elif id == wx.ID_PRINT:
+            self.OnUpdatePrint(event)
+            return True
+        elif id == wx.ID_PRINT_SETUP:
+            self.OnUpdatePrintSetup(event)
+            return True
+        elif id == wx.ID_PREVIEW:
+            self.OnUpdatePreview(event)
+            return True
+        else:
+            return False
+
+
+    def CreateDocument(self, path, flags = 0):
+        """
+        Creates a new document in a manner determined by the flags parameter,
+        which can be:
+
+        wx.lib.docview.DOC_NEW Creates a fresh document.
+        wx.lib.docview.DOC_SILENT Silently loads the given document file.
+
+        If wx.lib.docview.DOC_NEW is present, a new document will be created and returned,
+        possibly after asking the user for a template to use if there is more
+        than one document template. If wx.lib.docview.DOC_SILENT is present, a new document
+        will be created and the given file loaded into it. If neither of these
+        flags is present, the user will be presented with a file selector for
+        the file to load, and the template to use will be determined by the
+        extension (Windows) or by popping up a template choice list (other
+        platforms).
+
+        If the maximum number of documents has been reached, this function
+        will delete the oldest currently loaded document before creating a new
+        one.
+
+        wxPython version supports the document manager's wx.lib.docview.DOC_OPEN_ONCE flag.
+        """
+        templates = []
+        for temp in self._templates:
+            if temp.IsVisible():
+                templates.append(temp)
+        if len(templates) == 0:
+            return None
+
+        if len(self.GetDocuments()) >= self._maxDocsOpen:
+           doc = self.GetDocuments()[0]
+           if not self.CloseDocument(doc, False):
+               return None
+
+        if flags & DOC_NEW:
+            if len(templates) == 1:
+                temp = templates[0]
+                newDoc = temp.CreateDocument(path, flags)
+                if newDoc:
+                    newDoc.SetDocumentName(temp.GetDocumentName())
+                    newDoc.SetDocumentTemplate(temp)
+                    newDoc.OnNewDocument()
+                return newDoc
+
+            temp = self.SelectDocumentType(templates)
+            if temp:
+                newDoc = temp.CreateDocument(path, flags)
+                if newDoc:
+                    newDoc.SetDocumentName(temp.GetDocumentName())
+                    newDoc.SetDocumentTemplate(temp)
+                    newDoc.OnNewDocument()
+                return newDoc
+            else:
+                return None
+
+        # Existing document
+        if self.GetFlags() & DOC_OPEN_ONCE:
+            for document in self._docs:
+                if document.GetFilename() == path:
+                    firstView = document.GetFirstView()
+                    if firstView and firstView.GetFrame():
+                        firstView.GetFrame().SetFocus()  # Not in wxWindows code but useful nonetheless
+                        if hasattr(firstView.GetFrame(), "IsIconized") and firstView.GetFrame().IsIconized():  # Not in wxWindows code but useful nonetheless
+                            firstView.GetFrame().Iconize(False)
+                    return None
+
+        if flags & DOC_SILENT:
+            temp = self.FindTemplateForPath(path)
+        else:
+            temp, path = self.SelectDocumentPath(templates, path, flags)
+
+        if temp:
+            newDoc = temp.CreateDocument(path, flags)
+            if newDoc:
+                newDoc.SetDocumentName(temp.GetDocumentName())
+                newDoc.SetDocumentTemplate(temp)
+                if not newDoc.OnOpenDocument(path):
+                    newDoc.DeleteAllViews()  # Implicitly deleted by DeleteAllViews
+                    newDoc.GetFirstView().GetFrame().Destroy() # DeleteAllViews doesn't get rid of the frame, so we'll explicitly destroy it.
+                    return None
+                self.AddFileToHistory(path)
+            return newDoc
+
+        return None
+
+
+    def CreateView(self, document, flags = 0):
+        """
+        Creates a new view for the given document. If more than one view is
+        allowed for the document (by virtue of multiple templates mentioning
+        the same document type), a choice of view is presented to the user.
+        """
+        templates = []
+        for temp in self._templates:
+            if temp.IsVisible():
+                if temp.GetDocumentName() == doc.GetDocumentName():
+                    templates.append(temp)
+        if len(templates) == 0:
+            return None
+
+        if len(templates) == 1:
+            temp = templates[0]
+            view = temp.CreateView(doc, flags)
+            if view:
+                view.SetViewName(temp.GetViewName())
+            return view
+
+        temp = SelectViewType(templates)
+        if temp:
+            view = temp.CreateView(doc, flags)
+            if view:
+                view.SetViewName(temp.GetViewName())
+            return view
+        else:
+            return None
+
+
+    def DeleteTemplate(self, template, flags):
+        """
+        Placeholder, not yet implemented in wxWindows.
+        """
+        pass
+
+
+    def FlushDoc(self, doc):
+        """
+        Placeholder, not yet implemented in wxWindows.
+        """
+        return False
+
+
+    def MatchTemplate(self, path):
+        """
+        Placeholder, not yet implemented in wxWindows.
+        """
+        return None
+
+
+    def GetCurrentDocument(self):
+        """
+        Returns the document associated with the currently active view (if any).
+        """
+        view = self.GetCurrentView()
+        if view:
+            return view.GetDocument()
+        else:
+            return None
+
+
+    def MakeDefaultName(self):
+        """
+        Returns a suitable default name. This is implemented by appending an
+        integer counter to the string "Untitled" and incrementing the counter.
+        """
+        name = _("Untitled %d") % self._defaultDocumentNameCounter
+        self._defaultDocumentNameCounter = self._defaultDocumentNameCounter + 1
+        return name
+
+
+    def MakeFrameTitle(self):
+        """
+        Returns a suitable title for a document frame. This is implemented by
+        appending the document name to the application name.
+        """
+        appName = wx.GetApp().GetAppName()
+        if not doc:
+            title = appName
+        else:
+            docName = doc.GetPrintableName()
+            title = docName + _(" - ") + appName
+        return title
+
+
+    def AddFileToHistory(self, fileName):
+        """
+        Adds a file to the file history list, if we have a pointer to an
+        appropriate file menu.
+        """
+        if self._fileHistory:
+            self._fileHistory.AddFileToHistory(fileName)
+
+
+    def RemoveFileFromHistory(self, i):
+        """
+        Removes a file from the file history list, if we have a pointer to an
+        appropriate file menu.
+        """
+        if self._fileHistory:
+            self._fileHistory.RemoveFileFromHistory(i)
+
+
+    def GetFileHistory(self):
+        """
+        Returns the file history.
+        """
+        return self._fileHistory
+
+
+    def GetHistoryFile(self, i):
+        """
+        Returns the file at index i from the file history.
+        """
+        if self._fileHistory:
+            return self._fileHistory.GetHistoryFile(i)
+        else:
+            return None
+
+
+    def FileHistoryUseMenu(self, menu):
+        """
+        Use this menu for appending recently-visited document filenames, for
+        convenient access. Calling this function with a valid menu enables the
+        history list functionality.
+
+        Note that you can add multiple menus using this function, to be
+        managed by the file history object.
+        """
+        if self._fileHistory:
+            self._fileHistory.UseMenu(menu)
+
+
+    def FileHistoryRemoveMenu(self, menu):
+        """
+        Removes the given menu from the list of menus managed by the file
+        history object.
+        """
+        if self._fileHistory:
+            self._fileHistory.RemoveMenu(menu)
+
+
+    def FileHistoryLoad(self, config):
+        """
+        Loads the file history from a config object.
+        """
+        if self._fileHistory:
+            self._fileHistory.Load(config)
+
+
+    def FileHistorySave(self, config):
+        """
+        Saves the file history into a config object. This must be called
+        explicitly by the application.
+        """
+        if self._fileHistory:
+            self._fileHistory.Save(config)
+
+
+    def FileHistoryAddFilesToMenu(self, menu = None):
+        """
+        Appends the files in the history list, to all menus managed by the
+        file history object.
+
+        If menu is specified, appends the files in the history list to the
+        given menu only.
+        """
+        if self._fileHistory:
+            if menu:
+                self._fileHistory.AddFilesToThisMenu(menu)
+            else:
+                self._fileHistory.AddFilesToMenu()
+
+
+    def GetHistoryFilesCount(self):
+        """
+        Returns the number of files currently stored in the file history.
+        """
+        if self._fileHistory:
+            return self._fileHistory.GetNoHistoryFiles()
+        else:
+            return 0
+
+
+    def FindTemplateForPath(self, path):
+        """
+        Given a path, try to find template that matches the extension. This is
+        only an approximate method of finding a template for creating a
+        document.
+        """
+        for temp in self._templates:
+            if temp.FileMatchesTemplate(path):
+                return temp
+        return None
+
+
+    def FindSuitableParent(self):
+        """
+        Returns a parent frame or dialog, either the frame with the current
+        focus or if there is no current focus the application's top frame.
+        """
+        parent = wx.GetApp().GetTopWindow()
+        focusWindow = wx.Window_FindFocus()
+        if focusWindow:
+            while focusWindow and not isinstance(focusWindow, wx.Dialog) and not isinstance(focusWindow, wx.Frame):
+                focusWindow = focusWindow.GetParent()
+            if focusWindow:
+                parent = focusWindow
+        return parent
+
+
+    def SelectDocumentPath(self, templates, flags, save):
+        """
+        Under Windows, pops up a file selector with a list of filters
+        corresponding to document templates. The wxDocTemplate corresponding
+        to the selected file's extension is returned.
+
+        On other platforms, if there is more than one document template a
+        choice list is popped up, followed by a file selector.
+
+        This function is used in wxDocManager.CreateDocument.
+        """
+        if wx.Platform == "__WXMSW__" or wx.Platform == "__WXGTK__" or wx.Platform == "__WXMAC__":
+            allfilter = ''
+            descr = ''
+            for temp in templates:
+                if temp.IsVisible():
+                    if len(descr) > 0:
+                        descr = descr + _('|')
+                        allfilter = allfilter + _(';')
+                    descr = descr + temp.GetDescription() + _(" (") + temp.GetFileFilter() + _(") |") + temp.GetFileFilter()  # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk
+                    allfilter = allfilter + temp.GetFileFilter()
+            descr = _("All") + _(" (") + allfilter + _(") |") + allfilter + _('|') + descr  # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk
+        else:
+            descr = _("*.*")
+
+        path = wx.FileSelector(_("Select a File"),
+                               self._lastDirectory,
+                               _(""),
+                               wildcard = descr,
+                               flags = wx.HIDE_READONLY,
+                               parent = self.FindSuitableParent())
+        if path:
+            if not FileExists(path):
+                msgTitle = wx.GetApp().GetAppName()
+                if not msgTitle:
+                    msgTitle = _("File Error")
+                    wx.MessageBox("Could not open '%s'." % FileNameFromPath(path),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          parent)
+                    return (None, None)
+            self._lastDirectory = PathOnly(path)
+
+            theTemplate = self.FindTemplateForPath(path)
+            return (theTemplate, path)
+
+        return (None, None)
+
+
+    def OnOpenFileFailure(self):
+        """
+        Called when there is an error opening a file.
+        """
+        pass
+
+
+    def SelectDocumentType(self, temps, sort = False):
+        """
+        Returns a document template by asking the user (if there is more than
+        one template). This function is used in wxDocManager.CreateDocument.
+
+        Parameters
+
+        templates - list of templates from which to choose a desired template.
+
+        sort - If more than one template is passed in in templates, then this
+        parameter indicates whether the list of templates that the user will
+        have to choose from is sorted or not when shown the choice box dialog.
+        Default is false.
+        """
+        templates = []
+        for temp in temps:
+            if temp.IsVisible():
+                want = True
+                for temp2 in templates:
+                    if temp.GetDocumentName() == temp2.GetDocumentName() and temp.GetViewName() == temp2.GetViewName():
+                        want = False
+                        break
+                if want:
+                    templates.append(temp)
+
+        if len(templates) == 0:
+            return None
+        elif len(templates) == 1:
+            return template[0]
+
+        if sort:
+            def tempcmp(a, b):
+                return cmp(a.GetDescription(), b.GetDescription())
+            templates.sort(tempcmp)
+
+        strings = []
+        for temp in templates:
+            strings.append(temp.GetDescription())
+
+        res = wx.GetSingleChoiceIndex(_("Select a document type:"),
+                                      _("Documents"),
+                                      strings,
+                                      self.FindSuitableParent())
+        if res == -1:
+            return None
+        return templates[res]
+
+
+    def SelectViewType(self, temps, sort = False):
+        """
+        Returns a document template by asking the user (if there is more than one template), displaying a list of valid views. This function is used in wxDocManager::CreateView. The dialog normally will not appear because the array of templates only contains those relevant to the document in question, and often there will only be one such.
+        """
+        templates = []
+        strings = []
+        for temp in temps:
+            if temp.IsVisible() and temp.GetViewTypeName():
+                if temp.GetViewName() not in strings:
+                    templates.append(temp)
+                    strings.append(temp.GetViewTypeName())
+
+        if len(templates) == 0:
+            return None
+        elif len(templates) == 1:
+            return templates[0]
+
+        if sort:
+            def tempcmp(a, b):
+                return cmp(a.GetViewTypeName(), b.GetViewTypeName())
+            templates.sort(tempcmp)
+
+        res = wx.GetSingleChoiceIndex(_("Select a document view:"),
+                                      _("Views"),
+                                      strings,
+                                      self.FindSuitableParent())
+        if res == -1:
+            return None
+        return templates[res]
+
+
+    def GetTemplates(self):
+        """
+        Returns the document manager's template list.  This method has been added to
+        wxPython and is not in wxWindows.
+        """
+        return self._templates
+
+
+    def AssociateTemplate(self, docTemplate):
+        """
+        Adds the template to the document manager's template list.
+        """
+        if docTemplate not in self._templates:
+            self._templates.append(docTemplate)
+
+
+    def DisassociateTemplate(self, docTemplate):
+        """
+        Removes the template from the list of templates.
+        """
+        self._templates.remove(docTemplate)
+
+
+    def AddDocument(self, document):
+        """
+        Adds the document to the list of documents.
+        """
+        if document not in self._docs:
+            self._docs.append(document)
+
+
+    def RemoveDocument(self, doc):
+        """
+        Removes the document from the list of documents.
+        """
+        if doc in self._docs:
+            self._docs.remove(doc)
+
+
+    def ActivateView(self, view, activate = True, deleting = False):
+        """
+        Sets the current view.
+        """
+        if activate:
+            self._currentView = view
+            self._lastActiveView = view
+        else:
+            self._currentView = None
+
+
+    def GetMaxDocsOpen(self):
+        """
+        Returns the number of documents that can be open simultaneously.
+        """
+        return self._maxDocsOpen
+
+
+    def SetMaxDocsOpen(self, maxDocsOpen):
+        """
+        Sets the maximum number of documents that can be open at a time. By
+        default, this is 10,000. If you set it to 1, existing documents will
+        be saved and deleted when the user tries to open or create a new one
+        (similar to the behaviour of Windows Write, for example). Allowing
+        multiple documents gives behaviour more akin to MS Word and other
+        Multiple Document Interface applications.
+        """
+        self._maxDocsOpen = maxDocsOpen
+
+
+    def GetDocuments(self):
+        """
+        Returns the list of documents.
+        """
+        return self._docs
+
+
+class DocParentFrame(wx.Frame):
+    """
+    The wxDocParentFrame class provides a default top-level frame for
+    applications using the document/view framework. This class can only be
+    used for SDI (not MDI) parent frames.
+
+    It cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplates
+    classes.
+    """
+
+    def __init__(self, manager, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"):
+        """
+        Constructor.  Note that the event table must be rebuilt for the
+        frame since the EvtHandler is not virtual.
+        """
+        wx.Frame.__init__(self, frame, id, title, pos, size, style)
+        self._docManager = manager
+
+        wx.EVT_CLOSE(self, self.OnCloseWindow)
+
+        wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit)
+        wx.EVT_MENU_RANGE(self, wx.ID_FILE1, wx.ID_FILE9, self.OnMRUFile)
+
+        wx.EVT_MENU(self, wx.ID_NEW, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_OPEN, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_CLOSE_ALL, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_CLOSE, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_REVERT, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_SAVE, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_SAVEAS, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_UNDO, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_REDO, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PRINT, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PRINT_SETUP, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PREVIEW, self.ProcessEvent)
+
+        wx.EVT_UPDATE_UI(self, wx.ID_NEW, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_OPEN, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE_ALL, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_REVERT, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVE, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVEAS, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_UNDO, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_REDO, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT_SETUP, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PREVIEW, self.ProcessUpdateUIEvent)
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return self._docManager and self._docManager.ProcessEvent(event)
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return self._docManager and self._docManager.ProcessUpdateUIEvent(event)
+
+
+    def OnExit(self, event):
+        """
+        Called when File/Exit is chosen and closes the window.
+        """
+        self.Close()
+
+
+    def OnMRUFile(self, event):
+        """
+        Opens the appropriate file when it is selected from the file history
+        menu.
+        """
+        n = event.GetId() - wx.ID_FILE1
+        filename = self._docManager.GetHistoryFile(n)
+        if filename:
+            self._docManager.CreateDocument(filename, DOC_SILENT)
+        else:
+            self._docManager.RemoveFileFromHistory(n)
+            msgTitle = wx.GetApp().GetAppName()
+            if not msgTitle:
+                msgTitle = _("File Error")
+            wx.MessageBox("The file '%s' doesn't exist and couldn't be opened.\nIt has been removed from the most recently used files list" % FileNameFromPath(file),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          self)
+
+
+    def OnCloseWindow(self, event):
+        """
+        Deletes all views and documents. If no user input cancelled the
+        operation, the frame will be destroyed and the application will exit.
+        """
+        if self._docManager.Clear(not event.CanVeto()):
+            self.Destroy()
+        else:
+            event.Veto()
+
+
+class DocChildFrame(wx.Frame):
+    """
+    The wxDocChildFrame class provides a default frame for displaying
+    documents on separate windows. This class can only be used for SDI (not
+    MDI) child frames.
+
+    The class is part of the document/view framework supported by wxWindows,
+    and cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplate
+    classes.
+    """
+
+
+    def __init__(self, doc, view, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"):
+        """
+        Constructor.  Note that the event table must be rebuilt for the
+        frame since the EvtHandler is not virtual.
+        """
+        wx.Frame.__init__(self, frame, id, title, pos, size, style, name)
+        wx.EVT_ACTIVATE(self, self.OnActivate)
+        wx.EVT_CLOSE(self, self.OnCloseWindow)
+        self._childDocument = doc
+        self._childView = view
+        if view:
+            view.SetFrame(self)
+
+        wx.EVT_MENU(self, wx.ID_NEW, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_OPEN, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_CLOSE_ALL, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_CLOSE, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_REVERT, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_SAVE, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_SAVEAS, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_UNDO, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_REDO, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PRINT, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PRINT_SETUP, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PREVIEW, self.ProcessEvent)
+
+        wx.EVT_UPDATE_UI(self, wx.ID_NEW, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_OPEN, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE_ALL, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_REVERT, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVE, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVEAS, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_UNDO, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_REDO, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT_SETUP, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PREVIEW, self.ProcessUpdateUIEvent)
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if self._childView:
+            self._childView.Activate(True)
+        if not self._childView or not self._childView.ProcessEvent(event):
+            # IsInstance not working, but who cares just send all the commands up since this isn't a real ProcessEvent like wxWindows
+            # if not isinstance(event, wx.CommandEvent) or not self.GetParent() or not self.GetParent().ProcessEvent(event):
+            if not self.GetParent() or not self.GetParent().ProcessEvent(event):
+                return False
+            else:
+                return True
+        else:
+            return True
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if self.GetParent():
+            self.GetParent().ProcessUpdateUIEvent(event)
+        else:
+            return False
+
+
+    def OnActivate(self, event):
+        """
+        Activates the current view.
+        """
+        # wx.Frame.OnActivate(event)  This is in the wxWindows docview demo but there is no such method in wxPython, so do a Raise() instead
+        if self._childView:
+            self._childView.Activate(event.GetActive())
+
+
+    def OnCloseWindow(self, event):
+        """
+        Closes and deletes the current view and document.
+        """
+        if self._childView:
+            ans = False
+            if not event.CanVeto():
+                ans = True
+            else:
+                ans = self._childView.Close(deleteWindow = False)
+
+            if ans:
+                self._childView.Activate(False)
+                self._childView.Destroy()
+                self._childView = None
+                if self._childDocument:
+                    self._childDocument.Destroy()  # This isn't in the wxWindows codebase but the document needs to be disposed of somehow
+                    self._childDocument = None
+                self.Destroy()
+            else:
+                event.Veto()
+        else:
+            event.Veto()
+
+
+    def GetDocument(self):
+        """
+        Returns the document associated with this frame.
+        """
+        return self._childDocument
+
+
+    def SetDocument(self, document):
+        """
+        Sets the document for this frame.
+        """
+        self._childDocument = document
+
+
+    def GetView(self):
+        """
+        Returns the view associated with this frame.
+        """
+        return self._childView
+
+
+    def SetView(self, view):
+        """
+        Sets the view for this frame.
+        """
+        self._childView = view
+
+
+class DocMDIParentFrame(wx.MDIParentFrame):
+    """
+    The wxDocMDIParentFrame class provides a default top-level frame for
+    applications using the document/view framework. This class can only be
+    used for MDI parent frames.
+
+    It cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplate
+    classes.
+    """
+
+
+    def __init__(self, manager, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"):
+        """
+        Constructor.  Note that the event table must be rebuilt for the
+        frame since the EvtHandler is not virtual.
+        """
+        wx.MDIParentFrame.__init__(self, frame, id, title, pos, size, style, name)
+        self._docManager = manager
+
+        wx.EVT_CLOSE(self, self.OnCloseWindow)
+
+        wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit)
+        wx.EVT_MENU_RANGE(self, wx.ID_FILE1, wx.ID_FILE9, self.OnMRUFile)
+
+        wx.EVT_MENU(self, wx.ID_NEW, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_OPEN, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_CLOSE_ALL, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_CLOSE, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_REVERT, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_SAVE, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_SAVEAS, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_UNDO, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_REDO, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PRINT, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PRINT_SETUP, self.ProcessEvent)
+        wx.EVT_MENU(self, wx.ID_PREVIEW, self.ProcessEvent)
+
+        wx.EVT_UPDATE_UI(self, wx.ID_NEW, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_OPEN, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE_ALL, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLOSE, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_REVERT, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVE, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SAVEAS, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_UNDO, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_REDO, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PRINT_SETUP, self.ProcessUpdateUIEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PREVIEW, self.ProcessUpdateUIEvent)
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return self._docManager and self._docManager.ProcessEvent(event)
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return self._docManager and self._docManager.ProcessUpdateUIEvent(event)
+
+
+    def OnExit(self, event):
+        """
+        Called when File/Exit is chosen and closes the window.
+        """
+        self.Close()
+
+
+    def OnMRUFile(self, event):
+        """
+        Opens the appropriate file when it is selected from the file history
+        menu.
+        """
+        n = event.GetId() - wx.ID_FILE1
+        filename = self._docManager.GetHistoryFile(n)
+        if filename:
+            self._docManager.CreateDocument(filename, DOC_SILENT)
+        else:
+            self._docManager.RemoveFileFromHistory(n)
+            msgTitle = wx.GetApp().GetAppName()
+            if not msgTitle:
+                msgTitle = _("File Error")
+            wx.MessageBox("The file '%s' doesn't exist and couldn't be opened.\nIt has been removed from the most recently used files list" % FileNameFromPath(file),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          self)
+
+
+    def OnCloseWindow(self, event):
+        """
+        Deletes all views and documents. If no user input cancelled the
+        operation, the frame will be destroyed and the application will exit.
+        """
+        if self._docManager.Clear(not event.CanVeto()):
+            self.Destroy()
+        else:
+            event.Veto()
+
+
+class DocMDIChildFrame(wx.MDIChildFrame):
+    """
+    The wxDocMDIChildFrame class provides a default frame for displaying
+    documents on separate windows. This class can only be used for MDI child
+    frames.
+
+    The class is part of the document/view framework supported by wxWindows,
+    and cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplate
+    classes.
+    """
+
+
+    def __init__(self, doc, view, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"):
+        """
+        Constructor.  Note that the event table must be rebuilt for the
+        frame since the EvtHandler is not virtual.
+        """
+        wx.MDIChildFrame.__init__(self, frame, id, title, pos, size, style, name)
+        self._childDocument = doc
+        self._childView = view
+        if view:
+            view.SetFrame(self)
+        # self.Create(doc, view, frame, id, title, pos, size, style, name)
+        self._activeEvent = None
+        self._activated = 0
+        wx.EVT_ACTIVATE(self, self.OnActivate)
+        wx.EVT_CLOSE(self, self.OnCloseWindow)
+
+        if frame:  # wxBug: For some reason the EVT_ACTIVATE event is not getting triggered for the first mdi client window that is opened so we have to do it manually
+            mdiChildren = filter(lambda x: isinstance(x, wx.MDIChildFrame), frame.GetChildren())
+            if len(mdiChildren) == 1:
+                self.Activate()
+
+
+##    # Couldn't get this to work, but seems to work fine with single stage construction
+##    def Create(self, doc, view, frame, id, title, pos, size, style, name):
+##        self._childDocument = doc
+##        self._childView = view
+##        if wx.MDIChildFrame.Create(self, frame, id, title, pos, size, style, name):
+##            if view:
+##                view.SetFrame(self)
+##                return True
+##        return False
+
+
+
+    def Activate(self):  # Need this in case there are embedded sash windows and such, OnActivate is not getting called
+        """
+        Activates the current view.
+        """
+        if self._childView:
+            self._childView.Activate(True)
+
+
+    def ProcessEvent(event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if self._activeEvent == event:
+            return False
+
+        self._activeEvent = event  # Break recursion loops
+
+        if self._childView:
+            self._childView.Activate(True)
+
+        if not self._childView or not self._childView.ProcessEvent(event):
+            if not isinstance(event, wx.CommandEvent) or not self.GetParent() or not self.GetParent().ProcessEvent(event):
+                ret = False
+            else:
+                ret = True
+        else:
+            ret = True
+
+        self._activeEvent = None
+        return ret
+
+
+    def OnActivate(self, event):
+        """
+        Sets the currently active view to be the frame's view. You may need to
+        override (but still call) this function in order to set the keyboard
+        focus for your subwindow.
+        """
+        if self._activated != 0:
+            return True
+        self._activated += 1
+        wx.MDIChildFrame.Activate(self)
+        if event.GetActive() and self._childView:
+            self._childView.Activate(event.GetActive())
+        self._activated = 0
+
+    def OnCloseWindow(self, event):
+        """
+        Closes and deletes the current view and document.
+        """
+        if self._childView:
+            ans = False
+            if not event.CanVeto():
+                ans = True
+            else:
+                ans = self._childView.Close(deleteWindow = False)
+
+            if ans:
+                self._childView.Activate(False)
+                self._childView.Destroy()
+                self._childView = None
+                if self._childDocument:
+                    self._childDocument.Destroy()  # This isn't in the wxWindows codebase but the document needs to be disposed of somehow
+                self._childDocument = None
+                self.Destroy()
+            else:
+                event.Veto()
+        else:
+            event.Veto()
+
+
+    def GetDocument(self):
+        """
+        Returns the document associated with this frame.
+        """
+        return self._childDocument
+
+
+    def SetDocument(self, document):
+        """
+        Sets the document for this frame.
+        """
+        self._childDocument = document
+
+
+    def GetView(self):
+        """
+        Returns the view associated with this frame.
+        """
+        return self._childView
+
+
+    def SetView(self, view):
+        """
+        Sets the view for this frame.
+        """
+        self._childView = view
+
+
+class DocPrintout(wx.Printout):
+    """
+    DocPrintout is a default Printout that prints the first page of a document
+    view.
+    """
+
+
+    def __init__(self, view, title = "Printout"):
+        """
+        Constructor.
+        """
+        wx.Printout.__init__(self)
+        self._printoutView = view
+
+
+    def GetView(self):
+        """
+        Returns the DocPrintout's view.
+        """
+        return self._printoutView
+
+
+    def OnPrintPage(self, page):
+        """
+        Prints the first page of the view.
+        """
+        dc = self.GetDC()
+        ppiScreenX, ppiScreenY = self.GetPPIScreen()
+        ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()
+        scale = ppiPrinterX/ppiScreenX
+        w, h = dc.GetSize()
+        pageWidth, pageHeight = self.GetPageSizePixels()
+        overallScale = scale * w / pageWidth
+        dc.SetUserScale(overallScale, overallScale)
+        if self._printoutView:
+            self._printoutView.OnDraw(dc)
+        return True
+
+
+    def HasPage(self, pageNum):
+        """
+        Indicates that the DocPrintout only has a single page.
+        """
+        return pageNum == 1
+
+
+    def OnBeginDocument(self, startPage, endPage):
+        """
+        Not quite sure why this was overridden, but it was in wxWindows! :)
+        """
+        if not wx.Printout.base_OnBeginDocument(self, startPage, endPage):
+            return False
+        return True
+
+
+    def GetPageInfo(self):
+        """
+        Indicates that the DocPrintout only has a single page.
+        """
+        minPage = 1
+        maxPage = 1
+        selPageFrom = 1
+        selPageTo = 1
+        return (minPage, maxPage, selPageFrom, selPageTo)
+
+
+#----------------------------------------------------------------------
+# Command Classes
+#----------------------------------------------------------------------
+
+class Command(wx.Object):
+    """
+    wxCommand is a base class for modelling an application command, which is
+    an action usually performed by selecting a menu item, pressing a toolbar
+    button or any other means provided by the application to change the data
+    or view.
+    """
+
+
+    def __init__(self, canUndo = False, name = None):
+        """
+        Constructor. wxCommand is an abstract class, so you will need to
+        derive a new class and call this constructor from your own constructor.
+
+        canUndo tells the command processor whether this command is undo-able.
+        You can achieve the same functionality by overriding the CanUndo member
+        function (if for example the criteria for undoability is context-
+        dependent).
+
+        name must be supplied for the command processor to display the command
+        name in the application's edit menu.
+        """
+        self._canUndo = canUndo
+        self._name = name
+
+
+    def CanUndo(self):
+        """
+        Returns true if the command can be undone, false otherwise.
+        """
+        return self._canUndo
+
+
+    def GetName(self):
+        """
+        Returns the command name.
+        """
+        return self._name
+
+
+    def Do(self):
+        """
+        Override this member function to execute the appropriate action when
+        called. Return true to indicate that the action has taken place, false
+        otherwise. Returning false will indicate to the command processor that
+        the action is not undoable and should not be added to the command
+        history.
+        """
+        return True
+
+
+    def Undo(self):
+        """
+        Override this member function to un-execute a previous Do. Return true
+        to indicate that the action has taken place, false otherwise. Returning
+        false will indicate to the command processor that the action is not
+        redoable and no change should be made to the command history.
+
+        How you implement this command is totally application dependent, but
+        typical strategies include:
+
+        Perform an inverse operation on the last modified piece of data in the
+        document. When redone, a copy of data stored in command is pasted back
+        or some operation reapplied. This relies on the fact that you know the
+        ordering of Undos; the user can never Undo at an arbitrary position in
+        he command history.
+
+        Restore the entire document state (perhaps using document
+        transactioning). Potentially very inefficient, but possibly easier to
+        code if the user interface and data are complex, and an 'inverse
+        execute' operation is hard to write.
+        """
+        return True
+
+
+class CommandProcessor(wx.Object):
+    """
+    wxCommandProcessor is a class that maintains a history of wxCommands, with
+    undo/redo functionality built-in. Derive a new class from this if you want
+    different behaviour.
+    """
+
+
+    def __init__(self, maxCommands = -1):
+        """
+        Constructor.  maxCommands may be set to a positive integer to limit
+        the number of commands stored to it, otherwise (and by default) the
+        list of commands can grow arbitrarily.
+        """
+        self._maxCommands = maxCommands
+        self._editMenu = None
+        self._undoAccelerator = _("Ctrl+Z")
+        self._redoAccelerator = _("Ctrl+Y")
+        self.ClearCommands()
+
+
+    def _GetCurrentCommand(self):
+        if len(self._commands) == 0:
+            return None
+        else:
+            return self._commands[-1]
+
+
+    def _GetCurrentRedoCommand(self):
+        if len(self._redoCommands) == 0:
+            return None
+        else:
+            return self._redoCommands[-1]
+
+
+    def GetMaxCommands(self):
+        """
+        Returns the maximum number of commands that the command processor
+        stores.
+
+        """
+        return self._maxCommands
+
+
+    def GetCommands(self):
+        """
+        Returns the list of commands.
+        """
+        return self._commands
+
+
+    def ClearCommands(self):
+        """
+        Deletes all the commands in the list and sets the current command
+        pointer to None.
+        """
+        self._commands = []
+        self._redoCommands = []
+
+
+    def GetEditMenu(self):
+        """
+        Returns the edit menu associated with the command processor.
+        """
+        return self._editMenu
+
+
+    def SetEditMenu(self, menu):
+        """
+        Tells the command processor to update the Undo and Redo items on this
+        menu as appropriate. Set this to NULL if the menu is about to be
+        destroyed and command operations may still be performed, or the
+        command processor may try to access an invalid pointer.
+        """
+        self._editMenu = menu
+
+
+    def GetUndoAccelerator(self):
+        """
+        Returns the string that will be appended to the Undo menu item.
+        """
+        return self._undoAccelerator
+
+
+    def SetUndoAccelerator(self, accel):
+        """
+        Sets the string that will be appended to the Redo menu item.
+        """
+        self._undoAccelerator = accel
+
+
+    def GetRedoAccelerator(self):
+        """
+        Returns the string that will be appended to the Redo menu item.
+        """
+        return self._redoAccelerator
+
+
+    def SetRedoAccelerator(self, accel):
+        """
+        Sets the string that will be appended to the Redo menu item.
+        """
+        self._redoAccelerator = accel
+
+
+    def SetEditMenu(self, menu):
+        """
+        Tells the command processor to update the Undo and Redo items on this
+        menu as appropriate. Set this to NULL if the menu is about to be
+        destroyed and command operations may still be performed, or the
+        command processor may try to access an invalid pointer.
+        """
+        self._editMenu = menu
+
+
+    def SetMenuStrings(self):
+        """
+        Sets the menu labels according to the currently set menu and the
+        current command state.
+        """
+        if self.GetEditMenu() != None:
+            undoCommand = self._GetCurrentCommand()
+            redoCommand = self._GetCurrentRedoCommand()
+            undoItem = self.GetEditMenu().FindItemById(wx.ID_UNDO)
+            redoItem = self.GetEditMenu().FindItemById(wx.ID_REDO)
+            if self.GetUndoAccelerator():
+                undoAccel = '\t' + self.GetUndoAccelerator()
+            else:
+                undoAccel = ''
+            if self.GetRedoAccelerator():
+                redoAccel = '\t' + self.GetRedoAccelerator()
+            else:
+                redoAccel = ''
+            if undoCommand and undoItem and undoCommand.CanUndo():
+                undoItem.SetText(_("Undo ") + undoCommand.GetName() + undoAccel)
+            #elif undoCommand and not undoCommand.CanUndo():
+            #    undoItem.SetText(_("Can't Undo") + undoAccel)
+            else:
+                undoItem.SetText(_("Undo" + undoAccel))
+            if redoCommand and redoItem:
+                redoItem.SetText(_("Redo ") + redoCommand.GetName() + redoAccel)
+            else:
+                redoItem.SetText(_("Redo") + redoAccel)
+
+
+    def CanUndo(self):
+        """
+        Returns true if the currently-active command can be undone, false
+        otherwise.
+        """
+        if self._GetCurrentCommand() == None:
+            return False
+        return self._GetCurrentCommand().CanUndo()
+
+
+    def CanRedo(self):
+        """
+        Returns true if the currently-active command can be redone, false
+        otherwise.
+        """
+        return self._GetCurrentRedoCommand() != None
+
+
+    def Submit(self, command, storeIt = True):
+        """
+        Submits a new command to the command processor. The command processor
+        calls wxCommand::Do to execute the command; if it succeeds, the
+        command is stored in the history list, and the associated edit menu
+        (if any) updated appropriately. If it fails, the command is deleted
+        immediately. Once Submit has been called, the passed command should
+        not be deleted directly by the application.
+
+        storeIt indicates whether the successful command should be stored in
+        the history list.
+        """
+        done = command.Do()
+        if done and storeIt:
+            self._commands.append(command)
+        if self._maxCommands > -1:
+            if len(self._commands) > self._maxCommands:
+                del self._commands[0]
+        return done
+
+
+    def Redo(self):
+        """
+        Redoes the command just undone.
+        """
+        cmd = self._GetCurrentRedoCommand()
+        if not cmd:
+            return False
+        done = cmd.Do()
+        if done:
+            self._commands.append(self._redoCommands.pop())
+        return done
+
+
+    def Undo(self):
+        """
+        Undoes the command just executed.
+        """
+        cmd = self._GetCurrentCommand()
+        if not cmd:
+            return False
+        done = cmd.Undo()
+        if done:
+            self._redoCommands.append(self._commands.pop())
+        return done
+
+
diff --git a/wxPython/wx/lib/pydocview.py b/wxPython/wx/lib/pydocview.py
new file mode 100644 (file)
index 0000000..97ad542
--- /dev/null
@@ -0,0 +1,2455 @@
+#----------------------------------------------------------------------------
+# Name:         pydocview.py
+# Purpose:      Python extensions to the wxWindows docview framework
+#
+# Author:       Peter Yared
+#
+# Created:      5/15/03
+# CVS-ID:       $Id$
+# Copyright:    (c) 2003-2004 ActiveGrid, Inc.
+# License:      wxWindows license
+#----------------------------------------------------------------------------
+
+
+import wx
+import wx.lib.docview
+import sys
+import getopt
+from wxPython.lib.rcsizer import RowColSizer
+import os
+import os.path
+import time
+import string
+_ = wx.GetTranslation
+
+#----------------------------------------------------------------------------
+# Constants
+#----------------------------------------------------------------------------
+
+VIEW_TOOLBAR_ID = wx.NewId()
+VIEW_STATUSBAR_ID = wx.NewId()
+
+EMBEDDED_WINDOW_TOP = 1
+EMBEDDED_WINDOW_BOTTOM = 2
+EMBEDDED_WINDOW_LEFT = 4
+EMBEDDED_WINDOW_RIGHT = 8
+EMBEDDED_WINDOW_TOPLEFT = 16
+EMBEDDED_WINDOW_BOTTOMLEFT = 32
+EMBEDDED_WINDOW_TOPRIGHT = 64
+EMBEDDED_WINDOW_BOTTOMRIGHT = 128
+EMBEDDED_WINDOW_ALL = EMBEDDED_WINDOW_TOP | EMBEDDED_WINDOW_BOTTOM | EMBEDDED_WINDOW_LEFT | EMBEDDED_WINDOW_RIGHT | \
+                      EMBEDDED_WINDOW_TOPLEFT | EMBEDDED_WINDOW_BOTTOMLEFT | EMBEDDED_WINDOW_TOPRIGHT | EMBEDDED_WINDOW_BOTTOMRIGHT
+
+SAVEALL_ID = wx.NewId()
+
+WINDOW_MENU_NUM_ITEMS = 9
+
+
+class DocService(wx.EvtHandler):
+    """
+    An abstract class used to add reusable services to a docview application.
+    """
+
+
+    def __init__(self):
+        """Initializes the DocService."""
+        pass
+
+
+    def GetDocumentManager(self):
+        """Returns the DocManager for the docview application."""
+        return self._docManager
+
+
+    def SetDocumentManager(self, docManager):
+        """Sets the DocManager for the docview application."""
+        self._docManager = docManager
+
+
+    def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
+        """Called to install controls into the menubar and toolbar of a SDI or MDI window.  Override this method for a particular service."""
+        pass
+
+
+    def ProcessEventBeforeWindows(self, event):
+        """
+        Processes an event before the main window has a chance to process the window. 
+        Override this method for a particular service.
+        """
+        return False
+
+
+    def ProcessUpdateUIEventBeforeWindows(self, event):
+        """
+        Processes a UI event before the main window has a chance to process the window.
+        Override this method for a particular service.
+        """
+        return False
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return False
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        return False
+
+
+    def OnCloseFrame(self, event):
+        """
+        Called when the a docview frame is being closed.  Override this method
+        so a service can either do cleanup or veto the frame being closed by
+        returning false.
+        """
+        return True
+
+
+    def OnExit(self):
+        """
+        Called when the the docview application is being closed.  Override this method
+        so a service can either do cleanup or veto the frame being closed by
+        returning false.
+        """
+        pass
+
+
+    def GetMenuItemPos(self, menu, id):
+        """
+        Utility method used to find the position of a menu item so that services can
+        easily find where to insert a menu item in InstallControls.
+        """
+        menuItems = menu.GetMenuItems()
+        for i, menuItem in enumerate(menuItems):
+            if menuItem.GetId() == id:
+                return i
+        return i
+
+
+    def GetView(self):
+        """
+        Called by WindowMenuService to get views for services that don't
+        have dedicated documents such as the Outline Service.
+        """
+        return None
+
+
+class DocOptionsService(DocService):
+    """
+    A service that implements an options menu item and an options dialog with
+    notebook tabs.  New tabs can be added by other services by calling the
+    "AddOptionsPanel" method.
+    """
+
+
+    def __init__(self, showGeneralOptions = True):
+        """
+        Initializes the options service with the option of suppressing the default
+        general options pane that is included with the options service by setting
+        showGeneralOptions to False.
+        """
+        DocService.__init__(self)
+        self.ClearOptionsPanels()
+        self._toolOptionsID = wx.NewId()
+        if showGeneralOptions:
+            self.AddOptionsPanel(GeneralOptionsPanel)
+
+
+    def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
+        """
+        Installs a "Tools" menu with an "Options" menu item.
+        """
+        toolsMenuIndex = menuBar.FindMenu(_("&Tools"))
+        if toolsMenuIndex > -1:
+            toolsMenu = menuBar.GetMenu(toolsMenuIndex)
+        else:
+            toolsMenu = wx.Menu()
+        if toolsMenuIndex == -1:
+            formatMenuIndex = menuBar.FindMenu(_("&Format"))
+            menuBar.Insert(formatMenuIndex + 1, toolsMenu, _("&Tools"))
+        if toolsMenu:
+            if toolsMenu.GetMenuItemCount():
+                toolsMenu.AppendSeparator()
+            toolsMenu.Append(self._toolOptionsID, _("&Options..."), _("Sets options"))
+            wx.EVT_MENU(frame, self._toolOptionsID, frame.ProcessEvent)
+            
+
+    def ProcessEvent(self, event):
+        """
+        Checks to see if the "Options" menu item has been selected.
+        """
+        id = event.GetId()
+        if id == self._toolOptionsID:
+            self.OnOptions(event)
+            return True
+        else:
+            return False
+
+
+    def ClearOptionsPanels(self):
+        """
+        Clears all of the options panels that have been added into the
+        options dialog.
+        """
+        self._optionsPanels = []
+
+
+    def AddOptionsPanel(self, optionsPanel):
+        """
+        Adds an options panel to the options dialog. 
+        """
+        self._optionsPanels.append(optionsPanel)
+
+
+    def OnOptions(self, event):
+        """
+        Shows the options dialog, called when the "Options" menu item is selected.
+        """
+        if len(self._optionsPanels) == 0:
+            return
+        optionsDialog = OptionsDialog(wx.GetApp().GetTopWindow(), self._optionsPanels, self._docManager)
+        if optionsDialog.ShowModal() == wx.ID_OK:
+            optionsDialog.OnOK(optionsDialog)  # wxBug: wxDialog should be calling this automatically but doesn't
+        optionsDialog.Destroy()
+
+
+class OptionsDialog(wx.Dialog):
+    """
+    A default options dialog used by the OptionsService that hosts a notebook
+    tab of options panels.
+    """
+
+
+    def __init__(self, parent, optionsPanelClasses, docManager):
+        """
+        Initializes the options dialog with a notebook page that contains new
+        instances of the passed optionsPanelClasses.
+        """
+        wx.Dialog.__init__(self, parent, -1, _("Options"), size = (310, 375))
+
+        self._optionsPanels = []
+        self._docManager = docManager
+
+        HALF_SPACE = 5
+        SPACE = 10
+
+        sizer = wx.BoxSizer(wx.VERTICAL)
+
+        optionsNotebook = wx.Notebook(self, -1, size = (310, 375), style = wx.NB_MULTILINE)
+        optionsNotebookSizer = wx.NotebookSizer(optionsNotebook)
+        sizer.Add(optionsNotebookSizer, 0, wx.ALL | wx.EXPAND, SPACE)
+        for optionsPanelClass in optionsPanelClasses:
+            optionsPanel = optionsPanelClass(optionsNotebook, -1)
+            self._optionsPanels.append(optionsPanel)
+        sizer.Add(self.CreateButtonSizer(wx.OK | wx.CANCEL), 0, wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM, HALF_SPACE)
+        self.SetSizer(sizer)
+        self.Layout()
+        self.Fit()
+        wx.CallAfter(self.DoRefresh)
+
+
+    def DoRefresh(self):
+        """
+        wxBug: On Windows XP when using a multiline notebook the default page doesn't get
+        drawn, but it works when using a single line notebook.
+        """
+        self.Refresh()
+
+
+    def GetDocManager(self):
+        """
+        Returns the document manager passed to the OptionsDialog constructor.
+        """
+        return self._docManager
+
+
+    def OnOK(self, event):
+        """
+        Calls the OnOK method of all of the OptionDialog's embedded panels
+        """
+        for optionsPanel in self._optionsPanels:
+            optionsPanel.OnOK(event)
+
+
+class GeneralOptionsPanel(wx.Panel):
+    """
+    A general options panel that is used in the OptionDialog to configure the
+    generic properties of a pydocview application, such as "show tips at startup"
+    and whether to use SDI or MDI for the application.
+    """
+
+
+    def __init__(self, parent, id):
+        """
+        Initializes the panel by adding an "Options" folder tab to the parent notebook and
+        populating the panel with the generic properties of a pydocview application. 
+        """
+        wx.Panel.__init__(self, parent, id)
+        SPACE = 10
+        HALF_SPACE = 5
+        backgroundColor = wx.WHITE
+        config = wx.ConfigBase_Get()
+        self._showTipsCheckBox = wx.CheckBox(self, -1, _("Show tips at start up"))
+        self._showTipsCheckBox.SetBackgroundColour(backgroundColor) # wxBUG: uses wrong background color
+        self._showTipsCheckBox.SetValue(config.ReadInt("ShowTipAtStartup", True))
+        self._documentRadioBox = wx.RadioBox(self, -1, _("Document interface"),
+                                      choices = [_("Show each document in its own window (SDI)"),
+                                                 _("Show All documents in a single window (MDI)")],
+                                      majorDimension=1,
+                                      #style = wx.RA_SPECIFY_ROWS
+                                      )
+        #self._documentRadioBox.SetBackgroundColour(backgroundColor) # wxBug: uses wrong background color
+        if config.ReadInt("UseMDI", True):
+            self._documentRadioBox.SetSelection(1)
+        else:
+            self._documentRadioBox.SetSelection(0)
+            
+        def OnDocumentInterfaceSelect(event):
+            if not self._documentInterfaceMessageShown:
+                msgTitle = wx.GetApp().GetAppName()
+                if not msgTitle:
+                    msgTitle = _("Document Options")
+                wx.MessageBox("Document interface changes will not appear until the application is restarted.",
+                              msgTitle,
+                              wx.OK | wx.ICON_INFORMATION,
+                              self.GetParent())
+                self._documentInterfaceMessageShown = True
+                
+        wx.EVT_RADIOBOX(self, self._documentRadioBox.GetId(), OnDocumentInterfaceSelect)
+        optionsBorderSizer = wx.BoxSizer(wx.VERTICAL)
+        optionsSizer = wx.BoxSizer(wx.VERTICAL)
+        optionsSizer.Add(self._showTipsCheckBox, 0, wx.ALL, HALF_SPACE)
+        optionsSizer.Add(self._documentRadioBox, 0, wx.ALL, HALF_SPACE)
+        optionsBorderSizer.Add(optionsSizer, 0, wx.ALL, SPACE)
+        self.SetSizer(optionsBorderSizer)
+        self.Layout()
+        self._documentInterfaceMessageShown = False
+        parent.AddPage(self, _("Options"))
+
+    def OnOK(self, optionsDialog):
+        """
+        Updates the config based on the selections in the options panel.
+        """
+        config = wx.ConfigBase_Get()
+        config.WriteInt("ShowTipAtStartup", self._showTipsCheckBox.GetValue())
+        config.WriteInt("UseMDI", self._documentRadioBox.GetSelection())
+
+
+class DocApp(wx.PySimpleApp):
+    """
+    The DocApp class serves as the base class for pydocview applications and offers
+    functionality such as services, creation of SDI and MDI frames, show tips,
+    and a splash screen.
+    """
+
+
+    def OnInit(self):
+        """
+        Initializes the DocApp.
+        """
+        self._services = []
+        self._defaultIcon = None
+        self._registeredCloseEvent = False
+        self._debug = False
+        return True
+
+
+    def OpenCommandLineArgs(self):
+        """
+        Called to open files that have been passed to the application from the
+        command line.
+        """
+        args = sys.argv[1:]
+        for arg in args:
+            if arg[0] != '/' and arg[0] != '-':
+                self.GetDocumentManager().CreateDocument(arg, wx.lib.docview.DOC_SILENT)
+
+
+    def GetDocumentManager(self):
+        """
+        Returns the document manager associated to the DocApp.
+        """
+        return self._docManager
+
+
+    def SetDocumentManager(self, docManager):
+        """
+        Sets the document manager associated with the DocApp and loads the
+        DocApp's file history into the document manager.
+        """
+        self._docManager = docManager
+        config = wx.ConfigBase_Get()
+        self.GetDocumentManager().FileHistoryLoad(config)
+
+
+    def ProcessEventBeforeWindows(self, event):
+        """
+        Enables services to process an event before the main window has a chance to
+        process the window. 
+        """
+        for service in self._services:
+            if service.ProcessEventBeforeWindows(event):
+                return True
+        return False
+
+
+    def ProcessUpdateUIEventBeforeWindows(self, event):
+        """
+        Enables services to process a UI event before the main window has a chance
+        to process the window.
+        """
+        for service in self._services:
+            if service.ProcessUpdateUIEventBeforeWindows(event):
+                return True
+        return False
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        for service in self._services:
+            if service.ProcessEvent(event):
+                return True
+        return False
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        for service in self._services:
+            if service.ProcessUpdateUIEvent(event):
+                return True
+        return False
+
+
+    def InstallService(self, service):
+        """
+        Installs an instance of a DocService into the DocApp.
+        """
+        service.SetDocumentManager(self._docManager)
+        self._services.append(service)
+        return service
+
+
+    def GetServices(self):
+        """
+        Returns the DocService instances that have been installed into the DocApp.
+        """
+        return self._services
+
+
+    def GetService(self, type):
+        """
+        Returns the instance of a particular type of service that has been installed
+        into the DocApp.  For example, "wx.GetApp().GetService(pydocview.OptionsService)"
+        returns the isntance of the OptionsService that is running within the DocApp.
+        """
+        for service in self._services:
+            if isinstance(service, type):
+                return service
+        return None
+
+
+    def OnExit(self):
+        """
+        Called when the DocApp is exited, enables the installed DocServices to exit
+        and saves the DocManager's file history.
+        """
+        for service in self._services:
+            service.OnExit()
+        config = wx.ConfigBase_Get()
+        self._docManager.FileHistorySave(config)
+
+    
+    def GetDefaultDocManagerFlags(self):
+        """
+        Returns the default flags to use when creating the DocManager.
+        """
+        config = wx.ConfigBase_Get()
+        if config.ReadInt("UseMDI", True):
+            flags = wx.lib.docview.DOC_MDI | wx.lib.docview.DOC_OPEN_ONCE
+        else:
+            flags = wx.lib.docview.DOC_SDI | wx.lib.docview.DOC_OPEN_ONCE
+        return flags
+
+
+    def ShowTip(self, frame, tipProvider):
+        """
+        Shows the tip window, generally this is called when an application starts.
+        A wx.TipProvider must be passed.
+        """
+        config = wx.ConfigBase_Get()
+        showTip = config.ReadInt("ShowTipAtStartup", 1)
+        if showTip:
+            index = config.ReadInt("TipIndex", 0)
+            showTipResult = wx.ShowTip(frame, tipProvider, showAtStartup = showTip)
+            if showTipResult != showTip:
+                config.WriteInt("ShowTipAtStartup", showTipResult)
+
+
+    def GetEditMenu(self, frame):
+        """
+        Utility method that finds the Edit menu within the menubar of a frame.
+        """
+        menuBar = frame.GetMenuBar()
+        if not menuBar:
+            return None
+        editMenuIndex = menuBar.FindMenu(_("&Edit"))
+        if editMenuIndex == -1:
+            return None
+        return menuBar.GetMenu(editMenuIndex)
+
+
+    def CreateDocumentFrame(self, view, doc, flags, id = -1, title = "", pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE):
+        """
+        Called by the DocManager to create and return a new Frame for a Document. 
+        Chooses whether to create an MDIChildFrame or SDI Frame based on the
+        DocManager's flags.
+        """
+        docflags = self.GetDocumentManager().GetFlags()
+        if docflags & wx.lib.docview.DOC_SDI:
+            frame = self.CreateSDIDocumentFrame(doc, view, id, title, pos, size, style)
+            frame.Show()
+
+            # wxBug: operating system bug, first window is set to the position of last window closed, ignoring passed in position on frame creation
+            #        also, initial size is incorrect for the same reasons
+            if frame.GetPosition() != pos:
+                frame.Move(pos)
+            if frame.GetSize() != size:
+                frame.SetSize(size)
+
+            if doc and doc.GetCommandProcessor():
+                doc.GetCommandProcessor().SetEditMenu(self.GetEditMenu(frame))
+        elif docflags & wx.lib.docview.DOC_MDI:
+            frame = self.CreateMDIDocumentFrame(doc, view, id, title, pos, size, style)
+            if doc and doc.GetDocumentTemplate().GetIcon():
+                frame.SetIcon(doc.GetDocumentTemplate().GetIcon())
+            if doc and doc.GetCommandProcessor():
+                doc.GetCommandProcessor().SetEditMenu(self.GetEditMenu(wx.GetApp().GetTopWindow()))
+        if not frame.GetIcon() and self._defaultIcon:
+            frame.SetIcon(self.GetDefaultIcon())
+        view.SetFrame(frame)
+        return frame
+
+
+    def CreateSDIDocumentFrame(self, doc, view, id = -1, title = "", pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE):
+        """
+        Creates and returns an SDI Document Frame.
+        """
+        frame = DocSDIFrame(doc, view, None, id, title, pos, size, style)
+        return frame
+
+
+    def CreateMDIDocumentFrame(self, doc, view, id = -1, title = "", pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE):
+        """
+        Creates and returns an MDI Document Frame.
+        """
+        # if any child windows are maximized, then user must want any new children maximized
+        # if no children exist, then use the default value from registry
+        # wxBug:  Only current window is maximized, so need to check every child frame
+        parentFrame = wx.GetApp().GetTopWindow()
+        childrenMaximized = filter(lambda child: isinstance(child, wx.MDIChildFrame) and child.IsMaximized(), parentFrame.GetChildren())
+        if childrenMaximized:
+            maximize = True
+        else:
+            children = filter(lambda child: isinstance(child, wx.MDIChildFrame), parentFrame.GetChildren())
+            if children:
+                # other windows exist and none are maximized
+                maximize = False
+            else:
+                # get default setting from registry
+                maximize = wx.ConfigBase_Get().ReadInt("MDIChildFrameMaximized", False)
+
+        frame = wx.lib.docview.DocMDIChildFrame(doc, view, wx.GetApp().GetTopWindow(), id, title, pos, size, style)
+        if maximize:  # wxBug: Should already be maximizing new child frames if one is maximized but it's not so we have to force it to
+            frame.Maximize(True)
+
+##        wx.EVT_MAXIMIZE(frame, self.OnMaximize) # wxBug: This doesn't work, need to save MDIChildFrameMaximized state on close of windows instead
+        wx.EVT_CLOSE(frame, self.OnCloseChildWindow)
+        if not self._registeredCloseEvent:
+            wx.EVT_CLOSE(parentFrame, self.OnCloseMainWindow) # need to check on this, but only once
+            self._registeredCloseEvent = True
+
+        return frame
+
+
+    def SaveMDIDocumentFrameMaximizedState(self, maximized):
+        """
+        Remember in the config whether the MDI Frame is maximized so that it can be restored
+        on open.
+        """
+        config = wx.ConfigBase_Get()
+        maximizeFlag = config.ReadInt("MDIChildFrameMaximized", False)
+        if maximized != maximizeFlag:
+            config.WriteInt("MDIChildFrameMaximized", maximized)
+
+
+    def OnCloseChildWindow(self, event):
+        """
+        Called when an MDI Child Frame is closed.  Calls SaveMDIDocumentFrameMaximizedState to
+        remember whether the MDI Frame is maximized so that it can be restored on open.
+        """
+        self.SaveMDIDocumentFrameMaximizedState(event.GetEventObject().IsMaximized())
+        event.Skip()
+
+
+    def OnCloseMainWindow(self, event):
+        """
+        Called when the MDI Parent Frame is closed.  Remembers whether the MDI Parent Frame is
+        maximized.
+        """
+        children = event.GetEventObject().GetChildren()
+        childrenMaximized = filter(lambda child: isinstance(child, wx.MDIChildFrame)and child.IsMaximized(), children)
+        if childrenMaximized:
+            self.SaveMDIDocumentFrameMaximizedState(True)
+        else:
+            childrenNotMaximized = filter(lambda child: isinstance(child, wx.MDIChildFrame), children)
+
+            if childrenNotMaximized:
+                # other windows exist and none are maximized
+                self.SaveMDIDocumentFrameMaximizedState(False)
+
+        event.Skip()
+
+
+    def GetDefaultIcon(self):
+        """
+        Returns the application's default icon.
+        """
+        return self._defaultIcon
+
+
+    def SetDefaultIcon(self, icon):
+        """
+        Sets the application's default icon.
+        """
+        self._defaultIcon = icon
+
+
+    def GetDebug(self):
+        """
+        Returns True if the application is in debug mode.
+        """
+        return self._debug
+
+
+    def SetDebug(self, debug):
+        """
+        Returns False if the application is in debug mode.
+        """
+        self._debug = debug
+
+
+    def CreateChildDocument(self, parentDocument, documentType, objectToEdit, path = ''):
+        """
+        Creates a child window of a document that edits an object.  The child window
+        is managed by the parent document frame, so it will be prompted to close if its
+        parent is closed, etc.  Child Documents are useful when there are complicated 
+        Views of a Document and users will need to tunnel into the View.
+        """
+        for document in self.GetDocumentManager().GetDocuments()[:]:  # Cloning list to make sure we go through all docs even as they are deleted
+            if isinstance(document, ChildDocument) and document.GetParentDocument() == parentDocument:
+                if document.GetData() == objectToEdit:
+                    if hasattr(document.GetFirstView().GetFrame(), "SetFocus"):
+                        document.GetFirstView().GetFrame().SetFocus()
+                    return document
+        for temp in wx.GetApp().GetDocumentManager().GetTemplates():
+            if temp.GetDocumentType() == documentType:
+                break
+            temp = None
+        newDoc = temp.CreateDocument(path, 0, data = objectToEdit, parentDocument = parentDocument)
+        newDoc.SetDocumentName(temp.GetDocumentName())
+        newDoc.SetDocumentTemplate(temp)
+        if path == '':
+            newDoc.OnNewDocument()
+        else:
+            if not newDoc.OnOpenDocument(path):
+                newDoc.DeleteAllViews()  # Implicitly deleted by DeleteAllViews
+                return None
+        return newDoc
+
+
+    def CloseChildDocuments(self, parentDocument):
+        """
+        Closes the child windows of a Document.
+        """
+        for document in self.GetDocumentManager().GetDocuments()[:]:  # Cloning list to make sure we go through all docs even as they are deleted
+            if isinstance(document, ChildDocument) and document.GetParentDocument() == parentDocument:
+                if document.GetFirstView().GetFrame():
+                    document.GetFirstView().GetFrame().SetFocus()
+                if document.GetFirstView().OnClose(deleteWindow = False):
+                    if document.GetFirstView().GetFrame():
+                        document.GetFirstView().GetFrame().Close()  # wxBug: Need to do this for some random reason
+                else:
+                    return False
+        return True
+
+
+    def IsMDI(self):
+        """
+        Returns True if the application is in MDI mode.
+        """
+        return self.GetDocumentManager().GetFlags() & wx.lib.docview.DOC_MDI
+
+
+    def IsSDI(self):
+        """
+        Returns True if the application is in SDI mode.
+        """
+        return self.GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI
+
+
+    def ShowSplash(self, image):
+        """
+        Shows a splash window with the given image.
+        """
+        splash_bmp = wx.Image(image).ConvertToBitmap()
+        self._splash = wx.SplashScreen(splash_bmp,wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_NO_TIMEOUT,0, None, -1) 
+        self._splash.Show()
+
+
+    def CloseSplash(self):
+        """
+        Closes the splash window.
+        """
+        if self._splash:
+            self._splash.Close(True)
+        
+    
+class _DocFrameFileDropTarget(wx.FileDropTarget):
+    """
+    Class used to handle drops into the document frame.
+    """
+
+    def __init__(self, docManager, docFrame):
+        """
+        Initializes the FileDropTarget class with the active docManager and the docFrame.
+        """
+        wx.FileDropTarget.__init__(self)
+        self._docManager = docManager
+        self._docFrame = docFrame
+
+
+    def OnDropFiles(self, x, y, filenames):
+        """
+        Called when files are dropped in the drop target and tells the docManager to open
+        the files.
+        """
+        try:
+            for file in filenames:
+                self._docManager.CreateDocument(file, wx.lib.docview.DOC_SILENT)
+        except:
+            msgTitle = wx.GetApp().GetAppName()
+            if not msgTitle:
+                msgTitle = _("File Error")
+            wx.MessageBox("Could not open '%s'.  '%s'" % (docview.FileNameFromPath(file), sys.exc_value),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          self._docManager.FindSuitableParent())
+
+
+def _AboutDialog(frame):
+    """
+    Opens an AboutDialog.  Shared by DocMDIParentFrame and DocSDIFrame.
+    """
+    dlg = wx.Dialog(frame, -1, _("About ") + wx.GetApp().GetAppName(), style = wx.DEFAULT_DIALOG_STYLE)
+    dlg.SetBackgroundColour(wx.WHITE)
+    sizer = wx.BoxSizer(wx.VERTICAL)
+    splash_bmp = wx.Image("activegrid/tool/images/splash.jpg").ConvertToBitmap()
+    image = wx.StaticBitmap(dlg, -1, splash_bmp, (0,0), (splash_bmp.GetWidth(), splash_bmp.GetHeight()))
+    sizer.Add(image, 0, wx.ALIGN_CENTER|wx.ALL, 0)
+    sizer.Add(wx.StaticText(dlg, -1, _("ActiveGrid Application Builder\nVersion 1.0\n\nCopyright (c) 2003-2005 ActiveGrid Incorporated and Contributors.  All rights reserved.")), 0, wx.ALIGN_LEFT|wx.ALL, 5)
+    sizer.Add(wx.StaticText(dlg, -1, _("ActiveGrid Development Team:\nLawrence Bruhmuller\nMatt Fryer\nJoel Hare\nMorgan Hua\nJeff Norton\nPeter Yared")), 0, wx.ALIGN_LEFT|wx.ALL, 5)
+    sizer.Add(wx.StaticText(dlg, -1, _("http://www.activegrid.com")), 0, wx.ALIGN_LEFT|wx.ALL, 5)
+
+
+    btn = wx.Button(dlg, wx.ID_OK)
+    sizer.Add(btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
+
+    dlg.SetSizer(sizer)
+    dlg.SetAutoLayout(True)
+    sizer.Fit(dlg)
+    
+    dlg.CenterOnScreen()
+    dlg.ShowModal()
+    dlg.Destroy()
+
+
+class DocMDIParentFrame(wx.lib.docview.DocMDIParentFrame):
+    """
+    The DocMDIParentFrame is the primary frame which the DocApp uses to host MDI child windows.  It offers
+    features such as a default menubar, toolbar, and status bar, and a mechanism to manage embedded windows
+    on the edges of the DocMDIParentFrame.
+    """
+    
+
+    def __init__(self, docManager, parent, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "DocMDIFrame", embeddedWindows = 0):
+        """
+        Initializes the DocMDIParentFrame with the default menubar, toolbar, and status bar.  Use the
+        optional embeddedWindows parameter with the embedded window constants to create embedded
+        windows around the edges of the DocMDIParentFrame.
+        """
+        config = wx.ConfigBase_Get()
+        if pos == wx.DefaultPosition and size == wx.DefaultSize and config.ReadInt("MDIFrameMaximized", False):
+            pos = [0, 0]
+            size = wx.DisplaySize()
+            # wxBug: Need to set to fill screen to get around bug where maximize is leaving shadow of statusbar, check out maximize call at end of this function
+        else:
+            if pos == wx.DefaultPosition:
+                pos = config.ReadInt("MDIFrameXLoc", -1), config.ReadInt("MDIFrameYLoc", -1)
+
+            if wx.Display_GetFromPoint(pos) == -1:  # Check if the frame position is offscreen
+                pos = wx.DefaultPosition
+                
+            if size == wx.DefaultSize:
+                size = wx.Size(config.ReadInt("MDIFrameXSize", 450), config.ReadInt("MDIFrameYSize", 300))
+
+        wx.lib.docview.DocMDIParentFrame.__init__(self, docManager, parent, id, title, pos, size, style, name)
+        self._embeddedWindows = []
+        self.SetDropTarget(_DocFrameFileDropTarget(docManager, self))
+
+        if wx.GetApp().GetDefaultIcon():
+            self.SetIcon(wx.GetApp().GetDefaultIcon())
+
+        wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
+        wx.EVT_SIZE(self, self.OnSize)
+
+        self.InitializePrintData()
+
+        toolBar = self.CreateDefaultToolBar()
+        self.SetToolBar(toolBar)
+        menuBar = self.CreateDefaultMenuBar()
+        statusBar = self.CreateDefaultStatusBar()
+
+        if config.ReadInt("MDIFrameMaximized", False):
+            # wxBug: On maximize, statusbar leaves a residual that needs to be refereshed, happens even when user does it
+            self.Maximize()
+
+        self.CreateEmbeddedWindows(embeddedWindows)
+
+        wx.GetApp().SetTopWindow(self)  # Need to do this here in case the services are looking for wx.GetApp().GetTopWindow()
+        for service in wx.GetApp().GetServices():
+            service.InstallControls(self, menuBar = menuBar, toolBar = toolBar, statusBar = statusBar)
+            if hasattr(service, "ShowWindow"):
+                service.ShowWindow()  # instantiate service windows for correct positioning, we'll hide/show them later based on user preference
+
+        self.SetMenuBar(menuBar)  # wxBug: Have to set the menubar at the very end or the automatic MDI "window" menu doesn't get put in the right place when the services add new menus to the menubar
+
+
+    def CreateEmbeddedWindows(self, windows = 0):
+        """
+        Create the specified embedded windows around the edges of the DocMDIParentFrame.
+        """
+        frameSize = self.GetSize()   # TODO: GetClientWindow.GetSize is still returning 0,0 since the frame isn't fully constructed yet, so using full frame size
+        defaultHSize = int(frameSize[0] / 6)
+        defaultVSize = int(frameSize[1] / 7)
+        defaultSubVSize = int(frameSize[1] / 2)
+        #print defaultHSize, defaultVSize, defaultSubVSize
+        config = wx.ConfigBase_Get()
+        if windows & (EMBEDDED_WINDOW_LEFT | EMBEDDED_WINDOW_TOPLEFT | EMBEDDED_WINDOW_BOTTOMLEFT):
+            self._leftEmbWindow = self._CreateEmbeddedWindow(self, (config.ReadInt("MDIEmbedLeftSize", defaultHSize), -1), wx.LAYOUT_VERTICAL, wx.LAYOUT_LEFT, visible = config.ReadInt("MDIEmbedLeftVisible", 1), sash = wx.SASH_RIGHT)
+        else:
+            self._leftEmbWindow = None
+        if windows & EMBEDDED_WINDOW_TOPLEFT:
+            self._topLeftEmbWindow = self._CreateEmbeddedWindow(self._leftEmbWindow, (-1, config.ReadInt("MDIEmbedTopLeftSize", defaultSubVSize)), wx.LAYOUT_HORIZONTAL, wx.LAYOUT_TOP, visible = config.ReadInt("MDIEmbedTopLeftVisible", 1), sash = wx.SASH_BOTTOM)
+        else:
+            self._topLeftEmbWindow = None
+        if windows & EMBEDDED_WINDOW_BOTTOMLEFT:
+            self._bottomLeftEmbWindow = self._CreateEmbeddedWindow(self._leftEmbWindow, (-1, config.ReadInt("MDIEmbedBottomLeftSize", defaultSubVSize)), wx.LAYOUT_HORIZONTAL, wx.LAYOUT_BOTTOM, visible = config.ReadInt("MDIEmbedBottomLeftVisible", 1))
+        else:
+            self._bottomLeftEmbWindow = None
+        if windows & (EMBEDDED_WINDOW_RIGHT | EMBEDDED_WINDOW_TOPRIGHT | EMBEDDED_WINDOW_BOTTOMRIGHT):
+            self._rightEmbWindow = self._CreateEmbeddedWindow(self, (config.ReadInt("MDIEmbedRightSize", defaultHSize), -1), wx.LAYOUT_VERTICAL, wx.LAYOUT_RIGHT, visible = config.ReadInt("MDIEmbedRightVisible", 1), sash = wx.SASH_LEFT)
+        else:
+            self._rightEmbWindow = None
+        if windows & EMBEDDED_WINDOW_TOPRIGHT:
+            self._topRightEmbWindow = self._CreateEmbeddedWindow(self._rightEmbWindow, (-1, config.ReadInt("MDIEmbedTopRightSize", defaultSubVSize)), wx.LAYOUT_HORIZONTAL, wx.LAYOUT_TOP, visible = config.ReadInt("MDIEmbedTopRightVisible", 1), sash = wx.SASH_BOTTOM)
+        else:
+            self._topRightEmbWindow = None
+        if windows & EMBEDDED_WINDOW_BOTTOMRIGHT:
+            self._bottomRightEmbWindow = self._CreateEmbeddedWindow(self._rightEmbWindow, (-1, config.ReadInt("MDIEmbedBottomRightSize", defaultSubVSize)), wx.LAYOUT_HORIZONTAL, wx.LAYOUT_BOTTOM, visible = config.ReadInt("MDIEmbedBottomRightVisible", 1))
+        else:
+            self._bottomRightEmbWindow = None
+        if windows & EMBEDDED_WINDOW_TOP:
+            self._topEmbWindow = self._CreateEmbeddedWindow(self, (-1, config.ReadInt("MDIEmbedTopSize", defaultVSize)), wx.LAYOUT_HORIZONTAL, wx.LAYOUT_TOP, visible = config.ReadInt("MDIEmbedTopVisible", 1), sash = wx.SASH_BOTTOM)
+        else:
+            self._topEmbWindow = None
+        if windows & EMBEDDED_WINDOW_BOTTOM:
+            self._bottomEmbWindow = self._CreateEmbeddedWindow(self, (-1, config.ReadInt("MDIEmbedBottomSize", defaultVSize)), wx.LAYOUT_HORIZONTAL, wx.LAYOUT_BOTTOM, visible = config.ReadInt("MDIEmbedBottomVisible", 1), sash = wx.SASH_TOP)
+        else:
+            self._bottomEmbWindow = None
+        wx.LayoutAlgorithm().LayoutMDIFrame(self)
+        self.GetClientWindow().Refresh()
+
+
+    def SaveEmbeddedWindowSizes(self):
+        """
+        Saves the sizes of the embedded windows.
+        """
+        config = wx.ConfigBase_Get()
+        if self._leftEmbWindow:
+            config.WriteInt("MDIEmbedLeftSize", self._leftEmbWindow.GetSize()[0])
+            config.WriteInt("MDIEmbedLeftVisible", self._leftEmbWindow.IsShown())
+        if self._topLeftEmbWindow:
+            if self._topLeftEmbWindow._sizeBeforeHidden:
+                size = self._topLeftEmbWindow._sizeBeforeHidden[1]
+            else:
+                size = self._topLeftEmbWindow.GetSize()[1]
+            config.WriteInt("MDIEmbedTopLeftSize", size)
+            config.WriteInt("MDIEmbedTopLeftVisible", self._topLeftEmbWindow.IsShown())
+        if self._bottomLeftEmbWindow:
+            if self._bottomLeftEmbWindow._sizeBeforeHidden:
+                size = self._bottomLeftEmbWindow._sizeBeforeHidden[1]
+            else:
+                size = self._bottomLeftEmbWindow.GetSize()[1]
+            config.WriteInt("MDIEmbedBottomLeftSize", size)
+            config.WriteInt("MDIEmbedBottomLeftVisible", self._bottomLeftEmbWindow.IsShown())
+        if self._rightEmbWindow:
+            config.WriteInt("MDIEmbedRightSize", self._rightEmbWindow.GetSize()[0])
+            config.WriteInt("MDIEmbedRightVisible", self._rightEmbWindow.IsShown())
+        if self._topRightEmbWindow:
+            if self._topRightEmbWindow._sizeBeforeHidden:
+                size = self._topRightEmbWindow._sizeBeforeHidden[1]
+            else:
+                size = self._topRightEmbWindow.GetSize()[1]
+            config.WriteInt("MDIEmbedTopRightSize", size)
+            config.WriteInt("MDIEmbedTopRightVisible", self._topRightEmbWindow.IsShown())
+        if self._bottomRightEmbWindow:
+            if self._bottomRightEmbWindow._sizeBeforeHidden:
+                size = self._bottomRightEmbWindow._sizeBeforeHidden[1]
+            else:
+                size = self._bottomRightEmbWindow.GetSize()[1]
+            config.WriteInt("MDIEmbedBottomRightSize", size)
+            config.WriteInt("MDIEmbedBottomRightVisible", self._bottomRightEmbWindow.IsShown())
+        if self._topEmbWindow:
+            config.WriteInt("MDIEmbedTopSize", self._topEmbWindow.GetSize()[1])
+            config.WriteInt("MDIEmbedTopVisible", self._topEmbWindow.IsShown())
+        if self._bottomEmbWindow:
+            config.WriteInt("MDIEmbedBottomSize", self._bottomEmbWindow.GetSize()[1])
+            config.WriteInt("MDIEmbedBottomVisible", self._bottomEmbWindow.IsShown())
+
+
+    def GetEmbeddedWindow(self, loc):
+        """
+        Returns the instance of the embedded window specified by the embedded window location constant.
+        """
+        if loc == EMBEDDED_WINDOW_TOP:
+            return self._topEmbWindow
+        elif loc == EMBEDDED_WINDOW_BOTTOM:
+            return self._bottomEmbWindow
+        elif loc == EMBEDDED_WINDOW_LEFT:
+            return self._leftEmbWindow
+        elif loc == EMBEDDED_WINDOW_RIGHT:
+            return self._rightEmbWindow
+        elif loc == EMBEDDED_WINDOW_TOPLEFT:
+            return self._topLeftEmbWindow
+        elif loc == EMBEDDED_WINDOW_BOTTOMLEFT:
+            return self._bottomLeftEmbWindow
+        elif loc == EMBEDDED_WINDOW_TOPRIGHT:
+            return self._topRightEmbWindow
+        elif loc == EMBEDDED_WINDOW_BOTTOMRIGHT:
+            return self._bottomRightEmbWindow
+        return None
+
+
+    def _CreateEmbeddedWindow(self, parent, size, orientation, alignment, visible = True, sash = None):
+        """
+        Creates the embedded window with the specified size, orientation, and alignment.  If the 
+        window is not visible it will retain the size with which it was last viewed.
+        """
+        window = wx.SashLayoutWindow(parent, wx.NewId(), style = wx.NO_BORDER | wx.SW_3D)
+        window.SetDefaultSize(size)
+        window.SetOrientation(orientation)
+        window.SetAlignment(alignment)
+        if sash != None:  # wx.SASH_TOP is 0 so check for None instead of just doing "if sash:"
+            window.SetSashVisible(sash, True)
+        ####
+        def OnEmbeddedWindowSashDrag(event):
+            if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
+                return
+            sashWindow = event.GetEventObject()
+            if sashWindow.GetAlignment() == wx.LAYOUT_TOP or sashWindow.GetAlignment() == wx.LAYOUT_BOTTOM:
+                size = wx.Size(-1, event.GetDragRect().height)
+            else:
+                size = wx.Size(event.GetDragRect().width, -1)
+            event.GetEventObject().SetDefaultSize(size)
+            wx.LayoutAlgorithm().LayoutMDIFrame(self)
+            self.GetClientWindow().Refresh()
+            if isinstance(sashWindow.GetParent(), wx.SashLayoutWindow):
+                sashWindow.Show()
+                parentSashWindow = sashWindow.GetParent()  # Force a refresh
+                parentSashWindow.Layout()
+                parentSashWindow.Refresh()
+                parentSashWindow.SetSize((parentSashWindow.GetSize().width + 1, parentSashWindow.GetSize().height + 1))
+        ####
+        wx.EVT_SASH_DRAGGED(window, window.GetId(), OnEmbeddedWindowSashDrag)
+        window._sizeBeforeHidden = None
+        if not visible:
+            window.Show(False)
+            if isinstance(parent, wx.SashLayoutWindow): # It's a window embedded in another sash window so remember its actual size to show it again
+                window._sizeBeforeHidden = size
+        return window
+
+
+    def ShowEmbeddedWindow(self, window, show = True):
+        """
+        Shows or hides the embedded window specified by the embedded window location constant.
+        """
+        window.Show(show)
+        if isinstance(window.GetParent(), wx.SashLayoutWindow):  # It is a parent sashwindow with multiple embedded sashwindows
+            parentSashWindow = window.GetParent()
+            if show:  # Make sure it is visible in case all of the subwindows were hidden
+                parentSashWindow.Show()                
+            if show and window._sizeBeforeHidden:
+                if window._sizeBeforeHidden[1] == parentSashWindow.GetClientSize()[1]:
+                    if window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMLEFT) and self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPLEFT).IsShown():
+                        window.SetDefaultSize((window._sizeBeforeHidden[0], window._sizeBeforeHidden[0] - self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPLEFT).GetSize()[1]))
+                    elif window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPLEFT) and self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMLEFT).IsShown():
+                        window.SetDefaultSize((window._sizeBeforeHidden[0], window._sizeBeforeHidden[0] - self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMLEFT).GetSize()[1]))
+                    elif window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMRIGHT) and self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPRIGHT).IsShown():
+                        window.SetDefaultSize((window._sizeBeforeHidden[0], window._sizeBeforeHidden[0] - self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPRIGHT).GetSize()[1]))
+                    elif window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPRIGHT) and self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMRIGHT).IsShown():
+                        window.SetDefaultSize((window._sizeBeforeHidden[0], window._sizeBeforeHidden[0] - self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMRIGHT).GetSize()[1]))
+                    print window.GetSize()
+                else:
+                    window.SetDefaultSize(window._sizeBeforeHidden)
+                    # If it is not the size of the full parent sashwindow set the other window's size so that if it gets shown it will have a cooresponding size
+                    print "Parent size, size before hidden ", parentSashWindow.GetClientSize()[1], window._sizeBeforeHidden[1]
+                    if window._sizeBeforeHidden[1] < parentSashWindow.GetClientSize()[1]:
+                        otherWindowSize = (-1, parentSashWindow.GetClientSize()[1] - window._sizeBeforeHidden[1])
+                        print "Other", otherWindowSize
+                        if window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMLEFT):
+                            self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPLEFT).SetDefaultSize(otherWindowSize)
+                        elif window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPLEFT):
+                            self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMLEFT).SetDefaultSize(otherWindowSize)
+                        elif window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMRIGHT):
+                            self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPRIGHT).SetDefaultSize(otherWindowSize)
+                        elif window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPRIGHT):
+                            self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMRIGHT).SetDefaultSize(otherWindowSize)
+                    
+            if not show:
+                if window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMRIGHT) and not self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPRIGHT).IsShown() \
+                    or window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPRIGHT) and not self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMRIGHT).IsShown() \
+                    or window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMLEFT) and not self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPLEFT).IsShown() \
+                    or window == self.GetEmbeddedWindow(EMBEDDED_WINDOW_TOPLEFT) and not self.GetEmbeddedWindow(EMBEDDED_WINDOW_BOTTOMLEFT).IsShown():
+                    parentSashWindow.Hide()  # Hide the parent sashwindow if all of the children are hidden
+            parentSashWindow.Layout()   # Force a refresh
+            parentSashWindow.Refresh()
+            parentSashWindow.SetSize((parentSashWindow.GetSize().width + 1, parentSashWindow.GetSize().height + 1))
+        wx.LayoutAlgorithm().LayoutMDIFrame(self)
+        self.GetClientWindow().Refresh()
+
+
+    def HideEmbeddedWindow(self):
+        """
+        Hides the embedded window specified by the embedded window location constant.
+        """
+        self.ShowEmbeddedWindow(show = False)
+
+
+    def GetDocumentManager(self):
+        """
+        Returns the document manager associated with the DocMDIParentFrame.
+        """
+        return self._docManager
+
+
+    def InitializePrintData(self):
+        """
+        Initializes the PrintData that is used when printing.
+        """
+        self._printData = wx.PrintData()
+        self._printData.SetPaperId(wx.PAPER_LETTER)
+
+
+    def CreateDefaultStatusBar(self):
+        """
+        Creates the default StatusBar.
+        """
+        self.CreateStatusBar()
+        self.GetStatusBar().Show(wx.ConfigBase_Get().ReadInt("ViewStatusBar", True))
+        self.UpdateStatus()
+        return self.GetStatusBar()
+
+
+    def CreateDefaultToolBar(self):
+        """
+        Creates the default ToolBar.
+        """
+        self._toolBar = self.CreateToolBar(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT)
+        self._toolBar.AddSimpleTool(wx.ID_NEW, getNewBitmap(), _("New"), _("Creates a new document"))
+        self._toolBar.AddSimpleTool(wx.ID_OPEN, getOpenBitmap(), _("Open"), _("Opens an existing document"))
+        self._toolBar.AddSimpleTool(wx.ID_SAVE, getSaveBitmap(), _("Save"), _("Saves the active document"))
+        self._toolBar.AddSimpleTool(SAVEALL_ID, getSaveAllBitmap(), _("Save All"), _("Saves all the active documents"))
+        self._toolBar.AddSeparator()
+        self._toolBar.AddSimpleTool(wx.ID_PRINT, getPrintBitmap(), _("Print"), _("Displays full pages"))
+        self._toolBar.AddSimpleTool(wx.ID_PREVIEW, getPrintPreviewBitmap(), _("Print Preview"), _("Prints the active document"))
+        self._toolBar.AddSeparator()
+        self._toolBar.AddSimpleTool(wx.ID_CUT, getCutBitmap(), _("Cut"), _("Cuts the selection and puts it on the Clipboard"))
+        self._toolBar.AddSimpleTool(wx.ID_COPY, getCopyBitmap(), _("Copy"), _("Copies the selection and puts it on the Clipboard"))
+        self._toolBar.AddSimpleTool(wx.ID_PASTE, getPasteBitmap(), _("Paste"), _("Inserts Clipboard contents"))
+        self._toolBar.AddSimpleTool(wx.ID_UNDO, getUndoBitmap(), _("Undo"), _("Reverses the last action"))
+        self._toolBar.AddSimpleTool(wx.ID_REDO, getRedoBitmap(), _("Redo"), _("Reverses the last undo"))
+        self._toolBar.Realize()
+        self._toolBar.Show(wx.ConfigBase_Get().ReadInt("ViewToolBar", True))
+
+        return self._toolBar
+
+
+    def CreateDefaultMenuBar(self):
+        """
+        Creates the default MenuBar.  Contains File, Edit, View, Tools, and Help menus.
+        """
+        menuBar = wx.MenuBar()
+
+        fileMenu = wx.Menu()
+        fileMenu.Append(wx.ID_NEW, _("&New...\tCtrl+N"), _("Creates a new document"))
+        fileMenu.Append(wx.ID_OPEN, _("&Open...\tCtrl+O"), _("Opens an existing document"))
+        fileMenu.Append(wx.ID_CLOSE, _("&Close"), _("Closes the active document"))
+        fileMenu.Append(wx.ID_CLOSE_ALL, _("Close A&ll"), _("Closes all open documents"))
+        fileMenu.AppendSeparator()
+        fileMenu.Append(wx.ID_SAVE, _("&Save\tCtrl+S"), _("Saves the active document"))
+        fileMenu.Append(wx.ID_SAVEAS, _("Save &As..."), _("Saves the active document with a new name"))
+        fileMenu.Append(SAVEALL_ID, _("Save All\tCtrl+Shift+A"), _("Saves the all active documents"))
+        wx.EVT_MENU(self, SAVEALL_ID, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, SAVEALL_ID, self.ProcessUpdateUIEvent)
+        fileMenu.AppendSeparator()
+        fileMenu.Append(wx.ID_PRINT, _("&Print\tCtrl+P"), _("Prints the active document"))
+        fileMenu.Append(wx.ID_PREVIEW, _("Print Pre&view"), _("Displays full pages"))
+        fileMenu.Append(wx.ID_PRINT_SETUP, _("Page Set&up"), _("Changes page layout settings"))
+        fileMenu.AppendSeparator()
+        if wx.Platform == '__WXMAC__':
+            fileMenu.Append(wx.ID_EXIT, _("&Quit"), _("Closes this program"))
+        else:
+            fileMenu.Append(wx.ID_EXIT, _("E&xit"), _("Closes this program"))
+        self._docManager.FileHistoryUseMenu(fileMenu)
+        self._docManager.FileHistoryAddFilesToMenu()
+        menuBar.Append(fileMenu, _("&File"));
+
+        editMenu = wx.Menu()
+        editMenu.Append(wx.ID_UNDO, _("&Undo\tCtrl+Z"), _("Reverses the last action"))
+        editMenu.Append(wx.ID_REDO, _("&Redo\tCtrl+Y"), _("Reverses the last undo"))
+        editMenu.AppendSeparator()
+        #item = wxMenuItem(self.editMenu, wxID_CUT, _("Cu&t\tCtrl+X"), _("Cuts the selection and puts it on the Clipboard"))
+        #item.SetBitmap(getCutBitmap())
+        #editMenu.AppendItem(item)
+        editMenu.Append(wx.ID_CUT, _("Cu&t\tCtrl+X"), _("Cuts the selection and puts it on the Clipboard"))
+        wx.EVT_MENU(self, wx.ID_CUT, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CUT, self.ProcessUpdateUIEvent)
+        editMenu.Append(wx.ID_COPY, _("&Copy\tCtrl+C"), _("Copies the selection and puts it on the Clipboard"))
+        wx.EVT_MENU(self, wx.ID_COPY, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_COPY, self.ProcessUpdateUIEvent)
+        editMenu.Append(wx.ID_PASTE, _("&Paste\tCtrl+V"), _("Inserts Clipboard contents"))
+        wx.EVT_MENU(self, wx.ID_PASTE, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PASTE, self.ProcessUpdateUIEvent)
+        editMenu.Append(wx.ID_CLEAR, _("Cle&ar\tDel"), _("Erases the selection"))
+        wx.EVT_MENU(self, wx.ID_CLEAR, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLEAR, self.ProcessUpdateUIEvent)
+        editMenu.AppendSeparator()
+        editMenu.Append(wx.ID_SELECTALL, _("Select A&ll\tCtrl+A"), _("Selects all available data"))
+        wx.EVT_MENU(self, wx.ID_SELECTALL, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SELECTALL, self.ProcessUpdateUIEvent)
+        menuBar.Append(editMenu, _("&Edit"))
+
+        viewMenu = wx.Menu()
+        viewMenu.AppendCheckItem(VIEW_TOOLBAR_ID, _("&Toolbar"), _("Shows or hides the toolbar"))
+        wx.EVT_MENU(self, VIEW_TOOLBAR_ID, self.OnViewToolBar)
+        wx.EVT_UPDATE_UI(self, VIEW_TOOLBAR_ID, self.OnUpdateViewToolBar)
+        viewMenu.AppendCheckItem(VIEW_STATUSBAR_ID, _("&Status Bar"), _("Shows or hides the status bar"))
+        wx.EVT_MENU(self, VIEW_STATUSBAR_ID, self.OnViewStatusBar)
+        wx.EVT_UPDATE_UI(self, VIEW_STATUSBAR_ID, self.OnUpdateViewStatusBar)
+        menuBar.Append(viewMenu, _("&View"))
+
+        helpMenu = wx.Menu()
+        helpMenu.Append(wx.ID_ABOUT, _("&About" + " " + wx.GetApp().GetAppName()), _("Displays program information, version number, and copyright"))
+        wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
+        menuBar.Append(helpMenu, _("&Help"))
+
+##        windowMenu = wx.Menu()
+##        menuBar.Append(windowMenu, _("&Window"))
+##        # self.SetWindowMenu(windowMenu)
+##
+        wx.EVT_UPDATE_UI(self, wx.ID_ABOUT, self.ProcessUpdateUIEvent)  # Using ID_ABOUT to update the window menu, the window menu items are not triggering
+
+        return menuBar
+
+##        accelTable = wx.AcceleratorTable([
+##            eval(_("wx.ACCEL_CTRL, ord('Z'), wx.ID_UNDO")),
+##            eval(_("wx.ACCEL_CTRL, ord('Y'), wx.ID_REDO")),
+##            eval(_("wx.ACCEL_CTRL, ord('X'), wx.ID_CUT")),
+##            eval(_("wx.ACCEL_CTRL, ord('C'), wx.ID_COPY")),
+##            eval(_("wx.ACCEL_CTRL, ord('V'), wx.ID_PASTE")),
+##            (wx.ACCEL_NORMAL, wx.WXK_DELETE, wx.ID_CLEAR),
+##            eval(_("wx.ACCEL_CTRL, ord('A'), wx.ID_SELECTALL")),
+##            eval(_("wx.ACCEL_CTRL, ord('N'), wx.ID_NEW")),
+##            eval(_("wx.ACCEL_CTRL, ord('O'), wx.ID_OPEN")),
+##            eval(_("wx.ACCEL_CTRL, ord('S'), wx.ID_SAVE"))
+##            ])
+##        self.SetAcceleratorTable(accelTable)
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if wx.GetApp().ProcessEventBeforeWindows(event):
+            return True
+        if wx.lib.docview.DocMDIParentFrame.ProcessEvent(self, event):
+            return True
+            
+        id = event.GetId()
+        if id == SAVEALL_ID:
+            self.OnFileSaveAll(event)
+            return True
+            
+        return wx.GetApp().ProcessEvent(event)
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if wx.GetApp().ProcessUpdateUIEventBeforeWindows(event):
+            return True
+        if wx.lib.docview.DocMDIParentFrame.ProcessUpdateUIEvent(self, event):  # Let the views handle the event before the services
+            return True
+        id = event.GetId()
+        if id == wx.ID_CUT:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_COPY:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_PASTE:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_CLEAR:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_SELECTALL:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_ABOUT:  # Using ID_ABOUT to update the window menu, the window menu items are not triggering
+            self.UpdateWindowMenu()
+            return True
+        elif id == SAVEALL_ID:
+            filesModified = False
+            docs = wx.GetApp().GetDocumentManager().GetDocuments()
+            for doc in docs:
+                if doc.IsModified():
+                    filesModified = True
+                    break
+                
+            event.Enable(filesModified)
+            return True
+        else:
+            return wx.GetApp().ProcessUpdateUIEvent(event)
+
+
+    def UpdateWindowMenu(self):
+        """
+        Updates the WindowMenu Windows platforms.
+        """
+        if wx.Platform == '__WXMSW__':
+            children = filter(lambda child: isinstance(child, wx.MDIChildFrame), self.GetChildren())
+            windowCount = len(children)
+            hasWindow = windowCount >= 1
+            has2OrMoreWindows = windowCount >= 2
+
+            windowMenu = self.GetWindowMenu()
+            windowMenu.Enable(wx.IDM_WINDOWTILE, hasWindow)
+            windowMenu.Enable(wx.IDM_WINDOWTILEHOR, hasWindow)
+            windowMenu.Enable(wx.IDM_WINDOWCASCADE, hasWindow)
+            windowMenu.Enable(wx.IDM_WINDOWICONS, hasWindow)
+            windowMenu.Enable(wx.IDM_WINDOWTILEVERT, hasWindow)
+            wx.IDM_WINDOWPREV = 4006  # wxBug: Not defined for some reason
+            windowMenu.Enable(wx.IDM_WINDOWPREV, has2OrMoreWindows)
+            windowMenu.Enable(wx.IDM_WINDOWNEXT, has2OrMoreWindows)
+
+
+    def OnFileSaveAll(self, event):
+        """
+        Saves all of the currently open documents.
+        """
+        docs = wx.GetApp().GetDocumentManager().GetDocuments()
+        for doc in docs:
+            doc.Save()
+            
+
+    def OnCloseWindow(self, event):
+        """
+        Called when the DocMDIParentFrame is closed.  Remembers the frame size.
+        """
+        config = wx.ConfigBase_Get()
+        if not self.IsMaximized():
+            config.WriteInt("MDIFrameXLoc", self.GetPositionTuple()[0])
+            config.WriteInt("MDIFrameYLoc", self.GetPositionTuple()[1])
+            config.WriteInt("MDIFrameXSize", self.GetSizeTuple()[0])
+            config.WriteInt("MDIFrameYSize", self.GetSizeTuple()[1])
+        config.WriteInt("MDIFrameMaximized", self.IsMaximized())
+        config.WriteInt("ViewToolBar", self._toolBar.IsShown())
+        config.WriteInt("ViewStatusBar", self.GetStatusBar().IsShown())
+
+        self.SaveEmbeddedWindowSizes()
+
+        # save and close services last.
+        for service in wx.GetApp().GetServices():
+            if not service.OnCloseFrame(event):
+                return
+
+        # save and close documents
+        # documents with a common view, e.g. project view, should save the document, but not close the window
+        # and let the service close the window.
+        wx.lib.docview.DocMDIParentFrame.OnCloseWindow(self, event)
+
+
+    def OnAbout(self, event):
+        """
+        Invokes the about dialog.
+        """
+        _AboutDialog(self)
+
+
+    def OnViewToolBar(self, event):
+        """
+        Toggles whether the ToolBar is visible.
+        """
+        self._toolBar.Show(not self._toolBar.IsShown())
+        wx.LayoutAlgorithm().LayoutMDIFrame(self)
+        self.GetClientWindow().Refresh()
+
+
+    def OnUpdateViewToolBar(self, event):
+        """
+        Updates the View ToolBar menu item.
+        """
+        event.Check(self.GetToolBar().IsShown())
+
+
+    def OnViewStatusBar(self, event):
+        """
+        Toggles whether the StatusBar is visible.
+        """
+        self.GetStatusBar().Show(not self.GetStatusBar().IsShown())
+        self.Layout()
+        wx.LayoutAlgorithm().LayoutMDIFrame(self)
+        self.GetClientWindow().Refresh()
+
+
+    def OnUpdateViewStatusBar(self, event):
+        """
+        Updates the View StatusBar menu item.
+        """
+        event.Check(self.GetStatusBar().IsShown())
+
+
+    def UpdateStatus(self, message = _("Ready")):
+        """
+        Updates the StatusBar.
+        """
+        # wxBug: Menubar and toolbar help strings don't pop the status text back
+        if self.GetStatusBar().GetStatusText() != message:
+            self.GetStatusBar().PushStatusText(message)
+
+
+    def OnSize(self, event):
+        """
+        Called when the DocMDIParentFrame is resized and lays out the MDI client window.
+        """
+        # Needed in case there are splitpanels around the mdi frame
+        wx.LayoutAlgorithm().LayoutMDIFrame(self)
+        self.GetClientWindow().Refresh()
+
+
+class DocSDIFrame(wx.lib.docview.DocChildFrame):
+    """
+    The DocSDIFrame host DocManager Document windows.  It offers features such as a default menubar,
+    toolbar, and status bar.
+    """
+    
+
+    def __init__(self, doc, view, parent, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "DocSDIFrame"):
+        """
+        Initializes the DocSDIFrame with the default menubar, toolbar, and status bar.
+        """
+        wx.lib.docview.DocChildFrame.__init__(self, doc, view, parent, id, title, pos, size, style, name)
+        self._fileMenu = None
+        if doc:
+            self._docManager = doc.GetDocumentManager()
+        else:
+            self._docManager = None
+        self.SetDropTarget(_DocFrameFileDropTarget(self._docManager, self))
+
+        wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
+        wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit)
+        wx.EVT_MENU_RANGE(self, wx.ID_FILE1, wx.ID_FILE9, self.OnMRUFile)
+
+        self.InitializePrintData()
+
+        menuBar = self.CreateDefaultMenuBar()
+        toolBar = self.CreateDefaultToolBar()
+        self.SetToolBar(toolBar)
+        statusBar = self.CreateDefaultStatusBar()
+
+        for service in wx.GetApp().GetServices():
+            service.InstallControls(self, menuBar = menuBar, toolBar = toolBar, statusBar = statusBar, document = doc)
+
+        self.SetMenuBar(menuBar)  # wxBug: Need to do this in SDI to mimic MDI... because have to set the menubar at the very end or the automatic MDI "window" menu doesn't get put in the right place when the services add new menus to the menubar
+
+
+    def GetDocumentManager(self):
+        """
+        Returns the document manager associated with the DocSDIFrame.
+        """
+        return self._docManager
+
+
+    def OnExit(self, event):
+        """
+        Called when the application is exitting.
+        """
+        if self._childView.GetDocumentManager().Clear(force = False):
+            self.Destroy()
+        else:
+            event.Veto()
+
+
+    def OnMRUFile(self, event):
+        """
+        Opens the appropriate file when it is selected from the file history
+        menu.
+        """
+        n = event.GetId() - wx.ID_FILE1
+        filename = self._docManager.GetHistoryFile(n)
+        if filename:
+            self._docManager.CreateDocument(filename, wx.lib.docview.DOC_SILENT)
+        else:
+            self._docManager.RemoveFileFromHistory(n)
+            msgTitle = wx.GetApp().GetAppName()
+            if not msgTitle:
+                msgTitle = _("File Error")
+            wx.MessageBox("The file '%s' doesn't exist and couldn't be opened.\nIt has been removed from the most recently used files list" % docview.FileNameFromPath(file),
+                          msgTitle,
+                          wx.OK | wx.ICON_EXCLAMATION,
+                          self)
+
+
+    def InitializePrintData(self):
+        """
+        Initializes the PrintData that is used when printing.
+        """
+        self._printData = wx.PrintData()
+        self._printData.SetPaperId(wx.PAPER_LETTER)
+
+
+    def CreateDefaultStatusBar(self):
+        """
+        Creates the default StatusBar.
+        """
+        wx.lib.docview.DocChildFrame.CreateStatusBar(self)
+        self.GetStatusBar().Show(wx.ConfigBase_Get().ReadInt("ViewStatusBar", True))
+        self.UpdateStatus()
+        return self.GetStatusBar()
+
+
+    def CreateDefaultToolBar(self):
+        """
+        Creates the default ToolBar.
+        """
+        self._toolBar = self.CreateToolBar(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT)
+        self._toolBar.AddSimpleTool(wx.ID_NEW, getNewBitmap(), _("New"), _("Creates a new document"))
+        self._toolBar.AddSimpleTool(wx.ID_OPEN, getOpenBitmap(), _("Open"), _("Opens an existing document"))
+        self._toolBar.AddSimpleTool(wx.ID_SAVE, getSaveBitmap(), _("Save"), _("Saves the active document"))
+        self._toolBar.AddSimpleTool(SAVEALL_ID, getSaveAllBitmap(), _("Save All"), _("Saves all the active documents"))
+        self._toolBar.AddSeparator()
+        self._toolBar.AddSimpleTool(wx.ID_PRINT, getPrintBitmap(), _("Print"), _("Displays full pages"))
+        self._toolBar.AddSimpleTool(wx.ID_PREVIEW, getPrintPreviewBitmap(), _("Print Preview"), _("Prints the active document"))
+        self._toolBar.AddSeparator()
+        self._toolBar.AddSimpleTool(wx.ID_CUT, getCutBitmap(), _("Cut"), _("Cuts the selection and puts it on the Clipboard"))
+        self._toolBar.AddSimpleTool(wx.ID_COPY, getCopyBitmap(), _("Copy"), _("Copies the selection and puts it on the Clipboard"))
+        self._toolBar.AddSimpleTool(wx.ID_PASTE, getPasteBitmap(), _("Paste"), _("Inserts Clipboard contents"))
+        self._toolBar.AddSimpleTool(wx.ID_UNDO, getUndoBitmap(), _("Undo"), _("Reverses the last action"))
+        self._toolBar.AddSimpleTool(wx.ID_REDO, getRedoBitmap(), _("Redo"), _("Reverses the last undo"))
+        self._toolBar.Realize()
+        self._toolBar.Show(wx.ConfigBase_Get().ReadInt("ViewToolBar", True))
+        return self._toolBar
+
+
+    def CreateDefaultMenuBar(self):
+        """
+        Creates the default MenuBar.  Contains File, Edit, View, Tools, and Help menus.
+        """
+        menuBar = wx.MenuBar()
+
+        fileMenu = wx.Menu()
+        self._fileMenu = fileMenu
+        fileMenu.Append(wx.ID_NEW, _("&New...\tCtrl+N"), _("Creates a new document"))
+        fileMenu.Append(wx.ID_OPEN, _("&Open...\tCtrl+O"), _("Opens an existing document"))
+        fileMenu.Append(wx.ID_CLOSE, _("&Close"), _("Closes the active document"))
+        # fileMenu.Append(wx.ID_CLOSE_ALL, _("Close A&ll"), _("Closes all open documents"))
+        fileMenu.AppendSeparator()
+        fileMenu.Append(wx.ID_SAVE, _("&Save\tCtrl+S"), _("Saves the active document"))
+        fileMenu.Append(wx.ID_SAVEAS, _("Save &As..."), _("Saves the active document with a new name"))
+        fileMenu.Append(SAVEALL_ID, _("Save All\tCtrl+Shift+A"), _("Saves the all active documents"))
+        wx.EVT_MENU(self, SAVEALL_ID, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, SAVEALL_ID, self.ProcessUpdateUIEvent)
+        fileMenu.AppendSeparator()
+        fileMenu.Append(wx.ID_PRINT, _("&Print\tCtrl+P"), _("Prints the active document"))
+        fileMenu.Append(wx.ID_PREVIEW, _("Print Pre&view"), _("Displays full pages"))
+        fileMenu.Append(wx.ID_PRINT_SETUP, _("Page Set&up"), _("Changes page layout settings"))
+        fileMenu.AppendSeparator()
+        if wx.Platform == '__WXMAC__':
+            fileMenu.Append(wx.ID_EXIT, _("&Quit"), _("Closes this program"))
+        else:
+            fileMenu.Append(wx.ID_EXIT, _("E&xit"), _("Closes this program"))
+        if self._docManager:
+            self._docManager.FileHistoryUseMenu(fileMenu)
+            self._docManager.FileHistoryAddFilesToMenu(fileMenu)
+        menuBar.Append(fileMenu, _("&File"));
+
+        editMenu = wx.Menu()
+        editMenu.Append(wx.ID_UNDO, _("&Undo\tCtrl+Z"), _("Reverses the last action"))
+        editMenu.Append(wx.ID_REDO, _("&Redo\tCtrl+Y"), _("Reverses the last undo"))
+        editMenu.AppendSeparator()
+        editMenu.Append(wx.ID_CUT, _("Cu&t\tCtrl+X"), _("Cuts the selection and puts it on the Clipboard"))
+        wx.EVT_MENU(self, wx.ID_CUT, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CUT, self.ProcessUpdateUIEvent)
+        editMenu.Append(wx.ID_COPY, _("&Copy\tCtrl+C"), _("Copies the selection and puts it on the Clipboard"))
+        wx.EVT_MENU(self, wx.ID_COPY, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_COPY, self.ProcessUpdateUIEvent)
+        editMenu.Append(wx.ID_PASTE, _("&Paste\tCtrl+V"), _("Inserts Clipboard contents"))
+        wx.EVT_MENU(self, wx.ID_PASTE, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_PASTE, self.ProcessUpdateUIEvent)
+        editMenu.Append(wx.ID_CLEAR, _("Cle&ar\tDel"), _("Erases the selection"))
+        wx.EVT_MENU(self, wx.ID_CLEAR, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_CLEAR, self.ProcessUpdateUIEvent)
+        editMenu.AppendSeparator()
+        editMenu.Append(wx.ID_SELECTALL, _("Select A&ll\tCtrl+A"), _("Selects all available data"))
+        wx.EVT_MENU(self, wx.ID_SELECTALL, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(self, wx.ID_SELECTALL, self.ProcessUpdateUIEvent)
+        menuBar.Append(editMenu, _("&Edit"))
+        if self.GetDocument() and self.GetDocument().GetCommandProcessor():
+            self.GetDocument().GetCommandProcessor().SetEditMenu(editMenu)
+
+        viewMenu = wx.Menu()
+        viewMenu.AppendCheckItem(VIEW_TOOLBAR_ID, _("&Toolbar"), _("Shows or hides the toolbar"))
+        wx.EVT_MENU(self, VIEW_TOOLBAR_ID, self.OnViewToolBar)
+        wx.EVT_UPDATE_UI(self, VIEW_TOOLBAR_ID, self.OnUpdateViewToolBar)
+        viewMenu.AppendCheckItem(VIEW_STATUSBAR_ID, _("&Status Bar"), _("Shows or hides the status bar"))
+        wx.EVT_MENU(self, VIEW_STATUSBAR_ID, self.OnViewStatusBar)
+        wx.EVT_UPDATE_UI(self, VIEW_STATUSBAR_ID, self.OnUpdateViewStatusBar)
+        menuBar.Append(viewMenu, _("&View"))
+
+        helpMenu = wx.Menu()
+        helpMenu.Append(wx.ID_ABOUT, _("&About" + " " + wx.GetApp().GetAppName()), _("Displays program information, version number, and copyright"))
+        wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
+        menuBar.Append(helpMenu, _("&Help"))
+
+        wx.EVT_COMMAND_FIND_CLOSE(self, -1, self.ProcessEvent)
+
+        return menuBar
+##        accelTable = wx.AcceleratorTable([
+##            eval(_("wx.ACCEL_CTRL, ord('N'), wx.ID_NEW")),
+##            eval(_("wx.ACCEL_CTRL, ord('O'), wx.ID_OPEN")),
+##            eval(_("wx.ACCEL_CTRL, ord('S'), wx.ID_SAVE")),
+##            eval(_("wx.ACCEL_CTRL, ord('Z'), wx.ID_UNDO")),
+##            eval(_("wx.ACCEL_CTRL, ord('Y'), wx.ID_REDO")),
+##            eval(_("wx.ACCEL_CTRL, ord('X'), wx.ID_CUT")),
+##            eval(_("wx.ACCEL_CTRL, ord('C'), wx.ID_COPY")),
+##            eval(_("wx.ACCEL_CTRL, ord('Z'), wx.ID_PASTE")),
+##            (wx.ACCEL_NORMAL, wx.WXK_DELETE, wx.ID_CLEAR),
+##            eval(_("wx.ACCEL_CTRL, ord('A'), wx.ID_SELECTALL"))
+##            ])
+##        self.SetAcceleratorTable(accelTable)
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes an event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if wx.GetApp().ProcessEventBeforeWindows(event):
+            return True
+        if self._childView:
+            self._childView.Activate(True)
+
+        id = event.GetId()
+        if id == SAVEALL_ID:
+            self.OnFileSaveAll(event)
+            return True
+
+        if hasattr(self._childView, "GetDocumentManager") and self._childView.GetDocumentManager().ProcessEvent(event):  # Need to call docmanager here since super class relies on DocParentFrame which we are not using
+            return True
+        else:
+            return wx.GetApp().ProcessEvent(event)
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Processes a UI event, searching event tables and calling zero or more
+        suitable event handler function(s).  Note that the ProcessEvent
+        method is called from the wxPython docview framework directly since
+        wxPython does not have a virtual ProcessEvent function.
+        """
+        if wx.GetApp().ProcessUpdateUIEventBeforeWindows(event):
+            return True
+        if self._childView:
+            if hasattr(self._childView, "GetDocumentManager"):
+                docMgr = self._childView.GetDocumentManager()
+                if docMgr:
+                    if docMgr.GetCurrentDocument() != self._childView.GetDocument():
+                        return False
+                    if docMgr.ProcessUpdateUIEvent(event):  # Let the views handle the event before the services
+                        return True
+        id = event.GetId()
+        if id == wx.ID_CUT:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_COPY:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_PASTE:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_CLEAR:
+            event.Enable(False)
+            return True
+        elif id == wx.ID_SELECTALL:
+            event.Enable(False)
+            return True
+        elif id == SAVEALL_ID:
+            filesModified = False
+            docs = wx.GetApp().GetDocumentManager().GetDocuments()
+            for doc in docs:
+                if doc.IsModified():
+                    filesModified = True
+                    break
+                
+            event.Enable(filesModified)
+            return True
+        else:
+            return wx.GetApp().ProcessUpdateUIEvent(event)
+
+
+    def OnFileSaveAll(self, event):
+        """
+        Saves all of the currently open documents.
+        """
+        docs = wx.GetApp().GetDocumentManager().GetDocuments()
+        for doc in docs:
+            doc.Save()
+
+
+    def OnAbout(self, event):
+        """
+        Invokes the about dialog.
+        """
+        _AboutDialog(self)
+
+
+    def OnViewToolBar(self, event):
+        """
+        Toggles whether the ToolBar is visible.
+        """
+        self._toolBar.Show(not self._toolBar.IsShown())
+        self.Layout()
+
+
+    def OnUpdateViewToolBar(self, event):
+        """
+        Updates the View ToolBar menu item.
+        """
+        event.Check(self.GetToolBar().IsShown())
+
+
+    def OnViewStatusBar(self, event):
+        """
+        Toggles whether the StatusBar is visible.
+        """
+        self.GetStatusBar().Show(not self.GetStatusBar().IsShown())
+        self.Layout()
+
+
+    def OnUpdateViewStatusBar(self, event):
+        """
+        Updates the View StatusBar menu item.
+        """
+        event.Check(self.GetStatusBar().IsShown())
+
+
+    def UpdateStatus(self, message = _("Ready")):
+        """
+        Updates the StatusBar.
+        """
+        # wxBug: Menubar and toolbar help strings don't pop the status text back
+        if self.GetStatusBar().GetStatusText() != message:
+            self.GetStatusBar().PushStatusText(message)
+
+
+    def OnCloseWindow(self, event):
+        """
+        Called when the window is saved.  Enables services to help close the frame.
+        """
+        for service in wx.GetApp().GetServices():
+            service.OnCloseFrame(event)
+        wx.lib.docview.DocChildFrame.OnCloseWindow(self, event)
+        if self._fileMenu and self._docManager:
+            self._docManager.FileHistoryRemoveMenu(self._fileMenu)
+
+
+class FilePropertiesService(DocService):
+    """
+    Service that installas under the File menu to show the properties of the file associated
+    with the current document.
+    """
+
+    PROPERTIES_ID = wx.NewId()
+
+
+    def __init__(self):
+        """
+        Initializes the PropertyService.
+        """
+        self._customEventHandlers = []
+
+
+    def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
+        """
+        Installs a File/Properties menu item.
+        """
+        fileMenu = menuBar.GetMenu(menuBar.FindMenu(_("&File")))
+        exitMenuItemPos = self.GetMenuItemPos(fileMenu, wx.ID_EXIT)
+        fileMenu.InsertSeparator(exitMenuItemPos)
+        fileMenu.Insert(exitMenuItemPos, FilePropertiesService.PROPERTIES_ID, _("&Properties"), _("Show file properties"))
+        wx.EVT_MENU(frame, FilePropertiesService.PROPERTIES_ID, self.ProcessEvent)
+        wx.EVT_UPDATE_UI(frame, FilePropertiesService.PROPERTIES_ID, self.ProcessUpdateUIEvent)
+
+
+    def ProcessEvent(self, event):
+        """
+        Detects when the File/Properties menu item is selected.
+        """
+        id = event.GetId()
+        if id == FilePropertiesService.PROPERTIES_ID:
+            for eventHandler in self._customEventHandlers:
+                if eventHandler.ProcessEvent(event):
+                    return True
+
+            self.ShowPropertiesDialog()
+            return True
+        else:
+            return False
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Updates the File/Properties menu item.
+        """
+        id = event.GetId()
+        if id == FilePropertiesService.PROPERTIES_ID:
+            for eventHandler in self._customEventHandlers:
+                if eventHandler.ProcessUpdateUIEvent(event):
+                    return True
+
+            event.Enable(wx.GetApp().GetDocumentManager().GetCurrentDocument() != None)
+            return True
+        else:
+            return False
+
+
+    def ShowPropertiesDialog(self, filename = None):
+        """
+        Shows the PropertiesDialog for the specified file.
+        """
+        if not filename:
+            filename = wx.GetApp().GetDocumentManager().GetCurrentDocument().GetFilename()
+
+        filePropertiesDialog = FilePropertiesDialog(wx.GetApp().GetTopWindow(), filename)
+        if filePropertiesDialog.ShowModal() == wx.ID_OK:
+            pass  # Handle OK
+        filePropertiesDialog.Destroy()
+
+
+    def GetCustomEventHandlers(self):
+        """
+        Returns the custom event handlers for the PropertyService.
+        """
+        return self._customEventHandlers
+
+
+    def AddCustomEventHandler(self, handler):
+        """
+        Adds a custom event handlers for the PropertyService.  A custom event handler enables
+        a different dialog to be provided for a particular file.
+        """
+        self._customEventHandlers.append(handler)
+
+
+    def RemoveCustomEventHandler(self, handler):
+        """
+        Removes a custom event handler from the PropertyService.
+        """
+        self._customEventHandlers.remove(handler)
+
+
+    def chopPath(self, text, length = 36):
+        """
+        Simple version of textwrap.  textwrap.fill() unfortunately chops lines at spaces
+        and creates odd word boundaries.  Instead, we will chop the path without regard to
+        spaces, but pay attention to path delimiters.
+        """
+        chopped = None
+        textLen = len(text)
+        start = 0
+
+        while start < textLen:
+            end = start + length
+            if end > textLen:
+                end = textLen
+
+            # see if we can find a delimiter to chop the path
+            if end < textLen:
+                lastSep = text.rfind(os.sep, start, end + 1)
+                if lastSep != -1 and lastSep != start:
+                    end = lastSep
+
+            if chopped:
+                chopped = chopped + '\n' + text[start:end]
+            else:
+                chopped = text[start:end]
+
+            start = end
+
+        return chopped
+
+
+class FilePropertiesDialog(wx.Dialog):
+    """
+    Dialog that shows the properties of a file.  Invoked by the PropertiesService.
+    """
+
+
+    def __init__(self, parent, filename):
+        """
+        Initializes the properties dialog.
+        """
+        wx.Dialog.__init__(self, parent, -1, _("File Properties"), size = (310, 330))
+
+        HALF_SPACE = 5
+        SPACE = 10
+
+        filePropertiesService = wx.GetApp().GetService(FilePropertiesService)
+
+        notebook = wx.Notebook(self, -1)
+        tab = wx.Panel(notebook, -1)
+
+        gridSizer = RowColSizer()
+
+        gridSizer.Add(wx.StaticText(tab, -1, _("Filename:")), flag=wx.RIGHT, border=HALF_SPACE, row=0, col=0)
+        gridSizer.Add(wx.StaticText(tab, -1, os.path.basename(filename)), row=0, col=1)
+
+        gridSizer.Add(wx.StaticText(tab, -1, _("Location:")), flag=wx.RIGHT, border=HALF_SPACE, row=1, col=0)
+        gridSizer.Add(wx.StaticText(tab, -1, filePropertiesService.chopPath(os.path.dirname(filename))), flag=wx.BOTTOM, border=SPACE, row=1, col=1)
+
+        gridSizer.Add(wx.StaticText(tab, -1, _("Size:")), flag=wx.RIGHT, border=HALF_SPACE, row=2, col=0)
+        gridSizer.Add(wx.StaticText(tab, -1, str(os.path.getsize(filename)) + ' ' + _("bytes")), row=2, col=1)
+
+        lineSizer = wx.BoxSizer(wx.VERTICAL)    # let the line expand horizontally without vertical expansion
+        lineSizer.Add(wx.StaticLine(tab, -1, size = (10,-1)), 0, wx.EXPAND)
+        gridSizer.Add(lineSizer, flag=wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.TOP, border=HALF_SPACE, row=3, col=0, colspan=2)
+
+        gridSizer.Add(wx.StaticText(tab, -1, _("Created:")), flag=wx.RIGHT, border=HALF_SPACE, row=4, col=0)
+        gridSizer.Add(wx.StaticText(tab, -1, time.ctime(os.path.getctime(filename))), row=4, col=1)
+
+        gridSizer.Add(wx.StaticText(tab, -1, _("Modified:")), flag=wx.RIGHT, border=HALF_SPACE, row=5, col=0)
+        gridSizer.Add(wx.StaticText(tab, -1, time.ctime(os.path.getmtime(filename))), row=5, col=1)
+
+        gridSizer.Add(wx.StaticText(tab, -1, _("Accessed:")), flag=wx.RIGHT, border=HALF_SPACE, row=6, col=0)
+        gridSizer.Add(wx.StaticText(tab, -1, time.ctime(os.path.getatime(filename))), row=6, col=1)
+
+        # add a border around the inside of the tab
+        spacerGrid = wx.BoxSizer(wx.VERTICAL)
+        spacerGrid.Add(gridSizer, 0, wx.ALL, SPACE);
+        tab.SetSizer(spacerGrid)
+        notebook.AddPage(tab, _("General"))
+        notebook.SetPageSize((310,200))
+
+        sizer = wx.BoxSizer(wx.VERTICAL)
+        sizer.Add(notebook, 0, wx.ALL | wx.EXPAND, SPACE)
+        sizer.Add(self.CreateButtonSizer(wx.OK), 0, wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM, HALF_SPACE)
+
+        sizer.Fit(self)
+        self.SetDimensions(-1, -1, 310, -1, wx.SIZE_USE_EXISTING)
+        self.SetSizer(sizer)
+        self.Layout()
+
+
+class ChildDocument(wx.lib.docview.Document):
+    """
+    A ChildDocument is a document that represents a portion of a Document.  The child
+    document is managed by the parent document, so it will be prompted to close if its
+    parent is closed, etc.  Child Documents are useful when there are complicated 
+    Views of a Document and users will need to tunnel into the View.
+    """
+
+
+    def GetData(self):
+        """
+        Returns the data that the ChildDocument contains.
+        """
+        return self._data
+
+
+    def SetData(self, data):
+        """
+        Sets the data that the ChildDocument contains.
+        """
+        self._data = data
+
+
+    def GetParentDocument(self):
+        """
+        Returns the parent Document of the ChildDocument.
+        """
+        return self._parentDocument
+
+
+    def SetParentDocument(self, parentDocument):
+        """
+        Sets the parent Document of the ChildDocument.
+        """        
+        self._parentDocument = parentDocument
+
+
+    def OnSaveDocument(self, filename):
+        """
+        Called when the ChildDocument is saved and does the minimum such that the
+        ChildDocument looks like a real Document to the framework.
+        """
+        self.SetFilename(filename, True)
+        self.Modify(False)
+        self.SetDocumentSaved(True)
+        return True
+
+
+    def OnOpenDocument(self, filename):
+        """
+        Called when the ChildDocument is opened and does the minimum such that the
+        ChildDocument looks like a real Document to the framework.
+        """
+        self.SetFilename(filename, True)
+        self.Modify(False)
+        self.SetDocumentSaved(True)
+        self.UpdateAllViews()
+        return True
+
+
+class ChildDocTemplate(wx.lib.docview.DocTemplate):
+    """
+    A ChildDocTemplate is a DocTemplate subclass that enables the creation of ChildDocuments
+    that represents a portion of a Document.  The child document is managed by the parent document,
+    so it will be prompted to close if its parent is closed, etc.  Child Documents are useful
+    when there are complicated  Views of a Document and users will need to tunnel into the View.
+    """    
+
+
+    def __init__(self, manager, description, filter, dir, ext, docTypeName, viewTypeName, docType, viewType, flags = wx.lib.docview.TEMPLATE_INVISIBLE, icon = None):
+        """
+        Initializes the ChildDocTemplate.
+        """
+        wx.lib.docview.DocTemplate.__init__(self, manager, description, filter, dir, ext, docTypeName, viewTypeName, docType, viewType, flags = flags, icon = icon)
+
+
+    def CreateDocument(self, path, flags, data = None, parentDocument = None):
+        """
+        Called when a ChildDocument is to be created and does the minimum such that the
+        ChildDocument looks like a real Document to the framework.
+        """
+        doc = self._docType()
+        doc.SetFilename(path)
+        doc.SetData(data)
+        doc.SetParentDocument(parentDocument)
+        doc.SetDocumentTemplate(self)
+        self.GetDocumentManager().AddDocument(doc)
+        doc.SetCommandProcessor(doc.OnCreateCommandProcessor())
+        if doc.OnCreate(path, flags):
+            return doc
+        else:
+            if doc in self.GetDocumentManager().GetDocuments():
+                doc.DeleteAllViews()
+            return None
+
+
+class WindowMenuService(DocService):
+    """
+    The WindowMenuService is a service that implements a standard Window menu that is used
+    by the DocSDIFrame.  The MDIFrame automatically includes a Window menu and does not use
+    the WindowMenuService.
+    """
+    
+
+    def __init__(self):
+        """
+        Initializes the WindowMenu and its globals.
+        """
+        self.ARRANGE_WINDOWS_ID = wx.NewId()
+        self.SELECT_WINDOW_1_ID = wx.NewId()
+        self.SELECT_WINDOW_2_ID = wx.NewId()
+        self.SELECT_WINDOW_3_ID = wx.NewId()
+        self.SELECT_WINDOW_4_ID = wx.NewId()
+        self.SELECT_WINDOW_5_ID = wx.NewId()
+        self.SELECT_WINDOW_6_ID = wx.NewId()
+        self.SELECT_WINDOW_7_ID = wx.NewId()
+        self.SELECT_WINDOW_8_ID = wx.NewId()
+        self.SELECT_WINDOW_9_ID = wx.NewId()
+        self.SELECT_MORE_WINDOWS_ID = wx.NewId()
+
+
+    def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
+        """
+        Installs the Window menu.
+        """
+
+        if not self.GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI:
+            return  # Only need windows menu for SDI mode, MDI frame automatically creates one
+
+        windowMenu = wx.Menu()
+        windowMenu.Append(self.ARRANGE_WINDOWS_ID, _("&Arrange All"), _("Arrange the open windows"))
+        windowMenu.AppendSeparator()
+
+        wx.EVT_MENU(frame, self.ARRANGE_WINDOWS_ID, frame.ProcessEvent)
+        wx.EVT_UPDATE_UI(frame, self.ARRANGE_WINDOWS_ID, frame.ProcessUpdateUIEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_1_ID, frame.ProcessEvent)  # wxNewId may have been nonsequential, so can't use EVT_MENU_RANGE
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_2_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_3_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_4_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_5_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_6_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_7_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_8_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_WINDOW_9_ID, frame.ProcessEvent)
+        wx.EVT_MENU(frame, self.SELECT_MORE_WINDOWS_ID, frame.ProcessEvent)
+
+        helpMenuIndex = menuBar.FindMenu(_("&Help"))
+        menuBar.Insert(helpMenuIndex, windowMenu, _("&Window"))
+
+        self._lastFrameUpdated = None
+
+
+    def ProcessEvent(self, event):
+        """
+        Processes a Window menu event.
+        """
+        id = event.GetId()
+        if id == self.ARRANGE_WINDOWS_ID:
+            self.OnArrangeWindows(event)
+            return True
+        elif id == self.SELECT_MORE_WINDOWS_ID:
+            self.OnSelectMoreWindows(event)
+            return True
+        elif id == self.SELECT_WINDOW_1_ID or id == self.SELECT_WINDOW_2_ID or id == self.SELECT_WINDOW_3_ID or id == self.SELECT_WINDOW_4_ID or id == self.SELECT_WINDOW_5_ID or id == self.SELECT_WINDOW_6_ID or id == self.SELECT_WINDOW_7_ID or id == self.SELECT_WINDOW_8_ID or id == self.SELECT_WINDOW_9_ID:
+            self.OnSelectWindowMenu(event)
+            return True
+        else:
+            return False
+
+
+    def ProcessUpdateUIEvent(self, event):
+        """
+        Updates the Window menu items.
+        """
+        id = event.GetId()
+        if id == self.ARRANGE_WINDOWS_ID:
+            frame = event.GetEventObject()
+            if not self._lastFrameUpdated or self._lastFrameUpdated != frame:
+                self.BuildWindowMenu(frame)  # It's a new frame, so update the windows menu... this is as if the View::OnActivateMethod had been invoked
+                self._lastFrameUpdated = frame
+            return True
+        else:
+            return False
+
+
+    def BuildWindowMenu(self, currentFrame):
+        """
+        Builds the Window menu and adds menu items for all of the open documents in the DocManager.
+        """
+        windowMenuIndex = currentFrame.GetMenuBar().FindMenu(_("&Window"))
+        windowMenu = currentFrame.GetMenuBar().GetMenu(windowMenuIndex)
+        ids = self._GetWindowMenuIDList()
+        frames = self._GetWindowMenuFrameList(currentFrame)
+        max = WINDOW_MENU_NUM_ITEMS
+        if max > len(frames):
+            max = len(frames)
+        i = 0
+        for i in range(0, max):
+            frame = frames[i]
+            item = windowMenu.FindItemById(ids[i])
+            label = '&' + str(i + 1) + ' ' + frame.GetTitle()
+            if not item:
+                item = windowMenu.AppendCheckItem(ids[i], label)
+            else:
+                windowMenu.SetLabel(ids[i], label)
+            windowMenu.Check(ids[i], (frame == currentFrame))
+        if len(frames) > WINDOW_MENU_NUM_ITEMS:  # Add the more items item
+            if not windowMenu.FindItemById(self.SELECT_MORE_WINDOWS_ID):
+                windowMenu.Append(self.SELECT_MORE_WINDOWS_ID, _("&More Windows..."))
+        else:  # Remove any extra items
+            if windowMenu.FindItemById(self.SELECT_MORE_WINDOWS_ID):
+                windowMenu.Remove(self.SELECT_MORE_WINDOWS_ID)
+
+
+
+            for j in range(i + 1, WINDOW_MENU_NUM_ITEMS):
+                if windowMenu.FindItemById(ids[j]):
+                    windowMenu.Remove(ids[j])
+
+
+    def _GetWindowMenuIDList(self):
+        """
+        Returns a list of the Window menu item IDs.
+        """
+        return [self.SELECT_WINDOW_1_ID, self.SELECT_WINDOW_2_ID, self.SELECT_WINDOW_3_ID, self.SELECT_WINDOW_4_ID, self.SELECT_WINDOW_5_ID, self.SELECT_WINDOW_6_ID, self.SELECT_WINDOW_7_ID, self.SELECT_WINDOW_8_ID, self.SELECT_WINDOW_9_ID]
+
+
+    def _GetWindowMenuFrameList(self, currentFrame = None):
+        """
+        Returns the Frame associated with each menu item in the Window menu.
+        """
+        frameList = []
+        # get list of windows for documents
+        for doc in self._docManager.GetDocuments():
+            for view in doc.GetViews():
+                frame = view.GetFrame()
+                if frame not in frameList:
+                    if frame == currentFrame and len(frameList) >= WINDOW_MENU_NUM_ITEMS:
+                        frameList.insert(WINDOW_MENU_NUM_ITEMS - 1, frame)
+                    else:
+                        frameList.append(frame)
+        # get list of windows for general services
+        for service in wx.GetApp().GetServices():
+            view = service.GetView()
+            if view:
+                frame = view.GetFrame()
+                if frame not in frameList:
+                    if frame == currentFrame and len(frameList) >= WINDOW_MENU_NUM_ITEMS:
+                        frameList.insert(WINDOW_MENU_NUM_ITEMS - 1, frame)
+                    else:
+                        frameList.append(frame)
+
+        return frameList
+
+
+    def OnArrangeWindows(self, event):
+        """
+        Called by Window/Arrange and tiles the frames on the desktop.
+        """
+        currentFrame = event.GetEventObject()
+
+        tempFrame = wx.Frame(None, -1, "", pos = wx.DefaultPosition, size = wx.DefaultSize)
+        sizex = tempFrame.GetSize()[0]
+        sizey = tempFrame.GetSize()[1]
+        tempFrame.Destroy()
+
+        posx = 0
+        posy = 0
+        delta = 0
+        frames = self._GetWindowMenuFrameList()
+        frames.remove(currentFrame)
+        frames.append(currentFrame) # Make the current frame the last frame so that it is the last one to appear
+        for frame in frames:
+            if delta == 0:
+                delta = frame.GetClientAreaOrigin()[1]
+            frame.SetPosition((posx, posy))
+            frame.SetSize((sizex, sizey))
+            # TODO: Need to loop around if posx + delta + size > displaysize
+            frame.SetFocus()
+            posx = posx + delta
+            posy = posy + delta
+            if posx + sizex > wx.DisplaySize()[0] or posy + sizey > wx.DisplaySize()[1]:
+                posx = 0
+                posy = 0
+        currentFrame.SetFocus()
+
+
+    def OnSelectWindowMenu(self, event):
+        """
+        Called when the Window menu item representing a Frame is selected and brings the selected
+        Frame to the front of the desktop.
+        """
+        id = event.GetId()
+        index = self._GetWindowMenuIDList().index(id)
+        if index > -1:
+            currentFrame = event.GetEventObject()
+            frame = self._GetWindowMenuFrameList(currentFrame)[index]
+            if frame:
+                wx.CallAfter(frame.Raise)
+
+
+    def OnSelectMoreWindows(self, event):
+        """
+        Called when the "Window/Select More Windows..." menu item is selected and enables user to
+        select from the Frames that do not in the Window list.  Useful when there are more than
+        10 open frames in the application.
+        """
+        frames = self._GetWindowMenuFrameList()  # TODO - make the current window the first one
+        strings = map(lambda frame: frame.GetTitle(), frames)
+        # Should preselect the current window, but not supported by wx.GetSingleChoice
+        res = wx.GetSingleChoiceIndex(_("Select a window to show:"),
+                                      _("Select Window"),
+                                      strings,
+                                      self)
+        if res == -1:
+            return
+        frames[res].SetFocus()
+
+
+#----------------------------------------------------------------------------
+# File generated by encode_bitmaps.py
+#----------------------------------------------------------------------------
+from wx import ImageFromStream, BitmapFromImage
+import cStringIO
+
+#----------------------------------------------------------------------
+def getNewData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00[IDAT8\x8d\xed\x93\xb1\n\x001\x08C\x13{\xff\xff\xc7mn\xb8El\x91\x16\
+\x97\x0e\x97M\x90\x97\x88JZCE\x8f/4\xba\xb2fZc\n\x00\x00i\xcd \t\x8d\xae\x08\
+\xb1\xad\x9c\x0e\x1eS\x1e\x01\xc8\xcf\xdcC\xa6\x112\xf7\x08:N\xb0\xd2\x0f\
+\xb8\x010\xdd\x81\xdf\xf1\x8eX\xfd\xc6\xf2\x08/D\xbd\x19(\xc8\xa5\xd9\xfa\
+\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+def getNewBitmap():
+    return BitmapFromImage(getNewImage())
+
+def getNewImage():
+    stream = cStringIO.StringIO(getNewData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getOpenData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00\x95IDAT8\x8d\xa5\x92\xc1\x12\x03!\x08C\x13\xec\x87\xfb\xe3B\x0f.]\
+\xb0\x8e[m.\xea\x0c/\x06\x06R\n\xfe\xd1\xeb\xd7B\xd5f~\x17)\xdc2Pm\x16!\x7f\
+\xab6\xe3i\x0b\x9e\xe8\x93\xc0BD\x86\xdfV0\x00\x90R`\xda\xcc\x0c\x00\x0c\x00\
+\xc1\x05>\x9a\x87\x19t\x180\x981\xbd\xfd\xe4\xc4Y\x82\xf7\x14\xca\xe7\xb7\
+\xa6\t\xee6\x1c\xba\xe18\xab\xc1 \xc3\xb5N?L\xaa5\xb5\xd0\x8dw`JaJ\xb0\x0b\
+\x03!\xc1\t\xdc\xb9k\x0f\x9e\xd1\x0b\x18\xf6\xe0x\x95]\xf2\\\xb2\xd6\x1b}\
+\x14BL\xb9{t\xc7\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+def getOpenBitmap():
+    return BitmapFromImage(getOpenImage())
+
+def getOpenImage():
+    stream = cStringIO.StringIO(getOpenData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getCopyData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00\x9fIDAT8\x8d\xa5\x93\xdb\x0e\x830\x0cC\xed\x84\xdfF\xeb\xb4\xef\xa6\
+\xde\x030z\t\x94\tK\x91z\xcb\x01\xbb*i\x8e\'\x9a\x00@yQ\xb4Is\x8e\x00\xb6\
+\x0f$Uu\x05\x0e\x01\x91$\r!\xa49\x94\x17I\x02\xc9_\xe3:Nq\x93}XL|\xeb\xe9\
+\x05\xa4p\rH\xa29h^[ Y\xd5\xb9\xb5\x17\x94gu\x19DA\x96\xe0c\xfe^\xcf\xe7Y\
+\x95\x05\x00M\xf5\x16Z;\x7f\xfdAd\xcf\xee\x1cj\xc1%|\xdan"LL\x19\xda\xe1}\
+\x90:\x00#\x95_l5\x04\xec\x89\x9f\xef?|\x8d\x97o\xe1\x8e\xbeJ\xfc\xb1\xde\
+\xea\xf8\xb9\xc4\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+def getCopyBitmap():
+    return BitmapFromImage(getCopyImage())
+
+def getCopyImage():
+    stream = cStringIO.StringIO(getCopyData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getPasteData():
+    return \
+"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00\xa1IDAT8\x8d\xa5\x93\xd9\x0e\xc3 \x0c\x04\xc7\xa6\xbf]\xc5U\xbf\xbb\
+\xd9>$4\\9\xaa\xacd\t\x0c\x1e/H6\xf3\xc4\x1d=FI\xcd\x1f\x95{\xf3d{\x003O]\
+\x01\x80\x94/\x0c\x8a\n\xa0\x01\x8a\x88\xdfaD m\x85y\xdd\xde\xc9\x10/\xc9\
+\xf9\xc0S2\xf3%\xf2\xba\x04\x94\xea\xfe`\xf4\x9c#U\x80\xbd.\x97\x015\xec&\
+\x00@\x9a\xba\x9c\xd9\x0b\x08\xe0\r4\x9fxU\xd2\x84\xe6\xa7N\x1dl\x1dkGe\xee\
+\x14\xd0>\xa3\x85\xfc\xe5`\x08]\x87I}\x84\x8e\x04!\xf3\xb48\x18\r\x8bf4\xea\
+\xde;\xbc9\xce_!\\\\T\xf75'\xd6\x00\x00\x00\x00IEND\xaeB`\x82" 
+
+def getPasteBitmap():
+    return BitmapFromImage(getPasteImage())
+
+def getPasteImage():
+    stream = cStringIO.StringIO(getPasteData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getSaveData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00lIDAT8\x8d\xc5\x93\xe1\n\xc0 \x08\x84=\xed\xc1}\xf1\xcd\xfd\x18B\x98\
+mX\x83\x1d\x04\x11\xfayV\x02,\xb4#\xde\xca&\xa2\xe6\x1b;\x0f\xab$\x82\x05\
+\x83\x03U\xbdaf\xe9\xea\x13]\xe5\x16\xa2\xd32\xc0].\x03\xa2Z<PU\x02\x90\xc5\
+\x0e\xd5S\xc0,p\xa6\xef[xs\xb0t\x89`A|\xff\x12\xe0\x11\xde\x0fS\xe5;\xbb#\
+\xfc>\x8d\x17\x18\xfd(\xb72\xc2\x06\x00\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+def getSaveBitmap():
+    return BitmapFromImage(getSaveImage())
+
+def getSaveImage():
+    stream = cStringIO.StringIO(getSaveData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getSaveAllData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x01\tIDAT8\x8d\xa5\x93\xe1m\x830\x10\x85\xdfA\xd7H\x827\xf0\x02\xado\
+\x04\x8f`Fh\xfb\xb7\xad\xcd&$Y\x80\x11\xcc\x06\x8c\xe0E\xd2\xeb\x8f\x16\x04!\
+8R\xf3\xa4\x93Nw\xd2\xf3\xa7g\x9b\xa8(\xf1\x88\x9er\xcb\xc3~\')%x\xef\xa7Y\
+\x8c\x11J)\x00\xc0\xf1t&PQn\x163\x0b\x00\x99\xcb{/\x00\xc49\'T\x94(\xfe\x83\
+\x1dB\x98\xfa\x95\xc1a\xbf\x13\xf9\xbe\xc8\xd7\xe7\x87\x18c\xe0\xbd\x073\xa3\
+\xaek\x10\x11\xfa\xbe\xcfgPU\x15RJ\x8bSB\x08h\x9af1\xdb$\xc8aw]\x87\xae\xeb\
+\xd6\x04\xd7i\x1bc\xc0\xccPJ\xa1m[03\x98\x19Z\xeb\x951QQ\xc2\xbc<K\x8c\x11"\
+\x92\xc5N)M\xbd\xd6\x1a\xafo\xef\x94}\x07#6\x00Xk\x7f\xef\xfdO\xc7\xd3\x19\
+\xc0,\x83\x10\x02\x88h\xaa1m\xad\xf5M\xf4E\x06s\x93-\xcd\xf1\xef\x1a\x8c\'^c\
+\xdf5\x18\x95C\xbei`\xad\xc50\x0cp\xce-\x96[\xd8s\xd1\xa3\xdf\xf9\x075\xf1v>\
+\x92\xcb\xbc\xdd\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+def getSaveAllBitmap():
+    return BitmapFromImage(getSaveAllImage())
+
+def getSaveAllImage():
+    stream = cStringIO.StringIO(getSaveAllData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getPrintData():
+    return \
+"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00\xa1IDAT8\x8d\xa5S[\x0e\x02!\x0c\xec\xd0\xbd\xb6\x1a\xf5\xda\x96\xd9\
+\x0f\xa1V\x96\x00\xbaMHI\xd3y\xf0(\x90T\xce\xc4\xd6+2\x1bg@$E\x97\x80\xd9H\
+\x8e\xf1\x00\xc6\x0e\xda&''\x05\x80\xab\x1f\x08\xa2\xfa\xcc\xc5\xd0\xc1H\xbd\
+\n\x89\xbc\xef\xc1\tV\xd5\x91\x14\xcc\xc6\x9a\xa5<#WV\xed\x8d\x18\x94\xc2\
+\xd1s'\xa2\xb2\xe7\xc2\xf4STAf\xe3\x16\x0bm\xdc\xae\x17'\xbf?\x9e\x0e\x8an\
+\x86G\xc8\xf6\xf9\x91I\xf5\x8b\xa0\n\xff}\x04w\x80\xa4ng\x06l/QD\x04u\x1aW\
+\x06(:\xf0\xfd\x99q\xce\xf6\xe2\x0e\xa5\xa2~.\x00=\xb5t\x00\x00\x00\x00IEND\
+\xaeB`\x82" 
+
+def getPrintBitmap():
+    return BitmapFromImage(getPrintImage())
+
+def getPrintImage():
+    stream = cStringIO.StringIO(getPrintData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getPrintPreviewData():
+    return \
+'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00\xa8IDAT8\x8d\x9d\x93K\x0e\xc30\x08Dg \xd7n\xcd\xc1\x9b\xd2E\x83E\\\
+\xffT$/\x82\xc5\x83\x19\x13\x02p,\x82\xa2\x1c\xde\x01p\xf71\x83\xe4\x14"\xab\
+\xeeQ\xec\xef\xb3\xdbe{\x82\x0c\xcb\xdf\xc7\xaa{\x86\xb7\xb0-@\xaf(\xc7\xd4\
+\x03\x9203P\x94\x14\xa5\x99\xa1\xf5b\x08\x88b+\x05~\xbejQ\x0f\xe2\xbd\x00\
+\xe0\x14\x05\xdc\x9d\xa2\xa0(\xcc\xec\x9b\xbb\xee(\xba~F\xea15a\n(\xcfG\x1d5\
+d\xe4\xdcTB\xc8\x88\xb1CB\x9b\x9b\x02\x02\x92O@\xaa\x0fXl\xe2\xcd\x0f\xf2g\
+\xad\x89\x8d\xbf\xf1\x06\xb9V9 \x0c\x1d\xff\xc6\x07\x8aF\x9e\x04\x12\xb5\xf9\
+O\x00\x00\x00\x00IEND\xaeB`\x82' 
+
+def getPrintPreviewBitmap():
+    return BitmapFromImage(getPrintPreviewImage())
+
+def getPrintPreviewImage():
+    stream = cStringIO.StringIO(getPrintPreviewData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getCutData():
+    return \
+"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00rIDAT8\x8d\xad\x93\xc1\x0e\xc0 \x08CW\xdco{\xf2\xbb';\xb18\x07\x9d\
+\x0b\xe3\xa2\x98\xe6\xb5$\x02H\xd92%\xde\xa3\xf6CY\xff\nH'\xf8\x05`\xb1Y\xfc\
+\x10\x00)`\xfdR\x82\x15w\n0W\xe6N\x01\xda\xab\x8e\xe7g\xc0\xe8\xae\xbdj\x04\
+\xda#\xe7;\xa8] \xbb\xbb\tL0\x8bX\xa5?\xd2c\x84\xb9 \r6\x96\x97\x0c\xf362\
+\xb1k\x90]\xe7\x13\x85\xca7&\xcf\xda\xcdU\x00\x00\x00\x00IEND\xaeB`\x82" 
+
+def getCutBitmap():
+    return BitmapFromImage(getCutImage())
+
+def getCutImage():
+    stream = cStringIO.StringIO(getCutData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getUndoData():
+    return \
+"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00lIDAT8\x8d\xed\x92Q\x0b\x800\x08\x84\xd5\xf5\xb7\x07W\xfdo\xed!\xaca\
+\xb2\x11{\xe9!a\xa0\xc7\xeec\x1ec\x96B3%S\xeeO\x00\x96\xd1\x05\xd3j\xed\x0c\
+\x10\xad\xdb\xce\x97\xc0R\xe8\x0c\x12\xe6\xbd\xcfQs\x1d\xb8\xf5\xd4\x90\x19#\
+\xc4\xfbG\x06\xa6\xd5X\x9a'\x0e*\r1\xee\xfd\x1a\xd0\x83\x98V\x03\x1a\xa1\xb7\
+k<@\x12\xec\xff\x95\xe7\x01\x07L\x0e(\xe5\xa4\xff\x1c\x88\x00\x00\x00\x00IEN\
+D\xaeB`\x82" 
+
+def getUndoBitmap():
+    return BitmapFromImage(getUndoImage())
+
+def getUndoImage():
+    stream = cStringIO.StringIO(getUndoData())
+    return ImageFromStream(stream)
+
+#----------------------------------------------------------------------
+def getRedoData():
+    return \
+"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
+\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
+\x00\x00jIDAT8\x8d\xed\x92\xcd\n\xc0 \x0c\x83\x9bv\xaf\xed\x16\xf0\xbd\xd7]&\
+\xf8\x8f\xe0e\x87\t9$\xb6\x1f\xb5\x08\xa8\xc9\xce\xd1\xad\xeeO\x00\x8e\xdc\\\
+gp\xb2,\x80FL\tP\x13\xa8\tI\x17\xa1'\x9f$\xd2\xe6\xb9\xef\x86=\xa5\xfb\x1a\
+\xb8\xbc\x03h\x84\xdf\xc1\xeb|\x19\xd0k.\x00\xe4\xb8h\x94\xbf\xa3\x95\xef$\
+\xe7\xbbh\xf4\x7f\xe5}\xc0\x03&\x1b&\xe5\xc2\x03!\xa6\x00\x00\x00\x00IEND\
+\xaeB`\x82" 
+
+def getRedoBitmap():
+    return BitmapFromImage(getRedoImage())
+
+def getRedoImage():
+    stream = cStringIO.StringIO(getRedoData())
+    return ImageFromStream(stream)