source: sasview/src/sans/guiframe/CategoryManager.py @ 51f14603

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 51f14603 was 51f14603, checked in by Peter Parker, 10 years ago

Refs #202 - Fix Sphinx build errors (not including park-1.2.1/). Most warnings remain.

  • Property mode set to 100755
File size: 16.9 KB
Line 
1#!/usr/bin/python
2
3"""
4This software was developed by Institut Laue-Langevin as part of
5Distributed Data Analysis of Neutron Scattering Experiments (DANSE).
6
7Copyright 2012 Institut Laue-Langevin
8
9"""
10
11
12import wx
13import sys
14import os
15from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin
16from collections import defaultdict
17import cPickle as pickle
18from sans.guiframe.events import ChangeCategoryEvent
19from sans.guiframe.CategoryInstaller import CategoryInstaller
20IS_MAC = (sys.platform == 'darwin')
21
22""" Notes
23The category manager mechanism works from 3 data structures used:
24- self.master_category_dict: keys are the names of categories,
25the values are lists of tuples,
26the first being the model names (the models belonging to that
27category), the second a boolean
28of whether or not the model is enabled
29- self.by_model_dict: keys are model names, values are a list
30of categories belonging to that model
31- self.model_enabled_dict: keys are model names, values are
32bools of whether the model is enabled
33use self._regenerate_model_dict() to create the latter two
34structures from the former
35use self._regenerate_master_dict() to create the first
36structure from the latter two
37
38The need for so many data structures comes from the fact
39sometimes we need fast access
40to all the models in a category (eg user selection from the gui)
41and sometimes we need access to all the categories
42corresponding to a model (eg user modification of model categories)
43
44"""
45
46
47
48class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, 
49                    ListCtrlAutoWidthMixin):
50    """
51    Taken from
52    http://zetcode.com/wxpython/advanced/
53    """
54
55    def __init__(self, parent, callback_func):
56        """
57        Initialization
58        :param parent: Parent window
59        :param callback_func: A function to be called when
60        an element is clicked
61        """
62        wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT \
63                                 | wx.SUNKEN_BORDER)
64        CheckListCtrlMixin.__init__(self)
65        ListCtrlAutoWidthMixin.__init__(self)
66
67        self.callback_func = callback_func
68       
69    def OnCheckItem(self, index, flag):
70        """
71        When the user checks the item we need to save that state
72        """
73        self.callback_func(index, flag)
74   
75
76class CategoryManager(wx.Frame):
77    """
78    A class for managing categories
79    """
80    def __init__(self, parent, win_id, title):
81        """
82        Category Manager Dialog class
83        :param win_id: A new wx ID
84        :param title: Title for the window
85        """
86       
87        # make sure the category file is where it should be
88        self.performance_blocking = False
89
90        self.master_category_dict = defaultdict(list)
91        self.by_model_dict = defaultdict(list)
92        self.model_enabled_dict = defaultdict(bool)
93
94        wx.Frame.__init__(self, parent, win_id, title, size=(660, 400))
95
96        panel = wx.Panel(self, -1)
97        self.parent = parent
98
99        self._read_category_info()
100
101
102        vbox = wx.BoxSizer(wx.VERTICAL)
103        hbox = wx.BoxSizer(wx.HORIZONTAL)
104
105        left_panel = wx.Panel(panel, -1)
106        right_panel = wx.Panel(panel, -1)
107
108        self.cat_list = CheckListCtrl(right_panel, self._on_check)
109        self.cat_list.InsertColumn(0, 'Model', width = 280)
110        self.cat_list.InsertColumn(1, 'Category', width = 240)
111
112        self._fill_lists() 
113        self._regenerate_model_dict()
114        self._set_enabled()     
115
116        vbox2 = wx.BoxSizer(wx.VERTICAL)
117
118        sel = wx.Button(left_panel, -1, 'Enable All', size=(100, -1))
119        des = wx.Button(left_panel, -1, 'Disable All', size=(100, -1))
120        modify_button = wx.Button(left_panel, -1, 'Modify', 
121                                  size=(100, -1))
122        ok_button = wx.Button(left_panel, -1, 'OK', size=(100, -1))
123        cancel_button = wx.Button(left_panel, -1, 'Cancel', 
124                                  size=(100, -1))       
125
126       
127
128        self.Bind(wx.EVT_BUTTON, self._on_selectall, 
129                  id=sel.GetId())
130        self.Bind(wx.EVT_BUTTON, self._on_deselectall, 
131                  id=des.GetId())
132        self.Bind(wx.EVT_BUTTON, self._on_apply, 
133                  id = modify_button.GetId())
134        self.Bind(wx.EVT_BUTTON, self._on_ok, 
135                  id = ok_button.GetId())
136        self.Bind(wx.EVT_BUTTON, self._on_cancel, 
137                  id = cancel_button.GetId())
138
139        vbox2.Add(modify_button, 0, wx.TOP, 10)
140        vbox2.Add((-1, 20))
141        vbox2.Add(sel)
142        vbox2.Add(des)
143        vbox2.Add((-1, 20))
144        vbox2.Add(ok_button)
145        vbox2.Add(cancel_button)
146
147        left_panel.SetSizer(vbox2)
148
149        vbox.Add(self.cat_list, 1, wx.EXPAND | wx.TOP, 3)
150        vbox.Add((-1, 10))
151
152
153        right_panel.SetSizer(vbox)
154
155        hbox.Add(left_panel, 0, wx.EXPAND | wx.RIGHT, 5)
156        hbox.Add(right_panel, 1, wx.EXPAND)
157        hbox.Add((3, -1))
158
159        panel.SetSizer(hbox)
160        self.performance_blocking = True
161
162
163        self.Centre()
164        self.Show(True)
165
166        # gui stuff finished
167
168    def _on_check(self, index, flag):
169        """
170        When the user checks an item we need to immediately save that state.
171        :param index: The index of the checked item
172        :param flag: True or False whether the item was checked
173        """
174        if self.performance_blocking:
175            # for computational reasons we don't want to
176            # call this function every time the gui is set up
177            model_name = self.cat_list.GetItem(index, 0).GetText()
178            self.model_enabled_dict[model_name] = flag
179            self._regenerate_master_dict()
180
181
182    def _fill_lists(self):
183        """
184        Expands lists on the GUI
185        """
186        self.cat_list.DeleteAllItems()
187        model_name_list = [model for model in self.by_model_dict]
188        model_name_list.sort()
189
190        for model in model_name_list:
191            index = self.cat_list.InsertStringItem(sys.maxint, model)
192            self.cat_list.SetStringItem(index, 1, \
193                                            str(self.by_model_dict[model]).\
194                                            replace("'","").\
195                                            replace("[","").\
196                                            replace("]",""))
197
198
199           
200    def _set_enabled(self):
201        """
202        Updates enabled models from self.model_enabled_dict
203        """
204        num = self.cat_list.GetItemCount()
205        for i in range(num):
206            model_name = self.cat_list.GetItem(i, 0).GetText()
207            self.cat_list.CheckItem(i, 
208                                    self.model_enabled_dict[model_name] )
209                                   
210
211
212    def _on_selectall(self, event):
213        """
214        Callback for 'enable all'
215        """
216        self.performance_blocking = False
217        num = self.cat_list.GetItemCount()
218        for i in range(num):
219            self.cat_list.CheckItem(i)
220        for model in self.model_enabled_dict:
221            self.model_enabled_dict[model] = True
222        self._regenerate_master_dict()
223        self.performance_blocking = True
224
225    def _on_deselectall(self, event):
226        """
227        Callback for 'disable all'
228        """
229        self.performance_blocking = False
230        num = self.cat_list.GetItemCount()
231        for i in range(num):
232            self.cat_list.CheckItem(i, False)
233        for model in self.model_enabled_dict:
234            self.model_enabled_dict[model] = False
235        self._regenerate_master_dict()
236        self.performance_blocking = True
237
238    def _on_apply(self, event):
239        """
240        Call up the 'ChangeCat' dialog for category editing
241        """
242
243        if self.cat_list.GetSelectedItemCount() == 0:
244            wx.MessageBox('Please select a model', 'Error',
245                          wx.OK | wx.ICON_EXCLAMATION )
246
247        else:
248            selected_model = \
249                self.cat_list.GetItem(\
250                self.cat_list.GetFirstSelected(), 0).GetText()
251
252
253            modify_dialog = ChangeCat(self, selected_model, 
254                                      self._get_cat_list(),
255                                      self.by_model_dict[selected_model])
256           
257            if modify_dialog.ShowModal() == wx.ID_OK:
258                if not IS_MAC:
259                    self.dial_ok(modify_dialog, selected_model)
260
261    def dial_ok(self, dialog=None, model=None):
262        """
263        modify_dialog onclose
264        """
265        self.by_model_dict[model] = dialog.get_category()
266        self._regenerate_master_dict()
267        self._fill_lists()
268        self._set_enabled()
269
270
271    def _on_ok(self, event):
272        """
273        Close the manager
274        """
275        self._save_state()
276        evt = ChangeCategoryEvent()
277        wx.PostEvent(self.parent, evt)
278
279        self.Destroy()
280
281    def _on_cancel(self, event):
282        """
283        On cancel
284        """
285        self.Destroy()
286
287    def _save_state(self):
288        """
289        Serializes categorization info to file
290        """
291
292        self._regenerate_master_dict()
293
294        cat_file = open(CategoryInstaller.get_user_file(), 'wb')
295
296        pickle.dump( self.master_category_dict, cat_file )
297       
298        cat_file.close()
299   
300    def _read_category_info(self):
301        """
302        Read in categorization info from file
303        """
304        try:
305                file = CategoryInstaller.get_user_file()
306                if os.path.isfile(file):
307                    cat_file = open(file, 'rb')
308                    self.master_category_dict = pickle.load(cat_file)
309                else:
310                        cat_file = open(CategoryInstaller.get_default_file(), 'rb')
311                        self.master_category_dict = pickle.load(cat_file)
312                cat_file.close()
313        except IOError:
314            print 'Problem reading in category file. Please review'
315
316
317        self._regenerate_model_dict()
318
319    def _get_cat_list(self):
320        """
321        Returns a simple list of categories
322        """
323        cat_list = list()
324        for category in self.master_category_dict.iterkeys():
325            if not category == 'Uncategorized':
326                cat_list.append(category)
327   
328        return cat_list
329
330    def _regenerate_model_dict(self):
331        """
332        regenerates self.by_model_dict which has each model
333        name as the key
334        and the list of categories belonging to that model
335        along with the enabled mapping
336        """
337        self.by_model_dict = defaultdict(list)
338        for category in self.master_category_dict:
339            for (model, enabled) in self.master_category_dict[category]:
340                self.by_model_dict[model].append(category)
341                self.model_enabled_dict[model] = enabled
342
343    def _regenerate_master_dict(self):
344        """
345        regenerates self.master_category_dict from
346        self.by_model_dict and self.model_enabled_dict
347        """
348        self.master_category_dict = defaultdict(list)
349        for model in self.by_model_dict:
350            for category in self.by_model_dict[model]:
351                self.master_category_dict[category].append\
352                    ((model, self.model_enabled_dict[model]))
353   
354
355
356class ChangeCat(wx.Dialog):
357    """
358    dialog for changing the categories of a model
359    """
360
361    def __init__(self, parent, title, cat_list, current_cats):
362        """
363        Actual editor for a certain category
364        :param parent: Window parent
365        :param title: Window title
366        :param cat_list: List of all categories
367        :param current_cats: List of categories applied to current model
368        """
369        wx.Dialog.__init__(self, parent, title = 'Change Category: '+title, size=(485, 425))
370
371        self.current_cats = current_cats
372        if str(self.current_cats[0]) == 'Uncategorized':
373            self.current_cats = []
374        self.parent = parent
375        self.selcted_model = title
376        vbox = wx.BoxSizer(wx.VERTICAL)
377        self.add_sb = wx.StaticBox(self, label = "Add Category")
378        self.add_sb_sizer = wx.StaticBoxSizer(self.add_sb, wx.VERTICAL)
379        gs = wx.GridSizer(3, 2, 5, 5)
380        self.cat_list = cat_list
381       
382        self.cat_text = wx.StaticText(self, label = "Current categories: ")
383        self.current_categories = wx.ListBox(self, 
384                                             choices = self.current_cats
385                                             , size=(300, 100))
386        self.existing_check = wx.RadioButton(self, 
387                                             label = 'Choose Existing')
388        self.new_check = wx.RadioButton(self, label = 'Create new')
389        self.exist_combo = wx.ComboBox(self, style = wx.CB_READONLY, 
390                                       size=(220,-1), choices = cat_list)
391        self.exist_combo.SetSelection(0)
392       
393       
394        self.remove_sb = wx.StaticBox(self, label = "Remove Category")
395       
396        self.remove_sb_sizer = wx.StaticBoxSizer(self.remove_sb, 
397                                                 wx.VERTICAL)
398
399        self.new_text = wx.TextCtrl(self, size=(220, -1))
400        self.ok_button = wx.Button(self, wx.ID_OK, "Done")
401        self.add_button = wx.Button(self, label = "Add")
402        self.add_button.Bind(wx.EVT_BUTTON, self.on_add)
403        self.remove_button = wx.Button(self, label = "Remove Selected")
404        self.remove_button.Bind(wx.EVT_BUTTON, self.on_remove)
405
406        self.existing_check.Bind(wx.EVT_RADIOBUTTON, self.on_existing)
407        self.new_check.Bind(wx.EVT_RADIOBUTTON, self.on_newcat)
408        self.existing_check.SetValue(True)
409
410        vbox.Add(self.cat_text, flag = wx.LEFT | wx.TOP | wx.ALIGN_LEFT, 
411                 border = 10)
412        vbox.Add(self.current_categories, flag = wx.ALL | wx.EXPAND, 
413                 border = 10  )
414
415        gs.AddMany( [ (self.existing_check, 5, wx.ALL),
416                      (self.exist_combo, 5, wx.ALL),
417                      (self.new_check, 5, wx.ALL),
418                      (self.new_text, 5, wx.ALL ),
419                      ((-1,-1)),
420                      (self.add_button, 5, wx.ALL | wx.ALIGN_RIGHT) ] )
421
422        self.add_sb_sizer.Add(gs, proportion = 1, flag = wx.ALL, border = 5)
423        vbox.Add(self.add_sb_sizer, flag = wx.ALL | wx.EXPAND, border = 10)
424
425        self.remove_sb_sizer.Add(self.remove_button, border = 5, 
426                                 flag = wx.ALL | wx.ALIGN_RIGHT)
427        vbox.Add(self.remove_sb_sizer, 
428                 flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 
429                 border = 10)
430        vbox.Add(self.ok_button, flag = wx.ALL | wx.ALIGN_RIGHT, 
431                 border = 10)
432       
433        if self.current_categories.GetCount() > 0:
434                self.current_categories.SetSelection(0)
435        self.new_text.Disable()
436        self.SetSizer(vbox)
437        self.Centre()
438        self.Show(True)
439        if IS_MAC:
440            self.ok_button.Bind(wx.EVT_BUTTON, self.on_ok_mac)
441
442    def on_ok_mac(self, event):
443        """
444        On OK pressed (MAC only)
445        """
446        event.Skip()
447        self.parent.dial_ok(self, self.selcted_model)
448        self.Destroy()
449
450    def on_add(self, event):
451        """
452        Callback for new category added
453        """
454        new_cat = ''
455        if self.existing_check.GetValue():
456            new_cat = str(self.exist_combo.GetValue())
457        else:
458            new_cat = str(self.new_text.GetValue())
459            if new_cat in self.cat_list:
460                wx.MessageBox('%s is already a model' % new_cat, 'Error',
461                              wx.OK | wx.ICON_EXCLAMATION )
462                return
463
464        if new_cat in self.current_cats:
465            wx.MessageBox('%s is already included in this model' \
466                              % new_cat, 'Error',
467                          wx.OK | wx.ICON_EXCLAMATION )
468            return
469
470        self.current_cats.append(new_cat)
471        self.current_categories.SetItems(self.current_cats)
472           
473       
474    def on_remove(self, event):
475        """
476        Callback for a category removed
477        """
478        if self.current_categories.GetSelection() == wx.NOT_FOUND:
479            wx.MessageBox('Please select a category to remove', 'Error',
480                          wx.OK | wx.ICON_EXCLAMATION )
481        else:
482            self.current_categories.Delete( \
483                self.current_categories.GetSelection())
484            self.current_cats = self.current_categories.GetItems()
485
486       
487
488    def on_newcat(self, event):
489        """
490        Callback for new category added
491        """
492        self.new_text.Enable()
493        self.exist_combo.Disable()
494
495
496    def on_existing(self, event):   
497        """
498        Callback for existing category selected
499        """
500        self.new_text.Disable()
501        self.exist_combo.Enable()
502
503    def get_category(self):
504        """
505        Returns a list of categories applying to this model
506        """
507        if not self.current_cats:
508            self.current_cats.append("Uncategorized")
509
510        ret = list()
511        for cat in self.current_cats:
512            ret.append(str(cat))
513        return ret
514
515if __name__ == '__main__':
516       
517   
518    if(len(sys.argv) > 1):
519        app = wx.App()
520        CategoryManager(None, -1, 'Category Manager', sys.argv[1])
521        app.MainLoop()
522    else:
523        app = wx.App()
524        CategoryManager(None, -1, 'Category Manager', sys.argv[1])
525        app.MainLoop()
526
Note: See TracBrowser for help on using the repository browser.