source: sasview/sansguiframe/src/sans/guiframe/data_panel.py @ 1eae432

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 1eae432 was 31f3222b, checked in by Mathieu Doucet <doucetm@…>, 13 years ago

Re #5 OSX Cocoa port of wx doesn't allow wx.CB_SORT

  • Property mode set to 100644
File size: 49.0 KB
Line 
1################################################################################
2#This software was developed by the University of Tennessee as part of the
3#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4#project funded by the US National Science Foundation.
5#
6#See the license text in license.txt
7#
8#copyright 2010, University of Tennessee
9################################################################################
10"""
11This module provides Graphic interface for the data_manager module.
12"""
13import os
14import wx
15from wx.build import build_options
16# Check version
17toks = wx.__version__.split('.')
18if int(toks[1]) < 9:
19    if int(toks[2]) < 12:
20        wx_version = 811
21    else:
22        wx_version = 812
23else:
24    wx_version = 900
25import sys
26import warnings
27import logging
28from wx.lib.scrolledpanel import ScrolledPanel
29import  wx.lib.agw.customtreectrl as CT
30from sans.guiframe.dataFitting import Data1D
31from sans.guiframe.dataFitting import Data2D
32from sans.guiframe.panel_base import PanelBase
33from sans.guiframe.events import StatusEvent
34from sans.guiframe.events import EVT_DELETE_PLOTPANEL
35from sans.guiframe.events import NewLoadDataEvent
36from sans.guiframe.events import NewPlotEvent
37from sans.guiframe.gui_style import GUIFRAME
38from sans.guiframe.events import NewBatchEvent
39from sans.dataloader.loader import Loader
40
41import sans.guiframe.config as config
42 
43extension_list = []
44if config.APPLICATION_STATE_EXTENSION is not None:
45    extension_list.append(config.APPLICATION_STATE_EXTENSION)
46EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS + extension_list   
47PLUGINS_WLIST = config.PLUGINS_WLIST
48APPLICATION_WLIST = config.APPLICATION_WLIST
49
50#Control panel width
51if sys.platform.count("win32") > 0:
52    PANEL_WIDTH = 235
53    PANEL_HEIGHT = 700
54    CBOX_WIDTH = 140
55    BUTTON_WIDTH = 80
56    FONT_VARIANT = 0
57    IS_MAC = False
58else:
59    PANEL_WIDTH = 255
60    PANEL_HEIGHT = 750
61    CBOX_WIDTH = 155
62    BUTTON_WIDTH = 100
63    FONT_VARIANT = 1
64    IS_MAC = True
65
66STYLE_FLAG =wx.RAISED_BORDER|CT.TR_HAS_BUTTONS| CT.TR_HIDE_ROOT|\
67                    wx.WANTS_CHARS|CT.TR_HAS_VARIABLE_ROW_HEIGHT
68                   
69                   
70class DataTreeCtrl(CT.CustomTreeCtrl):
71    """
72    Check list control to be used for Data Panel
73    """
74    def __init__(self, parent,*args, **kwds):
75        #agwstyle is introduced in wx.2.8.11 but is not working for mac
76        if IS_MAC and wx_version < 812:
77            try:
78                kwds['style'] = STYLE_FLAG
79                CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
80            except:
81                del kwds['style']
82                CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
83        else:
84            #agwstyle is introduced in wx.2.8.11 .argument working only for windows
85            try:
86                kwds['agwStyle'] = STYLE_FLAG
87                CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
88            except:
89                try:
90                    del kwds['agwStyle']
91                    kwds['style'] = STYLE_FLAG
92                    CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
93                except:
94                    del kwds['style']
95                    CT.CustomTreeCtrl.__init__(self, parent, *args, **kwds)
96        self.root = self.AddRoot("Available Data")
97       
98class DataPanel(ScrolledPanel, PanelBase):
99    """
100    This panel displays data available in the application and widgets to
101    interact with data.
102    """
103    ## Internal name for the AUI manager
104    window_name = "Data Panel"
105    ## Title to appear on top of the window
106    window_caption = "Data Explorer"
107    #type of window
108    window_type = "Data Panel"
109    ## Flag to tell the GUI manager that this panel is not
110    #  tied to any perspective
111    #ALWAYS_ON = True
112    def __init__(self, parent, 
113                 list=None,
114                 size=(PANEL_WIDTH, PANEL_HEIGHT),
115                 list_of_perspective=None, manager=None, *args, **kwds):
116        kwds['size']= size
117        kwds['style'] = STYLE_FLAG
118        ScrolledPanel.__init__(self, parent=parent, *args, **kwds)
119        PanelBase.__init__(self)
120        self.SetupScrolling()
121        #Set window's font size
122        self.SetWindowVariant(variant=FONT_VARIANT)
123        self.loader = Loader() 
124        #Default location
125        self._default_save_location = None 
126        self.all_data1d = True
127        self.parent = parent
128        self.manager = manager
129        if list is None:
130            list = []
131        self.list_of_data = list
132        if list_of_perspective is None:
133            list_of_perspective = []
134        self.list_of_perspective = list_of_perspective
135        self.list_rb_perspectives= []
136        self.list_cb_data = {}
137        self.list_cb_theory = {}
138        self.tree_ctrl = None
139        self.tree_ctrl_theory = None
140        self.perspective_cbox = None
141        ## Create context menu for page
142        self.data_menu = None
143       
144        self.owner = None
145        self.do_layout()
146        self.fill_cbox_analysis(self.list_of_perspective)
147        self.Bind(wx.EVT_SHOW, self.on_close_page)
148        if self.parent is not None:
149            self.parent.Bind(EVT_DELETE_PLOTPANEL, self._on_delete_plot_panel)
150     
151    def do_layout(self):
152        """
153        """
154        self.define_panel_structure()
155        self.layout_selection()
156        self.layout_data_list()
157        self.layout_batch()
158        self.layout_button()
159       
160   
161    def define_panel_structure(self):
162        """
163        Define the skeleton of the panel
164        """
165        w, h = self.parent.GetSize()
166        self.vbox  = wx.BoxSizer(wx.VERTICAL)
167        self.sizer1 = wx.BoxSizer(wx.VERTICAL)
168        self.sizer1.SetMinSize(wx.Size(w/13, h*2/5))
169     
170        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
171        self.sizer3 = wx.FlexGridSizer(7, 2, 4, 1)
172        self.sizer4 = wx.BoxSizer(wx.VERTICAL)
173        self.sizer5 = wx.BoxSizer(wx.VERTICAL)
174       
175        self.vbox.Add(self.sizer5, 0, wx.EXPAND|wx.ALL,1)
176        self.vbox.Add(self.sizer1, 1, wx.EXPAND|wx.ALL,0)
177        self.vbox.Add(self.sizer2, 0, wx.EXPAND|wx.ALL,1)
178        self.vbox.Add(self.sizer3, 0, wx.EXPAND|wx.ALL,10)
179        #self.vbox.Add(self.sizer4, 0, wx.EXPAND|wx.ALL,5)
180       
181        self.SetSizer(self.vbox)
182       
183    def layout_selection(self):
184        """
185        """
186        select_txt = wx.StaticText(self, -1, 'Selection Options')
187        select_txt.SetForegroundColour('blue')
188        self.selection_cbox = wx.ComboBox(self, -1, style=wx.CB_READONLY)
189        list_of_options = ['Select all Data',
190                            'Unselect all Data',
191                           'Select all Data 1D',
192                           'Unselect all Data 1D',
193                           'Select all Data 2D',
194                           'Unselect all Data 2D' ]
195        for option in list_of_options:
196            self.selection_cbox.Append(str(option))
197        self.selection_cbox.SetValue('Select all Data')
198        wx.EVT_COMBOBOX(self.selection_cbox,-1, self._on_selection_type)
199        self.sizer5.AddMany([(select_txt,0, wx.ALL,5),
200                            (self.selection_cbox,0, wx.ALL,5)])
201        self.enable_selection()
202       
203   
204    def _on_selection_type(self, event):
205        """
206        Select data according to patterns
207        """
208       
209        list_of_options = ['Select all Data',
210                            'Unselect all Data',
211                           'Select all Data 1D',
212                           'Unselect all Data 1D',
213                           'Select all Data 2D',
214                           'Unselect all Data 2D' ]
215        option = self.selection_cbox.GetValue()
216       
217        pos = self.selection_cbox.GetSelection()
218        if pos == wx.NOT_FOUND:
219            return 
220        option = self.selection_cbox.GetString(pos)
221        for item in self.list_cb_data.values():
222            data_ctrl, _, _, _,_, _,_,_= item
223            data_id, data_class, _ = self.tree_ctrl.GetItemPyData(data_ctrl) 
224            if option == 'Select all Data':
225                self.tree_ctrl.CheckItem(data_ctrl, True) 
226            elif option == 'Unselect all Data':
227                self.tree_ctrl.CheckItem(data_ctrl, False)
228            elif option == 'Select all Data 1D':
229                if data_class == 'Data1D':
230                    self.tree_ctrl.CheckItem(data_ctrl, True) 
231            elif option == 'Unselect all Data 1D':
232                if data_class == 'Data1D':
233                    self.tree_ctrl.CheckItem(data_ctrl, False) 
234            elif option == 'Select all Data 1D':
235                if data_class == 'Data1D':
236                    self.tree_ctrl.CheckItem(data_ctrl, True) 
237            elif option == 'Select all Data 2D':
238                if data_class == 'Data2D':
239                    self.tree_ctrl.CheckItem(data_ctrl, True) 
240            elif option == 'Unselect all Data 2D':
241                if data_class == 'Data2D':
242                    self.tree_ctrl.CheckItem(data_ctrl, False) 
243        self.enable_append()
244        self.enable_freeze()
245        self.enable_plot()
246        self.enable_import()
247        self.enable_remove()
248               
249    def layout_button(self):
250        """
251        Layout widgets related to buttons
252        """
253        w, _ = self.GetSize()
254       
255        self.bt_add = wx.Button(self, wx.NewId(), "Load Data", 
256                                size=(BUTTON_WIDTH, -1))
257        self.bt_add.SetToolTipString("Load data files")
258        wx.EVT_BUTTON(self, self.bt_add.GetId(), self._load_data)
259        self.bt_remove = wx.Button(self, wx.NewId(), "Delete Data",
260         size=(BUTTON_WIDTH, -1))
261        self.bt_remove.SetToolTipString("Delete data from the application")
262        wx.EVT_BUTTON(self, self.bt_remove.GetId(), self.on_remove)
263        self.bt_import = wx.Button(self, wx.NewId(), "Send To",
264                                    size=(BUTTON_WIDTH, -1))
265        self.bt_import.SetToolTipString("Send set of Data to active perspective")
266        wx.EVT_BUTTON(self, self.bt_import.GetId(), self.on_import)
267        self.perspective_cbox = wx.ComboBox(self, -1,
268                                style=wx.CB_READONLY)
269        if not IS_MAC:
270            self.perspective_cbox.SetMinSize((BUTTON_WIDTH*1.6, -1))
271        wx.EVT_COMBOBOX(self.perspective_cbox,-1, 
272                        self._on_perspective_selection)
273   
274        self.bt_append_plot = wx.Button(self, wx.NewId(), "Append Plot To",
275                                        size=(BUTTON_WIDTH, -1))
276        self.bt_append_plot.SetToolTipString("Plot the selected data in the active panel")
277        wx.EVT_BUTTON(self, self.bt_append_plot.GetId(), self.on_append_plot)
278       
279        self.bt_plot = wx.Button(self, wx.NewId(), "New Plot", 
280                                 size=(BUTTON_WIDTH, -1))
281        self.bt_plot.SetToolTipString("To trigger plotting")
282        wx.EVT_BUTTON(self, self.bt_plot.GetId(), self.on_plot)
283       
284        self.bt_freeze = wx.Button(self, wx.NewId(), "Freeze Theory", 
285                                   size=(BUTTON_WIDTH, -1))
286        freeze_tip = "To trigger freeze a theory: making a copy\n"
287        freeze_tip += "of the theory checked to Data box,\n"
288        freeze_tip += "     so that it can act like a real data set."
289        self.bt_freeze.SetToolTipString(freeze_tip)
290        wx.EVT_BUTTON(self, self.bt_freeze.GetId(), self.on_freeze)
291        #hide plot
292        #self.bt_close_plot = wx.Button(self, wx.NewId(), "Delete Plot",
293        #                           size=(BUTTON_WIDTH, -1))
294        #self.bt_close_plot.SetToolTipString("Delete the plot panel on focus")
295        #wx.EVT_BUTTON(self, self.bt_close_plot.GetId(), self.on_close_plot)
296       
297        if sys.platform == 'darwin' and build_options.WXPORT == 'osx_cocoa':
298            self.cb_plotpanel = wx.ComboBox(self, -1, 
299                                            style=wx.CB_READONLY)
300        else:
301            self.cb_plotpanel = wx.ComboBox(self, -1, 
302                                            style=wx.CB_READONLY|wx.CB_SORT)
303        #self.cb_plotpanel.SetMinSize((BUTTON_WIDTH*2, -1))
304        wx.EVT_COMBOBOX(self.cb_plotpanel,-1, self._on_plot_selection)
305        self.cb_plotpanel.Disable()
306
307        self.sizer3.AddMany([(self.bt_add),
308                             ((10, 10)),
309                             (self.bt_remove),
310                             ((10, 10)),
311                             (self.bt_freeze),
312                             ((10, 10)),
313                             (self.bt_plot),
314                             ((10, 10)),
315                             (self.bt_append_plot),
316                             (self.cb_plotpanel, wx.EXPAND|wx.ADJUST_MINSIZE, 5),
317                             ((5, 5)),
318                             ((5, 5)),
319                             (self.bt_import, 0, wx.EXPAND|wx.RIGHT, 5),
320                             (self.perspective_cbox, wx.EXPAND|wx.ADJUST_MINSIZE, 5),
321                             ((10, 10)),
322                             (self.sizer4),
323                             ((10, 40)),
324                             ((10, 40))])
325
326        self.sizer3.AddGrowableCol(1, 1)
327        self.show_data_button()
328        self.enable_remove()
329        self.enable_import()
330        self.enable_plot()
331        self.enable_append()
332        self.enable_freeze()
333        self.enable_remove_plot()
334       
335    def layout_batch(self):
336        """
337        """
338        self.rb_single_mode = wx.RadioButton(self, -1, 'Single Mode',
339                                             style=wx.RB_GROUP)
340        self.rb_batch_mode = wx.RadioButton(self, -1, 'Batch Mode')
341        self.Bind(wx.EVT_RADIOBUTTON, self.on_single_mode,
342                     id=self.rb_single_mode.GetId())
343        self.Bind(wx.EVT_RADIOBUTTON, self.on_batch_mode,
344                   id=self.rb_batch_mode.GetId())
345       
346        self.rb_single_mode.SetValue(not self.parent.batch_on)
347        self.rb_batch_mode.SetValue(self.parent.batch_on)
348        self.sizer4.AddMany([(self.rb_single_mode,0, wx.ALL, 4),
349                             (self.rb_batch_mode,0, wx.ALL, 4)])
350       
351    def on_single_mode(self, event):
352        """
353        change guiframe to its single mode
354        """
355        if self.parent is not None:
356                wx.PostEvent(self.parent, 
357                             NewBatchEvent(enable=False))
358       
359    def on_batch_mode(self, event):
360        """
361        change guiframe to its batch mode
362        """
363        if self.parent is not None:
364                wx.PostEvent(self.parent, 
365                             NewBatchEvent(enable=True))
366     
367    def on_edit_data(self, event):
368        """
369        Pop Up Data Editor
370        """
371        selection = event.GetSelection()
372        id, _, _ = self.tree_ctrl.GetSelection().GetData()
373        data_list, _= self.parent._data_manager.get_by_id(id_list=[id])
374       
375        data = data_list.values()[0]
376        from sans.guiframe.local_perspectives.plotting.masking \
377            import MaskPanel as MaskDialog
378       
379        panel = MaskDialog(base=self, data=data, id=wx.NewId())
380        #self.panel.Bind(wx.EVT_CLOSE, self._draw_masked_model)
381        panel.ShowModal()
382       
383    def layout_data_list(self):
384        """
385        Add a listcrtl in the panel
386        """
387        tree_ctrl_label = wx.StaticText(self, -1, "Data")
388        tree_ctrl_label.SetForegroundColour('blue')
389        self.tree_ctrl = DataTreeCtrl(parent=self, style=wx.SUNKEN_BORDER)
390        self.tree_ctrl.Bind(CT.EVT_TREE_ITEM_CHECKING, self.on_check_item)
391        self.tree_ctrl.Bind(CT.EVT_TREE_ITEM_MENU, self.on_right_click)
392        ## Create context menu for page
393        self.data_menu = wx.Menu()
394        id = wx.NewId()
395        name = "Edit Mask"
396        msg = "Edit the current Data"
397        self.data_menu.Append(id, name, msg)
398        wx.EVT_MENU(self, id, self.on_edit_data)
399   
400        tree_ctrl_theory_label = wx.StaticText(self, -1, "Theory")
401        tree_ctrl_theory_label.SetForegroundColour('blue')
402        self.tree_ctrl_theory = DataTreeCtrl(parent=self, 
403                                                    style=wx.SUNKEN_BORDER)
404        self.tree_ctrl_theory.Bind(CT.EVT_TREE_ITEM_CHECKING, 
405                                                    self.on_check_item)
406        self.sizer1.Add(tree_ctrl_label, 0, wx.LEFT, 10)
407        self.sizer1.Add(self.tree_ctrl, 1, wx.EXPAND|wx.ALL, 10)
408        self.sizer1.Add(tree_ctrl_theory_label, 0,  wx.LEFT, 10)
409        self.sizer1.Add(self.tree_ctrl_theory, 1, wx.EXPAND|wx.ALL, 10)
410           
411           
412    def on_right_click(self, event):
413        """
414        Allow Editing Data
415        """
416        selection = event.GetSelection()
417        _, data_class_name, _ = self.tree_ctrl.GetSelection().GetData()
418        if data_class_name == "Data2D" and self.data_menu is not None:
419            self.PopupMenu(self.data_menu) 
420       
421    def onContextMenu(self, event): 
422        """
423        Retrieve the state selected state
424        """
425        # Skipping the save state functionality for release 0.9.0
426        #return
427        pos = event.GetPosition()
428        pos = self.ScreenToClient(pos)
429        self.PopupMenu(self.popUpMenu, pos) 
430     
431 
432    def on_check_item(self, event):
433        """
434        """
435        item = event.GetItem()
436        item.Check(not item.IsChecked()) 
437        self.enable_append()
438        self.enable_freeze()
439        self.enable_plot()
440        self.enable_import()
441        self.enable_remove()
442        event.Skip()
443       
444    def fill_cbox_analysis(self, plugin):
445        """
446        fill the combobox with analysis name
447        """
448        self.list_of_perspective = plugin
449        if self.parent is None or \
450            not hasattr(self.parent, "get_current_perspective") or \
451            len(self.list_of_perspective) == 0:
452            return
453        if self.parent is not None and self.perspective_cbox  is not None:
454            for plug in self.list_of_perspective:
455                if plug.get_perspective():
456                    self.perspective_cbox.Append(plug.sub_menu, plug)
457           
458            curr_pers = self.parent.get_current_perspective()
459            self.perspective_cbox.SetStringSelection(curr_pers.sub_menu)
460        self.enable_import()
461                       
462    def load_data_list(self, list):
463        """
464        add need data with its theory under the tree
465        """
466        if list:
467            for state_id, dstate in list.iteritems():
468                data = dstate.get_data()
469                theory_list = dstate.get_theory()
470                if data is not None:
471                    data_name = str(data.name)
472                    data_title = str(data.title)
473                    data_run = str(data.run)
474                    data_class = data.__class__.__name__
475                    path = dstate.get_path() 
476                    process_list = data.process
477                    data_id = data.id
478                    s_path = str(path)
479                    if state_id not in self.list_cb_data:
480                        #new state
481                        data_c = self.tree_ctrl.InsertItem(self.tree_ctrl.root,0,
482                                                           data_name, ct_type=1, 
483                                             data=(data_id, data_class, state_id))
484                        data_c.Check(True)
485                        d_i_c = self.tree_ctrl.AppendItem(data_c, 'Info')
486                        d_t_c = self.tree_ctrl.AppendItem(d_i_c, 
487                                                      'Title: %s' % data_title)
488                        r_n_c = self.tree_ctrl.AppendItem(d_i_c, 
489                                                      'Run: %s' % data_run)
490                        i_c_c = self.tree_ctrl.AppendItem(d_i_c, 
491                                                      'Type: %s' % data_class)
492                        p_c_c = self.tree_ctrl.AppendItem(d_i_c,
493                                                      "Path: '%s'" % s_path)
494                        d_p_c = self.tree_ctrl.AppendItem(d_i_c, 'Process')
495                       
496                        for process in process_list:
497                            process_str = str(process).replace('\n',' ')
498                            if len(process_str)>20:
499                                process_str = process_str[:20]+' [...]'
500                            i_t_c = self.tree_ctrl.AppendItem(d_p_c,
501                                                              process_str)
502                        theory_child = self.tree_ctrl.AppendItem(data_c, "THEORIES")
503                       
504                        self.list_cb_data[state_id] = [data_c, 
505                                                       d_i_c,
506                                                       d_t_c,
507                                                       r_n_c,
508                                                       i_c_c,
509                                                        p_c_c,
510                                                         d_p_c,
511                                                         theory_child]
512                    else:
513                        data_ctrl_list =  self.list_cb_data[state_id]
514                        #This state is already display replace it contains
515                        data_c, d_i_c, d_t_c, r_n_c,  i_c_c, p_c_c, d_p_c, t_c = data_ctrl_list
516                        self.tree_ctrl.SetItemText(data_c, data_name) 
517                        temp = (data_id, data_class, state_id)
518                        self.tree_ctrl.SetItemPyData(data_c, temp) 
519                        self.tree_ctrl.SetItemText(i_c_c, 'Type: %s' % data_class)
520                        self.tree_ctrl.SetItemText(p_c_c, 'Path: %s' % s_path) 
521                        self.tree_ctrl.DeleteChildren(d_p_c) 
522                        for process in process_list:
523                            i_t_c = self.tree_ctrl.AppendItem(d_p_c,
524                                                              process.__str__())
525                self.append_theory(state_id, theory_list)
526        self.enable_remove()
527        self.enable_import()
528        self.enable_plot()
529        self.enable_freeze()
530        self.enable_selection()
531       
532    def _uncheck_all(self):
533        """
534        Uncheck all check boxes
535        """
536        for item in self.list_cb_data.values():
537            data_ctrl, _, _, _, _, _,_, _ = item
538            self.tree_ctrl.CheckItem(data_ctrl, False) 
539        self.enable_append()
540        self.enable_freeze()
541        self.enable_plot()
542        self.enable_import()
543        self.enable_remove()
544   
545    def append_theory(self, state_id, theory_list):
546        """
547        append theory object under data from a state of id = state_id
548        replace that theory if  already displayed
549        """
550        if not theory_list:
551            return 
552        if state_id not in self.list_cb_data.keys():
553            root = self.tree_ctrl_theory.root
554            tree = self.tree_ctrl_theory
555        else:
556            item = self.list_cb_data[state_id]
557            data_c, _, _, _, _, _, _, _ = item
558            root = data_c
559            tree = self.tree_ctrl
560        if root is not None:
561             self.append_theory_helper(tree=tree, root=root, 
562                                       state_id=state_id, 
563                                       theory_list=theory_list)
564     
565     
566    def append_theory_helper(self, tree, root, state_id, theory_list):
567        """
568        """
569        if state_id in self.list_cb_theory.keys():
570            #update current list of theory for this data
571            theory_list_ctrl = self.list_cb_theory[state_id]
572
573            for theory_id, item in theory_list.iteritems():
574                theory_data, theory_state = item
575                if theory_data is None:
576                    name = "Unknown"
577                    theory_class = "Unknown"
578                    theory_id = "Unknown"
579                    temp = (None, None, None)
580                else:
581                    name = theory_data.name
582                    theory_class = theory_data.__class__.__name__
583                    theory_id = theory_data.id
584                    #if theory_state is not None:
585                    #    name = theory_state.model.name
586                    temp = (theory_id, theory_class, state_id)
587                if theory_id not in theory_list_ctrl:
588                    #add new theory
589                    t_child = tree.AppendItem(root,
590                                                    name, ct_type=1, data=temp)
591                    t_i_c = tree.AppendItem(t_child, 'Info')
592                    i_c_c = tree.AppendItem(t_i_c, 
593                                                  'Type: %s' % theory_class)
594                    t_p_c = tree.AppendItem(t_i_c, 'Process')
595                   
596                    for process in theory_data.process:
597                        i_t_c = tree.AppendItem(t_p_c,
598                                                          process.__str__())
599                    theory_list_ctrl[theory_id] = [t_child, 
600                                                   i_c_c, 
601                                                   t_p_c]
602                else:
603                    #replace theory
604                    t_child, i_c_c, t_p_c = theory_list_ctrl[theory_id]
605                    tree.SetItemText(t_child, name) 
606                    tree.SetItemPyData(t_child, temp) 
607                    tree.SetItemText(i_c_c, 'Type: %s' % theory_class) 
608                    tree.DeleteChildren(t_p_c) 
609                    for process in theory_data.process:
610                        i_t_c = tree.AppendItem(t_p_c,
611                                                          process.__str__())
612             
613        else:
614            #data didn't have a theory associated it before
615            theory_list_ctrl = {}
616            for theory_id, item in theory_list.iteritems():
617                theory_data, theory_state = item
618                if theory_data is not None:
619                    name = theory_data.name
620                    theory_class = theory_data.__class__.__name__
621                    theory_id = theory_data.id
622                    #if theory_state is not None:
623                    #    name = theory_state.model.name
624                    temp = (theory_id, theory_class, state_id)
625                    t_child = tree.AppendItem(root,
626                            name, ct_type=1, 
627                            data=(theory_data.id, theory_class, state_id))
628                    t_i_c = tree.AppendItem(t_child, 'Info')
629                    i_c_c = tree.AppendItem(t_i_c, 
630                                                  'Type: %s' % theory_class)
631                    t_p_c = tree.AppendItem(t_i_c, 'Process')
632                   
633                    for process in theory_data.process:
634                        i_t_c = tree.AppendItem(t_p_c,
635                                                          process.__str__())
636           
637                    theory_list_ctrl[theory_id] = [t_child, i_c_c, t_p_c]
638                #self.list_cb_theory[data_id] = theory_list_ctrl
639                self.list_cb_theory[state_id] = theory_list_ctrl
640       
641           
642   
643    def set_data_helper(self):
644        """
645        """
646        data_to_plot = []
647        state_to_plot = []
648        theory_to_plot = []
649        for value in self.list_cb_data.values():
650            item, _, _, _, _, _, _,  _ = value
651            if item.IsChecked():
652                data_id, _, state_id = self.tree_ctrl.GetItemPyData(item)
653                data_to_plot.append(data_id)
654                if state_id not in state_to_plot:
655                    state_to_plot.append(state_id)
656           
657        for theory_dict in self.list_cb_theory.values():
658            for key, value in theory_dict.iteritems():
659                item, _, _ = value
660                if item.IsChecked():
661                    theory_id, _, state_id = self.tree_ctrl.GetItemPyData(item)
662                    theory_to_plot.append(theory_id)
663                    if state_id not in state_to_plot:
664                        state_to_plot.append(state_id)
665        return data_to_plot, theory_to_plot, state_to_plot
666   
667    def remove_by_id(self, id):
668        """
669        """
670        for item in self.list_cb_data.values():
671            data_c, _, _, _, _, _,  _, theory_child = item
672            data_id, _, state_id = self.tree_ctrl.GetItemPyData(data_c) 
673            if id == data_id:
674                self.tree_ctrl.Delete(data_c)
675                del self.list_cb_data[state_id]
676                del self.list_cb_theory[data_id]
677             
678    def load_error(self, error=None):
679        """
680        Pop up an error message.
681       
682        :param error: details error message to be displayed
683        """
684        if error is not None or str(error).strip() != "":
685            dial = wx.MessageDialog(self.parent, str(error), 'Error Loading File',
686                                wx.OK | wx.ICON_EXCLAMATION)
687            dial.ShowModal() 
688       
689    def _load_data(self, event):
690        """
691        send an event to the parent to trigger load from plugin module
692        """
693        if self.parent is not None:
694            wx.PostEvent(self.parent, NewLoadDataEvent())
695           
696
697    def on_remove(self, event):
698        """
699        Get a list of item checked and remove them from the treectrl
700        Ask the parent to remove reference to this item
701        """
702        msg = "This operation will delete the data sets checked "
703        msg += "and all the dependents."
704        msg_box = wx.MessageDialog(None, msg, 'Warning', wx.OK|wx.CANCEL)
705        if msg_box.ShowModal() != wx.ID_OK:
706            return
707       
708        data_to_remove, theory_to_remove, _ = self.set_data_helper()
709        data_key = []
710        theory_key = []
711        #remove  data from treectrl
712        for d_key, item in self.list_cb_data.iteritems():
713            data_c, d_i_c, d_t_c, r_n_c,  i_c_c, p_c_c, d_p_c, t_c = item
714            if data_c.IsChecked():
715                self.tree_ctrl.Delete(data_c)
716                data_key.append(d_key)
717                if d_key in self.list_cb_theory.keys():
718                    theory_list_ctrl = self.list_cb_theory[d_key]
719                    theory_to_remove += theory_list_ctrl.keys()
720        # Remove theory from treectrl       
721        for t_key, theory_dict in self.list_cb_theory.iteritems():
722            for  key, value in theory_dict.iteritems():
723                item, _, _ = value
724                if item.IsChecked():
725                    try:
726                        self.tree_ctrl.Delete(item)
727                    except:
728                        pass
729                    theory_key.append(key)
730                   
731        #Remove data and related theory references
732        for key in data_key:
733            del self.list_cb_data[key]
734            if key in theory_key:
735                del self.list_cb_theory[key]
736        #remove theory  references independently of data
737        for key in theory_key:
738            for t_key, theory_dict in self.list_cb_theory.iteritems():
739                if key in theory_dict:
740                    for  key, value in theory_dict.iteritems():
741                        item, _, _ = value
742                        if item.IsChecked():
743                            try:
744                                self.tree_ctrl_theory.Delete(item)
745                            except:
746                                pass
747                    del theory_dict[key]
748                   
749           
750        self.parent.remove_data(data_id=data_to_remove,
751                                  theory_id=theory_to_remove)
752        self.enable_remove()
753        self.enable_freeze()
754        self.enable_remove_plot()
755       
756    def on_import(self, event=None):
757        """
758        Get all select data and set them to the current active perspetive
759        """
760        if event != None:
761            event.Skip()
762        data_id, theory_id, state_id = self.set_data_helper()
763        temp = data_id + state_id
764        self.parent.set_data(data_id=temp, theory_id=theory_id)
765       
766    def on_append_plot(self, event=None):
767        """
768        append plot to plot panel on focus
769        """
770        self._on_plot_selection()
771        data_id, theory_id, state_id = self.set_data_helper()
772        self.parent.plot_data(data_id=data_id, 
773                              state_id=state_id,
774                              theory_id=theory_id,
775                              append=True)
776   
777    def on_plot(self, event=None):
778        """
779        Send a list of data names to plot
780        """
781        data_id, theory_id, state_id = self.set_data_helper()
782        self.parent.plot_data(data_id=data_id, 
783                              state_id=state_id,
784                              theory_id=theory_id,
785                              append=False)
786        self.enable_remove_plot()
787         
788    def on_close_page(self, event=None):
789        """
790        On close
791        """
792        if event != None:
793            event.Skip()
794        # send parent to update menu with no show nor hide action
795        self.parent.show_data_panel(action=False)
796   
797    def on_freeze(self, event):
798        """
799        On freeze to make a theory to a data set
800        """
801        _, theory_id, state_id = self.set_data_helper()
802        if len(theory_id) > 0:
803            self.parent.freeze(data_id=state_id, theory_id=theory_id)
804            msg = "Freeze Theory:"
805            msg += " The theory(s) copied to the Data box as a data set."
806        else:
807            msg = "Freeze Theory: Requires at least one theory checked."
808        wx.PostEvent(self.parent, StatusEvent(status=msg))
809           
810    def set_active_perspective(self, name):
811        """
812        set the active perspective
813        """
814        self.perspective_cbox.SetStringSelection(name)
815        self.enable_import()
816       
817    def _on_delete_plot_panel(self, event):
818        """
819        get an event with attribute name and caption to delete existing name
820        from the combobox of the current panel
821        """
822        name = event.name
823        caption = event.caption
824        if self.cb_plotpanel is not None:
825            pos = self.cb_plotpanel.FindString(str(caption)) 
826            if pos != wx.NOT_FOUND:
827                self.cb_plotpanel.Delete(pos)
828        self.enable_append()
829       
830    def set_panel_on_focus(self, name=None):
831        """
832        set the plot panel on focus
833        """
834        for key, value in self.parent.plot_panels.iteritems():
835            name_plot_panel = str(value.window_caption)
836            if name_plot_panel not in self.cb_plotpanel.GetItems():
837                self.cb_plotpanel.Append(name_plot_panel, value)
838            if name != None and name == name_plot_panel:
839                self.cb_plotpanel.SetStringSelection(name_plot_panel)
840                break
841        self.enable_append()
842        self.enable_remove_plot()
843       
844    def _on_perspective_selection(self, event=None):
845        """
846        select the current perspective for guiframe
847        """
848        selection = self.perspective_cbox.GetSelection()
849        if self.perspective_cbox.GetValue() != 'None':
850            perspective = self.perspective_cbox.GetClientData(selection)
851            perspective.on_perspective(event=None)
852            self.parent.check_multimode(perspective=perspective)
853               
854    def _on_plot_selection(self, event=None):
855        """
856        On source combobox selection
857        """
858        if event != None:
859            combo = event.GetEventObject()
860            event.Skip()
861        else:
862            combo = self.cb_plotpanel
863        selection = combo.GetSelection()
864
865        if combo.GetValue() != 'None':
866            panel = combo.GetClientData(selection)
867            self.parent.on_set_plot_focus(panel)   
868           
869    def on_close_plot(self, event):
870        """
871        clseo the panel on focus
872        """ 
873        self.enable_append()
874        selection = self.cb_plotpanel.GetSelection()
875        if self.cb_plotpanel.GetValue() != 'None':
876            panel = self.cb_plotpanel.GetClientData(selection)
877            if self.parent is not None and panel is not None:
878                wx.PostEvent(self.parent, 
879                             NewPlotEvent(group_id=panel.group_id,
880                                          action="delete"))
881        self.enable_remove_plot()
882       
883    def enable_remove_plot(self):
884        """
885        enable remove plot button if there is a plot panel on focus
886        """
887        pass
888        #if self.cb_plotpanel.GetCount() == 0:
889        #    self.bt_close_plot.Disable()
890        #else:
891        #    self.bt_close_plot.Enable()
892           
893    def enable_remove(self):
894        """
895        enable or disable remove button
896        """
897        n_t = self.tree_ctrl.GetCount()
898        n_t_t = self.tree_ctrl_theory.GetCount()
899        if n_t + n_t_t <= 0:
900            self.bt_remove.Disable()
901        else:
902            self.bt_remove.Enable()
903           
904    def enable_import(self):
905        """
906        enable or disable send button
907        """
908        n_t = 0
909        if self.tree_ctrl != None:
910            n_t = self.tree_ctrl.GetCount()
911        if n_t > 0 and len(self.list_of_perspective) > 0:
912            self.bt_import.Enable()
913        else:
914            self.bt_import.Disable()
915        if len(self.list_of_perspective) <= 0 or \
916            self.perspective_cbox.GetValue()  in ["None",
917                                                "No Active Application"]:
918            self.perspective_cbox.Disable()
919        else:
920            self.perspective_cbox.Enable()
921           
922    def enable_plot(self):
923        """
924        enable or disable plot button
925        """
926        n_t = 0 
927        n_t_t = 0
928        if self.tree_ctrl != None:
929            n_t = self.tree_ctrl.GetCount()
930        if self.tree_ctrl_theory != None:
931            n_t_t = self.tree_ctrl_theory.GetCount()
932        if n_t + n_t_t <= 0:
933            self.bt_plot.Disable()
934        else:
935            self.bt_plot.Enable()
936        self.enable_append()
937       
938    def enable_append(self):
939        """
940        enable or disable append button
941        """
942        n_t = 0 
943        n_t_t = 0
944        if self.tree_ctrl != None:
945            n_t = self.tree_ctrl.GetCount()
946        if self.tree_ctrl_theory != None:
947            n_t_t = self.tree_ctrl_theory.GetCount()
948        if n_t + n_t_t <= 0: 
949            self.bt_append_plot.Disable()
950            self.cb_plotpanel.Disable()
951        elif self.cb_plotpanel.GetCount() <= 0:
952                self.cb_plotpanel.Disable()
953                self.bt_append_plot.Disable()
954        else:
955            self.bt_append_plot.Enable()
956            self.cb_plotpanel.Enable()
957           
958    def check_theory_to_freeze(self):
959        """
960        """
961    def enable_freeze(self):
962        """
963        enable or disable the freeze button
964        """
965        n_t_t = 0
966        n_l = 0
967        if self.tree_ctrl_theory != None:
968            n_t_t = self.tree_ctrl_theory.GetCount()
969        n_l = len(self.list_cb_theory)
970        if (n_t_t + n_l > 0):
971            self.bt_freeze.Enable()
972        else:
973            self.bt_freeze.Disable()
974       
975    def enable_selection(self):
976        """
977        enable or disable combobo box selection
978        """
979        n_t = 0
980        n_t_t = 0
981        if self.tree_ctrl != None:
982            n_t = self.tree_ctrl.GetCount()
983        if self.tree_ctrl_theory != None:
984            n_t_t = self.tree_ctrl_theory.GetCount()
985        if n_t + n_t_t > 0 and self.selection_cbox != None:
986            self.selection_cbox.Enable()
987        else:
988            self.selection_cbox.Disable()
989           
990    def show_data_button(self):
991        """
992        show load data and remove data button if
993        dataloader on else hide them
994        """
995        try:
996            gui_style = self.parent.get_style()
997            style = gui_style & GUIFRAME.DATALOADER_ON
998            if style == GUIFRAME.DATALOADER_ON: 
999                #self.bt_remove.Show(True)
1000                self.bt_add.Show(True) 
1001            else:
1002                #self.bt_remove.Hide()
1003                self.bt_add.Hide()
1004        except: 
1005            #self.bt_remove.Hide()
1006            self.bt_add.Hide() 
1007   
1008
1009
1010WIDTH = 400
1011HEIGHT = 300
1012
1013
1014class DataDialog(wx.Dialog):
1015    """
1016    Allow file selection at loading time
1017    """
1018    def __init__(self, data_list, parent=None, text='', *args, **kwds):
1019        wx.Dialog.__init__(self, parent, *args, **kwds)
1020        self.SetTitle("Data Selection")
1021        self.SetSize((WIDTH, HEIGHT))
1022        self.list_of_ctrl = []
1023        if not data_list:
1024            return 
1025        self._sizer_main = wx.BoxSizer(wx.VERTICAL)
1026        self._sizer_txt = wx.BoxSizer(wx.VERTICAL)
1027        self._sizer_button = wx.BoxSizer(wx.HORIZONTAL)
1028        self.sizer = wx.GridBagSizer(5, 5)
1029        self._panel = ScrolledPanel(self, style=wx.RAISED_BORDER,
1030                               size=(WIDTH-20, HEIGHT-50))
1031        self._panel.SetupScrolling()
1032        self.__do_layout(data_list, text=text)
1033       
1034    def __do_layout(self, data_list, text=''):
1035        """
1036        layout the dialog
1037        """
1038        if not data_list or len(data_list) <= 1:
1039            return 
1040        #add text
1041       
1042        text = "Deleting these file reset some panels.\n"
1043        text += "Do you want to proceed?\n"
1044        text_ctrl = wx.StaticText(self, -1, str(text))
1045        self._sizer_txt.Add(text_ctrl)
1046        iy = 0
1047        ix = 0
1048        data_count = 0
1049        for (data_name, in_use, sub_menu) in range(len(data_list)):
1050            if in_use == True:
1051                ctrl_name = wx.StaticBox(self, -1, str(data_name))
1052                ctrl_in_use = wx.StaticBox(self, -1, " is used by ")
1053                plug_name = str(sub_menu) + "\n"
1054                ctrl_sub_menu = wx.StaticBox(self, -1, plug_name)
1055                self.sizer.Add(ctrl_name, (iy, ix),
1056                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1057                ix += 1
1058                self._sizer_button.Add(ctrl_in_use, 1,
1059                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1060                ix += 1
1061                self._sizer_button.Add(plug_name, 1,
1062                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1063            iy += 1
1064        self._panel.SetSizer(self.sizer)
1065        #add sizer
1066        self._sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1067        button_cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
1068        self._sizer_button.Add(button_cancel, 0,
1069                          wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
1070        button_OK = wx.Button(self, wx.ID_OK, "Ok")
1071        button_OK.SetFocus()
1072        self._sizer_button.Add(button_OK, 0,
1073                                wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
1074        static_line = wx.StaticLine(self, -1)
1075       
1076        self._sizer_txt.Add(self._panel, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
1077        self._sizer_main.Add(self._sizer_txt, 1, wx.EXPAND|wx.ALL, 10)
1078        self._sizer_main.Add(self._data_text_ctrl, 0, 
1079                             wx.EXPAND|wx.LEFT|wx.RIGHT, 10)
1080        self._sizer_main.Add(static_line, 0, wx.EXPAND, 0)
1081        self._sizer_main.Add(self._sizer_button, 0, wx.EXPAND|wx.ALL, 10)
1082        self.SetSizer(self._sizer_main)
1083        self.Layout()
1084       
1085    def get_data(self):
1086        """
1087        return the selected data
1088        """
1089        temp = []
1090        for item in self.list_of_ctrl:
1091            cb, data = item
1092            if cb.GetValue():
1093                temp.append(data)
1094        return temp
1095   
1096    def _count_selected_data(self, event):
1097        """
1098        count selected data
1099        """
1100        if event.GetEventObject().GetValue():
1101            self._nb_selected_data += 1
1102        else:
1103            self._nb_selected_data -= 1
1104        select_data_text = " %s Data selected.\n" % str(self._nb_selected_data)
1105        self._data_text_ctrl.SetLabel(select_data_text)
1106        if self._nb_selected_data <= self._max_data:
1107            self._data_text_ctrl.SetForegroundColour('blue')
1108        else:
1109            self._data_text_ctrl.SetForegroundColour('red')
1110       
1111                 
1112       
1113class DataFrame(wx.Frame):
1114    ## Internal name for the AUI manager
1115    window_name = "Data Panel"
1116    ## Title to appear on top of the window
1117    window_caption = "Data Panel"
1118    ## Flag to tell the GUI manager that this panel is not
1119    #  tied to any perspective
1120    ALWAYS_ON = True
1121   
1122    def __init__(self, parent=None, owner=None, manager=None,size=(300, 800),
1123                         list_of_perspective=[],list=[], *args, **kwds):
1124        kwds['size'] = size
1125        kwds['id'] = -1
1126        kwds['title']= "Loaded Data"
1127        wx.Frame.__init__(self, parent=parent, *args, **kwds)
1128        self.parent = parent
1129        self.owner = owner
1130        self.manager = manager
1131        self.panel = DataPanel(parent=self, 
1132                               #size=size,
1133                               list_of_perspective=list_of_perspective)
1134     
1135    def load_data_list(self, list=[]):
1136        """
1137        Fill the list inside its panel
1138        """
1139        self.panel.load_data_list(list=list)
1140       
1141   
1142   
1143from dataFitting import Data1D
1144from dataFitting import Data2D, Theory1D
1145from data_state import DataState
1146import sys
1147class State():
1148    def __init__(self):
1149        self.msg = ""
1150    def __str__(self):
1151        self.msg = "model mane : model1\n"
1152        self.msg += "params : \n"
1153        self.msg += "name  value\n"
1154        return msg
1155def set_data_state(data=None, path=None, theory=None, state=None):
1156    dstate = DataState(data=data)
1157    dstate.set_path(path=path)
1158    dstate.set_theory(theory, state)
1159 
1160    return dstate
1161"""'
1162data_list = [1:('Data1', 'Data1D', '07/01/2010', "theory1d", "state1"),
1163            ('Data2', 'Data2D', '07/03/2011', "theory2d", "state1"),
1164            ('Data3', 'Theory1D', '06/01/2010', "theory1d", "state1"),
1165            ('Data4', 'Theory2D', '07/01/2010', "theory2d", "state1"),
1166            ('Data5', 'Theory2D', '07/02/2010', "theory2d", "state1")]
1167"""     
1168if __name__ == "__main__":
1169   
1170    app = wx.App()
1171    try:
1172        list_of_perspective = [('perspective2', False), ('perspective1', True)]
1173        data_list = {}
1174        # state 1
1175        data = Data2D()
1176        data.name = "data2"
1177        data.id = 1
1178        data.append_empty_process()
1179        process = data.process[len(data.process)-1]
1180        process.data = "07/01/2010"
1181        theory = Data2D()
1182        theory.id = 34
1183        theory.name = "theory1"
1184        path = "path1"
1185        state = State()
1186        data_list['1']=set_data_state(data, path,theory, state)
1187        #state 2
1188        data = Data2D()
1189        data.name = "data2"
1190        data.id = 76
1191        theory = Data2D()
1192        theory.id = 78
1193        theory.name = "CoreShell 07/24/25"
1194        path = "path2"
1195        #state3
1196        state = State()
1197        data_list['2']=set_data_state(data, path,theory, state)
1198        data = Data1D()
1199        data.id = 3
1200        data.name = "data2"
1201        theory = Theory1D()
1202        theory.name = "CoreShell"
1203        theory.id = 4
1204        theory.append_empty_process()
1205        process = theory.process[len(theory.process)-1]
1206        process.description = "this is my description"
1207        path = "path3"
1208        data.append_empty_process()
1209        process = data.process[len(data.process)-1]
1210        process.data = "07/22/2010"
1211        data_list['4']=set_data_state(data, path,theory, state)
1212        #state 4
1213        temp_data_list = {}
1214        data.name = "data5 erasing data2"
1215        temp_data_list['4'] = set_data_state(data, path,theory, state)
1216        #state 5
1217        data = Data2D()
1218        data.name = "data3"
1219        data.id = 5
1220        data.append_empty_process()
1221        process = data.process[len(data.process)-1]
1222        process.data = "07/01/2010"
1223        theory = Theory1D()
1224        theory.name = "Cylinder"
1225        path = "path2"
1226        state = State()
1227        dstate= set_data_state(data, path,theory, state)
1228        theory = Theory1D()
1229        theory.id = 6
1230        theory.name = "CoreShell"
1231        dstate.set_theory(theory)
1232        theory = Theory1D()
1233        theory.id = 6
1234        theory.name = "CoreShell replacing coreshell in data3"
1235        dstate.set_theory(theory)
1236        data_list['3'] = dstate
1237        #state 6
1238        data_list['6']=set_data_state(None, path,theory, state)
1239        data_list['6']=set_data_state(theory=theory, state=None)
1240        theory = Theory1D()
1241        theory.id = 7
1242        data_list['6']=set_data_state(theory=theory, state=None)
1243        data_list['7']=set_data_state(theory=theory, state=None)
1244        window = DataFrame(list=data_list)
1245        window.load_data_list(list=data_list)
1246        window.Show(True)
1247        window.load_data_list(list=temp_data_list)
1248    except:
1249        #raise
1250        print "error",sys.exc_value
1251       
1252    app.MainLoop() 
1253   
1254   
Note: See TracBrowser for help on using the repository browser.