source: sasview/guiframe/gui_manager.py @ 9455d77

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 9455d77 was c1469ebe, checked in by Gervaise Alina <gervyh@…>, 15 years ago

add welcome page on the help menu

  • Property mode set to 100644
File size: 32.7 KB
Line 
1"""
2This software was developed by the University of Tennessee as part of the
3Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4project funded by the US National Science Foundation.
5
6See the license text in license.txt
7
8copyright 2008, University of Tennessee
9
10How-to build an application using guiframe:
11
12 1- Write a main application script along the lines of dummyapp.py
13 2- Write a config script along the lines of config.py, and name it local_config.py
14 3- Write your plug-ins and place them in a directory called "perspectives".
15     - Look at local_perspectives/plotting for an example of a plug-in.
16     - A plug-in should define a class called Plugin. See abstract class below.
17
18"""
19#TODO: rewrite the status bar monstrosity
20
21import wx
22import wx.aui
23import os, sys
24import xml
25try:
26    # Try to find a local config
27    import imp
28    path = os.getcwd()
29    if(os.path.isfile("%s/%s.py" % (path, 'local_config'))) or \
30      (os.path.isfile("%s/%s.pyc" % (path, 'local_config'))):
31            fObj, path, descr = imp.find_module('local_config', [path])
32            config = imp.load_module('local_config', fObj, path, descr) 
33    else:
34        # Try simply importing local_config
35        import local_config as config
36except:
37    # Didn't find local config, load the default
38    import config
39   
40from sans.guicomm.events import EVT_STATUS
41from sans.guicomm.events import EVT_NEW_PLOT,EVT_SLICER_PARS_UPDATE
42
43import warnings
44warnings.simplefilter("ignore")
45
46import logging
47
48class Plugin:
49    """
50        This class defines the interface for a Plugin class
51        that can be used by the gui_manager.
52       
53        Plug-ins should be placed in a sub-directory called "perspectives".
54        For example, a plug-in called Foo should be place in "perspectives/Foo".
55        That directory contains at least two files:
56            perspectives/Foo/__init.py contains two lines:
57           
58                PLUGIN_ID = "Foo plug-in 1.0"
59                from Foo import *
60               
61            perspectives/Foo/Foo.py contains the definition of the Plugin
62            class for the Foo plug-in. The interface of that Plugin class
63            should follow the interface of the class you are looking at.
64           
65        See dummyapp.py for a plugin example.
66    """
67   
68    def __init__(self, name="Test_plugin"):
69        """
70            Abstract class for gui_manager Plugins.
71        """
72        ## Plug-in name. It will appear on the application menu.
73        self.sub_menu = name     
74       
75        ## Reference to the parent window. Filled by get_panels() below.
76        self.parent = None
77       
78        ## List of panels that you would like to open in AUI windows
79        #  for your plug-in. This defines your plug-in "perspective"
80        self.perspective = []
81       
82       
83    def populate_menu(self, id, parent):
84        """
85            Create and return the list of application menu
86            items for the plug-in.
87           
88            @param id: deprecated. Un-used.
89            @param parent: parent window
90            @return: plug-in menu
91        """
92        return []
93   
94    def get_panels(self, parent):
95        """
96            Create and return the list of wx.Panels for your plug-in.
97            Define the plug-in perspective.
98           
99            Panels should inherit from DefaultPanel defined below,
100            or should present the same interface. They must define
101            "window_caption" and "window_name".
102           
103            @param parent: parent window
104            @return: list of panels
105        """
106        ## Save a reference to the parent
107        self.parent = parent
108       
109        # Return the list of panels
110        return []
111   
112    def get_tools(self):
113        """
114            Returns a set of menu entries for tools
115        """
116        return []
117       
118   
119    def get_context_menu(self, graph=None):
120        """
121            This method is optional.
122       
123            When the context menu of a plot is rendered, the
124            get_context_menu method will be called to give you a
125            chance to add a menu item to the context menu.
126           
127            A ref to a Graph object is passed so that you can
128            investigate the plot content and decide whether you
129            need to add items to the context menu. 
130           
131            This method returns a list of menu items.
132            Each item is itself a list defining the text to
133            appear in the menu, a tool-tip help text, and a
134            call-back method.
135           
136            @param graph: the Graph object to which we attach the context menu
137            @return: a list of menu items with call-back function
138        """
139        return []
140   
141    def get_perspective(self):
142        """
143            Get the list of panel names for this perspective
144        """
145        return self.perspective
146   
147    def on_perspective(self, event):
148        """
149            Call back function for the perspective menu item.
150            We notify the parent window that the perspective
151            has changed.
152            @param event: menu event
153        """
154        self.parent.set_perspective(self.perspective)
155   
156    def post_init(self):
157        """
158            Post initialization call back to close the loose ends
159        """
160        pass
161
162
163class ViewerFrame(wx.Frame):
164    """
165        Main application frame
166    """
167    def __init__(self, parent, id, title, window_height=300, window_width=300):
168        """
169            Initialize the Frame object
170        """
171        from local_perspectives.plotting import plotting
172        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size=(window_width, window_height))
173        # Preferred window size
174        self._window_height = window_height
175        self._window_width  = window_width
176       
177        # Logging info
178        logging.basicConfig(level=logging.DEBUG,
179                    format='%(asctime)s %(levelname)s %(message)s',
180                    filename='sans_app.log',
181                    filemode='w')       
182        path = os.path.dirname(__file__)
183        temp_path= os.path.join(path,'images')
184        ico_file = os.path.join(temp_path,'ball.ico')
185        if os.path.isfile(ico_file):
186            self.SetIcon(wx.Icon(ico_file, wx.BITMAP_TYPE_ICO))
187        else:
188            temp_path= os.path.join(os.getcwd(),'images')
189            ico_file = os.path.join(temp_path,'ball.ico')
190            if os.path.isfile(ico_file):
191                self.SetIcon(wx.Icon(ico_file, wx.BITMAP_TYPE_ICO))
192       
193        ## Application manager
194        self.app_manager = None
195       
196        ## Find plug-ins
197        # Modify this so that we can specify the directory to look into
198        self.plugins =[]
199        self.plugins.append(plotting.Plugin())
200        self.plugins += self._find_plugins()
201     
202        ## List of panels
203        self.panels = {}
204
205        ## Next available ID for wx gui events
206        #TODO:  No longer used - remove all calls to this
207        self.next_id = 20000
208
209        # Default locations
210        self._default_save_location = os.getcwd()       
211
212        # Welcome panel
213        self.defaultPanel = None
214
215        # Check for update
216        self._check_update(None)
217        ## maximum number of opened files' paths to store
218        self.n_maxfileopen =  2
219        ## number of file open
220        self.n_fileOpen=0
221        ## list of path of open files
222        self.filePathList=[]
223        ## list of open file with name form menu
224        #self._saveOpenData()
225        ## Dictionary of open file where keys are filename  and values are number of copy of data plotted
226        ## using the same loaded file
227        self.indice_load_data={}
228        # Register the close event so it calls our own method
229        wx.EVT_CLOSE(self, self._onClose)
230        # Register to status events
231        self.Bind(EVT_STATUS, self._on_status_event)
232   
233       
234    def build_gui(self):
235        # Set up the layout
236        self._setup_layout()
237       
238        # Set up the menu
239        self._setup_menus()
240       
241        #self.Fit()
242       
243        self._check_update(None)
244             
245    def _setup_layout(self):
246        """
247            Set up the layout
248        """
249        # Status bar
250        from statusbar import MyStatusBar
251        self.sb = MyStatusBar(self,wx.ID_ANY)
252        self.SetStatusBar(self.sb)
253
254        # Add panel
255        self._mgr = wx.aui.AuiManager(self)
256        self._mgr.SetDockSizeConstraint(0.5, 0.5) 
257       
258        # Load panels
259        self._load_panels()
260       
261        self._mgr.Update()
262
263    def add_perspective(self, plugin):
264        """
265            Add a perspective if it doesn't already
266            exist.
267        """
268        is_loaded = False
269        for item in self.plugins:
270             if plugin.__class__==item.__class__:
271                 print "Plugin %s already loaded" % plugin.__class__.__name__
272                 is_loaded = True
273                 
274        if not is_loaded:
275            self.plugins.append(plugin)
276     
277    def _find_plugins(self, dir="perspectives"):
278        """
279            Find available perspective plug-ins
280            @param dir: directory in which to look for plug-ins
281            @return: list of plug-ins
282        """
283        import imp
284       
285        plugins = []
286        # Go through files in panels directory
287        try:
288            list = os.listdir(dir)
289            ## the default panel is the panel is the last plugin added
290            for item in list:
291                toks = os.path.splitext(os.path.basename(item))
292                name = None
293                if not toks[0] == '__init__':
294                   
295                    if toks[1]=='.py' or toks[1]=='':
296                        name = toks[0]
297               
298                    path = [os.path.abspath(dir)]
299                    file = None
300                    try:
301                        if toks[1]=='':
302                            mod_path = '.'.join([dir, name])
303                            module = __import__(mod_path, globals(), locals(), [name])
304                        else:
305                            (file, path, info) = imp.find_module(name, path)
306                            module = imp.load_module( name, file, item, info )
307                        if hasattr(module, "PLUGIN_ID"):
308                            try:
309                                plugins.append(module.Plugin())
310                                logging.info("Found plug-in: %s" % module.PLUGIN_ID)
311                            except:
312                                config.printEVT("Error accessing PluginPanel in %s\n  %s" % (name, sys.exc_value))
313                       
314                    except:
315                        print sys.exc_value
316                        logging.error("ViewerFrame._find_plugins: %s" % sys.exc_value)
317                    finally:
318                        if not file==None:
319                            file.close()
320        except:
321            # Should raise and catch at a higher level and display error on status bar
322            pass   
323        return plugins
324   
325    def set_welcome_panel(self, panel_class):
326        """
327           Sets the default panel as the given welcome panel
328           @param panel_class: class of the welcome panel to be instantiated
329        """
330        self.defaultPanel    = panel_class(self, -1, style=wx.RAISED_BORDER)
331        self.defaultPanel.set_manager(manager=self.app_manager)
332     
333    def _load_panels(self):
334        """
335            Load all panels in the panels directory
336        """
337       
338        # Look for plug-in panels
339        panels = []   
340        for item in self.plugins:
341            if hasattr(item, "get_panels"):
342                ps = item.get_panels(self)
343                panels.extend(ps)
344
345        # Show a default panel with some help information
346        # It also sets the size of the application windows
347        #TODO: Use this for slpash screen
348        if self.defaultPanel is None:
349            self.defaultPanel    = DefaultPanel(self, -1, style=wx.RAISED_BORDER)
350           
351        self.panels["default"] = self.defaultPanel
352       
353        self._mgr.AddPane(self.defaultPanel, wx.aui.AuiPaneInfo().
354                              Name("default").
355                              CenterPane().
356                              # This is where we set the size of the application window
357                              BestSize(wx.Size(self._window_width, self._window_height)).
358                              #MinSize(wx.Size(self._window_width, self._window_height)).
359                              Show())
360     
361
362        # Add the panels to the AUI manager
363        for panel_class in panels:
364            p = panel_class
365            id = wx.NewId()
366           
367            # Check whether we need to put this panel
368            # in the center pane
369            if hasattr(p, "CENTER_PANE"):
370                if p.CENTER_PANE:
371                    self.panels[str(id)] = p
372                    self._mgr.AddPane(p, wx.aui.AuiPaneInfo().
373                                          Name(p.window_name).Caption(p.window_caption).
374                                          CenterPane().
375                                          #BestSize(wx.Size(550,600)).
376                                          #MinSize(wx.Size(500,500)).
377                                          Hide())
378            else:
379                self.panels[str(id)] = p
380                self._mgr.AddPane(p, wx.aui.AuiPaneInfo().
381                                  Name(p.window_name).Caption(p.window_caption).
382                                  Right().
383                                  Dock().
384                                  TopDockable().
385                                  BottomDockable().
386                                  LeftDockable().
387                                  RightDockable().
388                                  MinimizeButton().
389                                  Hide())
390                                  #BestSize(wx.Size(550,600)))
391                                  #MinSize(wx.Size(500,500)))                 
392               
393       
394    def get_context_menu(self, graph=None):
395        """
396            Get the context menu items made available
397            by the different plug-ins.
398            This function is used by the plotting module
399        """
400        menu_list = []
401        for item in self.plugins:
402            if hasattr(item, "get_context_menu"):
403                menu_list.extend(item.get_context_menu(graph))
404           
405        return menu_list
406       
407    def popup_panel(self, p):
408        """
409            Add a panel object to the AUI manager
410            @param p: panel object to add to the AUI manager
411            @return: ID of the event associated with the new panel [int]
412        """
413       
414        ID = wx.NewId()
415        self.panels[str(ID)] = p
416       
417        count = 0
418        for item in self.panels:
419            if self.panels[item].window_name.startswith(p.window_name): 
420                count += 1
421       
422        windowname = p.window_name
423        caption = p.window_caption
424       
425        if count>0:
426            windowname += str(count+1)
427            caption += (' '+str(count))
428         
429        p.window_name = windowname
430        p.window_caption = caption
431           
432        self._mgr.AddPane(p, wx.aui.AuiPaneInfo().
433                          Name(windowname).Caption(caption).
434                          Floatable().
435                          #Float().
436                          Right().
437                          Dock().
438                          TopDockable().
439                          BottomDockable().
440                          LeftDockable().
441                          RightDockable().
442                          MinimizeButton().
443                          #Hide().
444                          #Show().
445                          Resizable(True).
446                          # Use a large best size to make sure the AUI manager
447                          # takes all the available space
448                          BestSize(wx.Size(400,400)))
449        pane = self._mgr.GetPane(windowname)
450        self._mgr.MaximizePane(pane)
451        self._mgr.RestoreMaximizedPane()
452       
453       
454        # Register for showing/hiding the panel
455       
456        wx.EVT_MENU(self, ID, self._on_view)
457       
458        self._mgr.Update()
459        return ID
460       
461    def _setup_menus(self):
462        """
463            Set up the application menus
464        """
465        # Menu
466        menubar = wx.MenuBar()
467       
468        # File menu
469        self.filemenu = wx.Menu()
470       
471        id = wx.NewId()
472        self.filemenu.Append(id, '&Open', 'Open a file')
473        wx.EVT_MENU(self, id, self._on_open)
474        #self.filemenu.AppendSeparator()
475       
476        id = wx.NewId()
477        self.filemenu.Append(id,'&Quit', 'Exit') 
478        wx.EVT_MENU(self, id, self.Close)
479       
480        # Add sub menus
481        menubar.Append(self.filemenu,  '&File')
482       
483        # Plot menu
484        # Attach a menu item for each panel in our
485        # panel list that also appears in a plug-in.
486        # TODO: clean this up. We should just identify
487        # plug-in panels and add them all.
488       
489        # Only add the panel menu if there is more than two panels
490        n_panels = 0
491        for plug in self.plugins:
492            pers = plug.get_perspective()
493            if len(pers)>0:
494                n_panels += 1
495       
496        if n_panels>2:
497            viewmenu = wx.Menu()
498            for plug in self.plugins:
499                plugmenu = wx.Menu()
500                pers = plug.get_perspective()
501                if len(pers)>0:
502                    for item in self.panels:
503                        if item == 'default':
504                            continue
505                        panel = self.panels[item]
506                        if panel.window_name in pers:
507                            plugmenu.Append(int(item), panel.window_caption, "Show %s window" % panel.window_caption)
508                           
509                            wx.EVT_MENU(self, int(item), self._on_view)
510                   
511                    viewmenu.AppendMenu(wx.NewId(), plug.sub_menu, plugmenu, plug.sub_menu)
512            menubar.Append(viewmenu, '&Panel')
513
514        # Perspective
515        # Attach a menu item for each defined perspective.
516        # Only add the perspective menu if there are more than one perspectives
517        n_perspectives = 0
518        for plug in self.plugins:
519            if len(plug.get_perspective()) > 0:
520                n_perspectives += 1
521       
522        if n_perspectives>1:
523            p_menu = wx.Menu()
524            for plug in self.plugins:
525                if len(plug.get_perspective()) > 0:
526                    id = wx.NewId()
527                    p_menu.Append(id, plug.sub_menu, "Switch to %s perspective" % plug.sub_menu)
528                    wx.EVT_MENU(self, id, plug.on_perspective)
529            menubar.Append(p_menu,   '&Perspective')
530 
531        # Tools menu
532        # Go through plug-ins and find tools to populate the tools menu
533        toolsmenu = None
534        for item in self.plugins:
535            if hasattr(item, "get_tools"):
536                for tool in item.get_tools():
537                    # Only create a menu if we have at least one tool
538                    if toolsmenu is None:
539                        toolsmenu = wx.Menu()
540                    id = wx.NewId()
541                   
542                    toolsmenu.Append(id, tool[0], tool[1])
543                    wx.EVT_MENU(self, id, tool[2])
544        if toolsmenu is not None:
545            menubar.Append(toolsmenu, '&Tools')
546 
547        # Help menu
548        helpmenu = wx.Menu()
549        # add the welcome panel menu item
550        id = wx.NewId()
551        helpmenu.Append(id,'&Welcome', '')
552        helpmenu.AppendSeparator()
553        wx.EVT_MENU(self, id, self.show_welcome_panel)
554       
555        # Look for help item in plug-ins
556        for item in self.plugins:
557            if hasattr(item, "help"):
558                id = wx.NewId()
559                helpmenu.Append(id,'&%s help' % item.sub_menu, '')
560                wx.EVT_MENU(self, id, item.help)
561       
562        if config._do_aboutbox:
563            id = wx.NewId()
564            helpmenu.Append(id,'&About', 'Software information')
565            wx.EVT_MENU(self, id, self._onAbout)
566        id = wx.NewId()
567        helpmenu.Append(id,'&Check for update', 'Check for the latest version of %s' % config.__appname__)
568        wx.EVT_MENU(self, id, self._check_update)
569       
570       
571       
572       
573        # Look for plug-in menus
574        # Add available plug-in sub-menus.
575        for item in self.plugins:
576            if hasattr(item, "populate_menu"):
577                for (self.next_id, menu, name) in item.populate_menu(self.next_id, self):
578                    menubar.Append(menu, name)
579                   
580
581        menubar.Append(helpmenu, '&Help')
582         
583        self.SetMenuBar(menubar)
584       
585       
586       
587    def _on_status_event(self, evt):
588        """
589            Display status message
590        """
591        #self.sb.clear_gauge( msg="")
592        mythread=None
593        mytype= None
594        if hasattr(evt, "curr_thread"):
595            mythread= evt.curr_thread
596        if hasattr(evt, "type"):
597            mytype= evt.type
598        self.sb.set_status( type=mytype,msg=str(evt.status),thread=mythread)
599       
600
601       
602    def _on_view(self, evt):
603        """
604            A panel was selected to be shown. If it's not already
605            shown, display it.
606            @param evt: menu event
607        """
608        self.show_panel(evt.GetId())
609       
610    def on_close_welcome_panel(self ):
611        """
612            Close the welcome panel
613        """
614        self._mgr.GetPane(self.panels["default"].window_name).Hide()
615        self._mgr.Update()
616       
617       
618    def show_welcome_panel(self, event):
619        """   
620            Display the welcome panel
621        """
622        for id in self.panels.keys():
623            if self._mgr.GetPane(self.panels[id].window_name).IsShown():
624                self._mgr.GetPane(self.panels[id].window_name).Hide()
625        # Show default panel
626        if not self._mgr.GetPane(self.panels["default"].window_name).IsShown():
627            self._mgr.GetPane(self.panels["default"].window_name).Show()
628       
629        self._mgr.Update()
630       
631    def show_panel(self, uid):
632        """
633            Shows the panel with the given id
634            @param uid: unique ID number of the panel to show
635        """
636        ID = str(uid)
637        config.printEVT("show_panel: %s" % ID)
638        if ID in self.panels.keys():
639            if not self._mgr.GetPane(self.panels[ID].window_name).IsShown():
640                self._mgr.GetPane(self.panels[ID].window_name).Show()
641                # Hide default panel
642                self._mgr.GetPane(self.panels["default"].window_name).Hide()
643           
644               
645            self._mgr.Update()
646   
647    def _on_open(self, event):
648   
649        from data_loader import plot_data
650        path = self.choose_file()
651
652        if path ==None:
653            return
654        if path and os.path.isfile(path):
655            plot_data(self, path)
656           
657       
658       
659    def _onClose(self, event):
660        """
661            Store info to retrieve in xml before closing the application
662        """
663        try:
664            doc = xml.dom.minidom.Document()
665            main_node = doc.createElement("file Path")
666           
667            doc.appendChild(main_node)
668       
669            for item in self.filePathList:
670                id, menuitem_name , path, title = item
671                pt1 = doc.createElement("File")
672                pt1.setAttribute("name", menuitem_name)
673                pt2 = doc.createElement("path")
674                pt2.appendChild(doc.createTextNode(str(path)))
675                pt1.appendChild(pt2)
676                pt3 = doc.createElement("title")
677                pt3.appendChild(doc.createTextNode(str(title)))
678                pt1.appendChild(pt3)
679               
680                main_node.appendChild(pt1)
681               
682               
683            fd = open("fileOpened.xml",'w')
684            fd.write(doc.toprettyxml())
685            fd.close()
686        except:
687            pass
688       
689        import sys
690        wx.Exit()
691        sys.exit()
692                   
693                   
694    def Close(self, event=None):
695        """
696            Quit the application
697        """
698        import sys
699        wx.Frame.Close(self)
700        wx.Exit()
701        sys.exit()
702
703 
704    def _check_update(self, event=None): 
705        """
706            Check with the deployment server whether a new version
707            of the application is available.
708            A thread is started for the connecting with the server. The thread calls
709            a call-back method when the current version number has been obtained.
710        """
711        if hasattr(config, "__update_URL__"):
712            import version
713            checker = version.VersionThread(config.__update_URL__, self._process_version, baggage=event==None)
714            checker.start() 
715   
716    def _process_version(self, version, standalone=True):
717        """
718            Call-back method for the process of checking for updates.
719            This methods is called by a VersionThread object once the current
720            version number has been obtained. If the check is being done in the
721            background, the user will not be notified unless there's an update.
722           
723            @param version: version string
724            @param standalone: True of the update is being checked in the background, False otherwise.
725        """
726        try:
727            if cmp(version, config.__version__)>0:
728                self.SetStatusText("Version %s is available! See the Help menu to download it." % version)
729                if not standalone:
730                    import webbrowser
731                    webbrowser.open(config.__download_page__)
732            else:
733                if not standalone:
734                    self.SetStatusText("You have the latest version of %s" % config.__appname__)
735        except:
736            logging.error("guiframe: could not get latest application version number\n  %s" % sys.exc_value)
737            if not standalone:
738                self.SetStatusText("Could not connect to the application server. Please try again later.")
739                   
740       
741    def _onAbout(self, evt):
742        """
743            Pop up the about dialog
744            @param evt: menu event
745        """
746        if config._do_aboutbox:
747            import aboutbox 
748            dialog = aboutbox.DialogAbout(None, -1, "")
749            dialog.ShowModal()           
750           
751    def _onreloaFile(self, event): 
752        """
753            load a data previously opened
754        """
755        from data_loader import plot_data
756        for item in self.filePathList:
757            id, menuitem_name , path, title = item
758            if id == event.GetId():
759                if path and os.path.isfile(path):
760                    plot_data(self, path)
761                    break
762           
763       
764    def set_manager(self, manager):
765        """
766            Sets the application manager for this frame
767            @param manager: frame manager
768        """
769        self.app_manager = manager
770       
771    def post_init(self):
772        """
773            This initialization method is called after the GUI
774            has been created and all plug-ins loaded. It calls
775            the post_init() method of each plug-in (if it exists)
776            so that final initialization can be done.
777        """
778        for item in self.plugins:
779            if hasattr(item, "post_init"):
780                item.post_init()
781       
782    def set_perspective(self, panels):
783        """
784            Sets the perspective of the GUI.
785            Opens all the panels in the list, and closes
786            all the others.
787           
788            @param panels: list of panels
789        """
790        for item in self.panels:
791            # Check whether this is a sticky panel
792            if hasattr(self.panels[item], "ALWAYS_ON"):
793                if self.panels[item].ALWAYS_ON:
794                    continue 
795           
796            if self.panels[item].window_name in panels:
797                if not self._mgr.GetPane(self.panels[item].window_name).IsShown():
798                    self._mgr.GetPane(self.panels[item].window_name).Show()
799            else:
800                if self._mgr.GetPane(self.panels[item].window_name).IsShown():
801                    self._mgr.GetPane(self.panels[item].window_name).Hide()
802   
803        self._mgr.Update()
804       
805    def choose_file(self, path=None):
806        """
807            Functionality that belongs elsewhere
808            Should add a hook to specify the preferred file type/extension.
809        """
810        #TODO: clean this up
811        from data_loader import choose_data_file
812       
813        # Choose a file path
814        if path==None:
815            path = choose_data_file(self, self._default_save_location)
816           
817        if not path==None:
818            try:
819                self._default_save_location = os.path.dirname(path)
820               
821                #self.n_fileOpen += 1
822                if self.n_fileOpen==1:
823                    pos= self.filemenu.GetMenuItemCount()-1
824                    #self.filemenu.InsertSeparator(pos )
825               
826                id = wx.NewId()
827                filename= os.path.basename(path)
828                dir= os.path.split(self._default_save_location)[1]
829                title= str(os.path.join(dir,filename )) 
830                menuitem_name = str(self.n_fileOpen)+". "+ title
831                position= self.filemenu.GetMenuItemCount()-2
832                #self.filemenu.Insert(id=id, pos= position,text=menuitem_name,help=str(path) )
833                #self.filePathList.append(( id, menuitem_name, path, title))
834                #wx.EVT_MENU(self, id, self._onreloaFile)
835               
836                ## construct menu item for open file
837                if self.n_fileOpen == self.n_maxfileopen +1:
838                    ## reach the maximun number of path to store
839                    self.n_fileOpen = 0
840                    id, menuitem_name , path, title = self.filePathList[0]
841                    self.filemenu.Delete(id)
842                    self.filePathList.pop(0)
843                    for item in self.filePathList:
844                        id, menuitem_name , path, title = item
845                        self.n_fileOpen += 1
846                        label = str(self.n_fileOpen)+". "+ title
847                        #self.filemenu.FindItemById(id).SetItemLabel(label)
848                       
849                         
850            except:
851                raise
852                #pass
853        return path
854   
855    def load_ascii_1D(self, path):
856        from data_loader import load_ascii_1D
857        return load_ascii_1D(path)
858                 
859class DefaultPanel(wx.Panel):
860    """
861        Defines the API for a panels to work with
862        the GUI manager
863    """
864    ## Internal nickname for the window, used by the AUI manager
865    window_name = "default"
866    ## Name to appear on the window title bar
867    window_caption = "Welcome panel"
868    ## Flag to tell the AUI manager to put this panel in the center pane
869    CENTER_PANE = True
870
871 
872# Toy application to test this Frame
873class ViewApp(wx.App):
874    def OnInit(self):
875        #from gui_manager import ViewerFrame
876        self.frame = ViewerFrame(None, -1, config.__appname__)   
877        self.frame.Show(True)
878
879        if hasattr(self.frame, 'special'):
880            self.frame.special.SetCurrent()
881        self.SetTopWindow(self.frame)
882        return True
883   
884    def set_manager(self, manager):
885        """
886            Sets a reference to the application manager
887            of the GUI manager (Frame)
888        """
889        self.frame.set_manager(manager)
890       
891    def build_gui(self):
892        """
893            Build the GUI
894        """
895        self.frame.build_gui()
896        self.frame.post_init()
897       
898    def set_welcome_panel(self, panel_class):
899        """
900            Set the welcome panel
901            @param panel_class: class of the welcome panel to be instantiated
902        """
903        self.frame.set_welcome_panel(panel_class)
904       
905    def add_perspective(self, perspective):
906        """
907            Manually add a perspective to the application GUI
908        """
909        self.frame.add_perspective(perspective)
910       
911
912if __name__ == "__main__": 
913    app = ViewApp(0)
914    app.MainLoop()             
Note: See TracBrowser for help on using the repository browser.