]> git.saurik.com Git - wxWidgets.git/blobdiff - wxPython/demo/Main.py
Overridable CreatePopupMenu in TaskBarIcon
[wxWidgets.git] / wxPython / demo / Main.py
index 642d5427f13c03f027d9ab5af3b11de726399b1f..5edc12806a9c110c62fffdf5cca1eb8ced376599 100644 (file)
@@ -47,12 +47,13 @@ import images
 _treeList = [
     # new stuff
     ('Recent Additions/Updates', [
-        'OGL',
-        'FloatCanvas',
+        'StockButtons',
+        'Ticker',
+        'Choicebook',
         ]),
 
     # managed windows == things with a (optional) caption you can close
-    ('Base Frames and Dialogs', [
+    ('Frames and Dialogs', [
         'Dialog',
         'Frame',
         'MDIWindows',
@@ -65,7 +66,6 @@ _treeList = [
         'ColourDialog',
         'DirDialog',
         'FileDialog',
-        'FileDialog_Save',
         'FindReplaceDialog',
         'FontDialog',
         'MessageDialog',
@@ -90,6 +90,7 @@ _treeList = [
         'CheckBox',
         'CheckListBox',
         'Choice',
+        'Choicebook',
         'ComboBox',
         'Gauge',
         'Grid',
@@ -113,6 +114,7 @@ _treeList = [
         'StaticBitmap',
         'StaticText',
         'StatusBar',
+        'StockButtons',
         'TextCtrl',
         'ToggleButton',
         'ToolBar',
@@ -163,6 +165,7 @@ _treeList = [
         'StyledTextCtrl_2',
         'TablePrint',
         'Throbber',
+        'Ticker',
         'TimeCtrl',
         'VListBox',
         ]),
@@ -189,7 +192,7 @@ _treeList = [
         'PythonEvents',
         'Threads',
         'Timer',
-        'infoframe',
+        ##'infoframe',    # needs better explaination and some fixing
         ]),
 
     # Clipboard and DnD
@@ -214,7 +217,7 @@ _treeList = [
     # Other stuff
     ('Miscellaneous', [
         'ColourDB',
-        'DialogUnits',
+        ##'DialogUnits',   # needs more explainations
         'DrawXXXList',
         'FileHistory',
         'FontEnumerator',
@@ -274,7 +277,7 @@ try:
 
     class DemoCodeEditor(PythonSTC):
         def __init__(self, parent):
-            PythonSTC.__init__(self, parent, -1, wx.BORDER_NONE)
+            PythonSTC.__init__(self, parent, -1, style=wx.BORDER_NONE)
             self.SetUpEditor()
 
         # Some methods to make it compatible with how the wxTextCtrl is used
@@ -297,7 +300,8 @@ try:
 
         def ShowPosition(self, pos):
             line = self.LineFromPosition(pos)
-            self.EnsureVisible(line)
+            #self.EnsureVisible(line)
+            self.GotoLine(line)
 
         def GetLastPosition(self):
             return self.GetLength()
@@ -355,9 +359,12 @@ try:
             # White space
             self.SetViewWhiteSpace(False)   # Don't view white space
     
-            # EOL
-            #self.SetEOLMode(wx.stc.STC_EOL_CRLF)  # Just leave it at the default (autosense)
-            self.SetViewEOL(False)    
+            # EOL: Since we are loading/saving ourselves, and the
+            # strings will always have \n's in them, set the STC to
+            # edit them that way.            
+            self.SetEOLMode(wx.stc.STC_EOL_LF)
+            self.SetViewEOL(False)
+            
             # No right-edge mode indicator
             self.SetEdgeMode(stc.STC_EDGE_NONE)
     
@@ -440,8 +447,8 @@ try:
 except ImportError:
     class DemoCodeEditor(wx.TextCtrl):
         def __init__(self, parent):
-            wx.TextCtrl.__init__(self, parent, -1, style = wx.TE_MULTILINE | 
-                                 wx.HSCROLL | wx.TE_RICH2 | wx.TE_NOHIDESEL)
+            wx.TextCtrl.__init__(self, parent, -1, style =
+                                 wx.TE_MULTILINE | wx.HSCROLL | wx.TE_RICH2 | wx.TE_NOHIDESEL)
 
         def RegisterModifiedEvent(self, eventHandler):
             self.Bind(wx.EVT_TEXT, eventHandler)
@@ -479,7 +486,9 @@ modDefault = modOriginal
 class DemoCodePanel(wx.Panel):
     """Panel for the 'Demo Code' tab"""
     def __init__(self, parent, mainFrame):
-        wx.Panel.__init__(self, parent)
+        wx.Panel.__init__(self, parent, size=(1,1))
+        if 'wxMSW' in wx.PlatformInfo:
+            self.Hide()
         self.mainFrame = mainFrame
         self.editor = DemoCodeEditor(self)
         self.editor.RegisterModifiedEvent(self.OnCodeModified)
@@ -506,6 +515,7 @@ class DemoCodePanel(wx.Panel):
 
         self.box = wx.BoxSizer(wx.VERTICAL)
         self.box.Add(self.controlBox, 0, wx.EXPAND)
+        self.box.Add(wx.StaticLine(self), 0, wx.EXPAND)
         self.box.Add(self.editor, 1, wx.EXPAND)
         
         self.box.Fit(self)
@@ -610,7 +620,7 @@ class DemoCodePanel(wx.Panel):
                 wx.LogMessage("Created directory for modified demos: %s" % GetModifiedDirectory())
             
         # Save
-        f = open(modifiedFilename, "w")
+        f = open(modifiedFilename, "wt")
         source = self.editor.GetText()
         try:
             f.write(source)
@@ -704,6 +714,7 @@ class DemoModules:
         
         # load original module
         self.LoadFromFile(modOriginal, GetOriginalFilename(name))
+        self.SetActive(modOriginal)
 
         # load modified module (if one exists)
         if DoesModifiedExist(name):
@@ -712,7 +723,7 @@ class DemoModules:
 
     def LoadFromFile(self, modID, filename):
         self.modules[modID][2] = filename
-        file = open(filename, "r")
+        file = open(filename, "rt")
         self.LoadFromSource(modID, file.read())
         file.close()
 
@@ -789,7 +800,7 @@ class DemoModules:
         filename = self.modules[modID][2]
 
         try:        
-            file = open(filename, "w")
+            file = open(filename, "wt")
             file.write(source)
         finally:
             file.close()
@@ -804,35 +815,6 @@ class DemoModules:
         self.modules[modID][2] = ""
 
 
-#---------------------------------------------------------------------------
-class ReloadDemoPanel(wx.Panel):
-    """
-    Panel put into the demo tab when the demo just shows some
-    top-level window.  Enables the demo to be reloaded after being
-    closed.
-    """
-
-    infoText = "This demo runs outside the main window"
-    
-    def __init__(self, parent, codePanel, log):
-        wx.Panel.__init__(self, parent, -1)
-        self.codePanel = codePanel
-        self.log = log
-
-        self.label = wx.StaticText(self, -1, self.infoText)
-        self.btnReload = wx.Button(self, -1, "Reload Demo")
-        self.btnReload.Bind(wx.EVT_BUTTON, self.OnReload)
-
-        self.box = wx.BoxSizer(wx.VERTICAL)
-        self.box.Add(self.label, 0, wx.ALIGN_CENTER | wx.ALL, 10)
-        self.box.Add(self.btnReload, 0, wx.ALIGN_CENTER | wx.ALL, 10)
-
-        self.box.Fit(self)
-        self.SetSizer(self.box)
-        
-    def OnReload(self, event):
-        self.codePanel.ReloadDemo()
-
 #---------------------------------------------------------------------------
 
 class DemoError:
@@ -967,11 +949,89 @@ class DemoErrorPanel(wx.Panel):
 
 #---------------------------------------------------------------------------
 
+class DemoTaskBarIcon(wx.TaskBarIcon):
+    TBMENU_RESTORE = wx.NewId()
+    TBMENU_CLOSE   = wx.NewId()
+    TBMENU_CHANGE  = wx.NewId()
+    TBMENU_REMOVE  = wx.NewId()
+    
+    def __init__(self, frame):
+        wx.TaskBarIcon.__init__(self)
+        self.frame = frame
+
+        # Set the image
+        icon = self.MakeIcon(images.getMondrianImage())
+        self.SetIcon(icon, "wxPython Demo")
+        
+        # bind some events
+        self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate)
+        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE)
+        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE)
+        self.Bind(wx.EVT_MENU, self.OnTaskBarChange, id=self.TBMENU_CHANGE)
+        self.Bind(wx.EVT_MENU, self.OnTaskBarRemove, id=self.TBMENU_REMOVE)
+
+
+    def CreatePopupMenu(self):
+        """
+        This method is called by the base class when it needs to popup
+        the menu for the default EVT_RIGHT_DOWN event.  Just create
+        the menu how you want it and return it from this function,
+        the base class takes care of the rest.
+        """
+        menu = wx.Menu()
+        menu.Append(self.TBMENU_RESTORE, "Restore wxPython Demo")
+        menu.Append(self.TBMENU_CLOSE,   "Close wxPython Demo")
+        menu.AppendSeparator()
+        menu.Append(self.TBMENU_CHANGE, "Change the TB Icon")
+        menu.Append(self.TBMENU_REMOVE, "Remove the TB Icon")
+        return menu
+
+
+    def MakeIcon(self, img):
+        """
+        The various platforms have different requirements for the
+        icon size...
+        """
+        if "wxMSW" in wx.PlatformInfo:
+            img.Scale(16, 16)
+        elif "wxGTK" in wx.PlatformInfo:
+            img.Scale(22, 22)
+        # wxMac can be any size upto 128.128....
+        icon = wx.IconFromBitmap(img.ConvertToBitmap() )
+        return icon
+    
+
+    def OnTaskBarActivate(self, evt):
+        if self.frame.IsIconized():
+            self.frame.Iconize(False)
+        if not self.frame.IsShown():
+            self.frame.Show(True)
+        self.frame.Raise()
+
+
+    def OnTaskBarClose(self, evt):
+        self.frame.Close()
+
+        # because of the way wx.TaskBarIcon.PopupMenu is implemented we have to
+        # prod the main idle handler a bit to get the window to actually close
+        wx.GetApp().ProcessIdle()
+    
+
+    def OnTaskBarChange(self, evt):
+        icon = self.MakeIcon(images.getRobinImage())
+        self.SetIcon(icon, "This is a new icon")
+
+
+    def OnTaskBarRemove(self, evt):
+        self.RemoveIcon()
+
+
+#---------------------------------------------------------------------------
 class wxPythonDemo(wx.Frame):
     overviewText = "wxPython Overview"
 
     def __init__(self, parent, title):
-        wx.Frame.__init__(self, parent, -1, title, size = (950, 750),
+        wx.Frame.__init__(self, parent, -1, title, size = (950, 720),
                           style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE)
 
         self.loaded = False
@@ -979,24 +1039,13 @@ class wxPythonDemo(wx.Frame):
         self.curOverview = ""
         self.demoPage = None
         self.codePage = None
-        self.useModified = False
+        self.shell = None
+        self.firstTime = True
 
         icon = images.getMondrianIcon()
         self.SetIcon(icon)
 
-        if wx.Platform != '__WXMAC__':
-            # setup a taskbar icon, and catch some events from it
-            dim = 16  # (may want to use 22 on wxGTK, but 16 looks okay too)
-            icon = wx.IconFromBitmap(
-                images.getMondrianImage().Scale(dim,dim).ConvertToBitmap() )
-            #icon = wx.Icon('bmp_source/mondrian.ico', wx.BITMAP_TYPE_ICO)
-            #icon = images.getMondrianIcon()
-            self.tbicon = wx.TaskBarIcon()
-            self.tbicon.SetIcon(icon, "wxPython Demo")
-            self.tbicon.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate)
-            self.tbicon.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnTaskBarMenu)
-            self.tbicon.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE)
-            self.tbicon.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE)
+        self.tbicon = DemoTaskBarIcon(self)
 
         wx.CallAfter(self.ShowTip)
 
@@ -1063,15 +1112,18 @@ class wxPythonDemo(wx.Frame):
        # 
 
         # Make a Help menu
-        helpID = wx.NewId()
-        findID = wx.NewId()
-        findnextID = wx.NewId()
         menu = wx.Menu()
         findItem = menu.Append(-1, '&Find\tCtrl-F', 'Find in the Demo Code')
         findnextItem = menu.Append(-1, 'Find &Next\tF3', 'Find Next')
         menu.AppendSeparator()
+
+        shellItem = menu.Append(-1, 'Open Py&Shell Window\tF5',
+                                'An interactive interpreter window with the demo app and frame objects in the namesapce')
+        menu.AppendSeparator()
         helpItem = menu.Append(-1, '&About\tCtrl-H', 'wxPython RULES!!!')
         wx.App_SetMacAboutMenuItemId(helpItem.GetId())
+
+        self.Bind(wx.EVT_MENU, self.OnOpenShellWindow, shellItem)
         self.Bind(wx.EVT_MENU, self.OnHelpAbout, helpItem)
         self.Bind(wx.EVT_MENU, self.OnHelpFind,  findItem)
         self.Bind(wx.EVT_MENU, self.OnFindNext,  findnextItem)
@@ -1136,7 +1188,7 @@ class wxPythonDemo(wx.Frame):
             panel.Bind(wx.EVT_ERASE_BACKGROUND, EmptyHandler)
 
         if "gtk2" in wx.PlatformInfo:
-            self.ovr.NormalizeFontSizes()
+            self.ovr.SetStandardFonts()
         self.SetOverview(self.overviewText, mainOverview)
 
 
@@ -1282,20 +1334,28 @@ class wxPythonDemo(wx.Frame):
             if hasattr(module, "overview"):
                 overviewText = module.overview
 
-            # in case runTest is modal, make sure things look right...
-            wx.YieldIfNeeded()
-
             try:
                 self.demoPage = module.runTest(self, self.nb, self)
-                if self.demoPage is None:
-                    self.demoPage = ReloadDemoPanel(self.nb, self.codePage, self)
             except:
-                self.demoPage = DemoErrorPanel(self.nb, self.codePage, DemoError(sys.exc_info()), self)
+                self.demoPage = DemoErrorPanel(self.nb, self.codePage,
+                                               DemoError(sys.exc_info()), self)
+
+            assert self.demoPage is not None, "runTest must return a window!"
+            
         else:
             # There was a previous error in compiling or exec-ing
-            self.demoPage = DemoErrorPanel(self.nb, self.codePage, self.demoModules.GetErrorInfo(), self)
+            self.demoPage = DemoErrorPanel(self.nb, self.codePage,
+                                           self.demoModules.GetErrorInfo(), self)
+            
         self.SetOverview(self.demoModules.name + " Overview", overviewText)
-        self.UpdateNotebook()
+
+        if self.firstTime:
+            # cahnge to the demo page the first time a module is run
+            self.UpdateNotebook(2)
+            self.firstTime = False
+        else:
+            # otherwise just stay on the same tab in case the user has changed to another one
+            self.UpdateNotebook()
 
     #---------------------------------------------
     def ShutdownDemoModule(self):
@@ -1323,23 +1383,12 @@ class wxPythonDemo(wx.Frame):
             if page:
                 if not pageExists:
                     # Add a new page
- #                   panel = wx.Panel(nb, -1)
- #                   page.Reparent(panel)
- #                   panel.page = page
- #                   nb.AddPage(panel, pageText)
                     nb.AddPage(page, pageText)
                     if debug: wx.LogMessage("DBG: ADDED %s" % pageText)
                 else:
- #                   if nb.GetPage(pagePos).page != page:
                     if nb.GetPage(pagePos) != page:
                         # Reload an existing page
                         nb.Freeze()
- #                       panel = nb.GetPage(pagePos)
- #                       panel.page = page
- #                       page.Reparent(panel)
-                        
                         nb.DeletePage(pagePos)
                         nb.InsertPage(pagePos, page, pageText)
                         nb.Thaw()
@@ -1360,7 +1409,7 @@ class wxPythonDemo(wx.Frame):
         UpdatePage(self.codePage, "Demo Code")
         UpdatePage(self.demoPage, "Demo")
 
-        if select >= 0:
+        if select >= 0 and select < nb.GetPageCount():
             nb.SetSelection(select)
             
     #---------------------------------------------
@@ -1441,12 +1490,40 @@ class wxPythonDemo(wx.Frame):
         event.GetDialog().Destroy()
 
 
+    def OnOpenShellWindow(self, evt):
+        if self.shell:
+            # if it already exists then just make sure it's visible
+            s = self.shell
+            if s.IsIconized():
+                s.Iconize(False)
+            s.Raise()
+        else:
+            # Make a PyShell window
+            from wx import py
+            namespace = { 'wx'    : wx,
+                          'app'   : wx.GetApp(),
+                          'frame' : self,
+                          }
+            self.shell = py.shell.ShellFrame(None, locals=namespace)
+            self.shell.SetSize((640,480))
+            self.shell.Show()
+
+            # Hook the close event of the main frame window so that we
+            # close the shell at the same time if it still exists            
+            def CloseShell(evt):
+                if self.shell:
+                    self.shell.Close()
+                evt.Skip()
+            self.Bind(wx.EVT_CLOSE, CloseShell)
+
+        
     #---------------------------------------------
     def OnCloseWindow(self, event):
         self.dying = True
         self.demoPage = None
         self.codePage = None
         self.mainmenu = None
+        self.tbicon.Destroy()
         self.Destroy()
 
 
@@ -1484,34 +1561,6 @@ class wxPythonDemo(wx.Frame):
             self.tree.EnsureVisible(selectedDemo)
 
 
-    #---------------------------------------------
-    def OnTaskBarActivate(self, evt):
-        if self.IsIconized():
-            self.Iconize(False)
-        if not self.IsShown():
-            self.Show(True)
-        self.Raise()
-
-    #---------------------------------------------
-
-    TBMENU_RESTORE = 1000
-    TBMENU_CLOSE   = 1001
-
-    def OnTaskBarMenu(self, evt):
-        menu = wx.Menu()
-        menu.Append(self.TBMENU_RESTORE, "Restore wxPython Demo")
-        menu.Append(self.TBMENU_CLOSE,   "Close")
-        self.tbicon.PopupMenu(menu)
-        menu.Destroy()
-
-    #---------------------------------------------
-    def OnTaskBarClose(self, evt):
-        self.Close()
-
-        # because of the way wx.TaskBarIcon.PopupMenu is implemented we have to
-        # prod the main idle handler a bit to get the window to actually close
-        wx.GetApp().ProcessIdle()
-
 
     #---------------------------------------------
     def OnIconfiy(self, evt):
@@ -1575,7 +1624,7 @@ def main():
         os.chdir(demoPath)
     except:
         pass
-    app = MyApp(0) ##wx.Platform == "__WXMAC__")
+    app = MyApp(False)
     app.MainLoop()
 
 #---------------------------------------------------------------------------