source: sasview/src/sans/guiframe/CategoryManager.py @ 27b7acc

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 27b7acc was 27b7acc, checked in by butler, 10 years ago

converted stored category file from pickle to json and a bit of cleanup

  • Property mode set to 100755
File size: 17.1 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 json
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        json.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                self.master_category_dict = json.load(cat_file)
310            else:
311                cat_file = open(CategoryInstaller.get_default_file(), 'rb')
312#                       self.master_category_dict = pickle.load(cat_file)
313                self.master_category_dict = json.load(cat_file)
314            cat_file.close()
315        except IOError:
316            print 'Problem reading in category file. Please review'
317
318
319        self._regenerate_model_dict()
320
321    def _get_cat_list(self):
322        """
323        Returns a simple list of categories
324        """
325        cat_list = list()
326        for category in self.master_category_dict.iterkeys():
327            if not category == 'Uncategorized':
328                cat_list.append(category)
329   
330        return cat_list
331
332    def _regenerate_model_dict(self):
333        """
334        regenerates self.by_model_dict which has each model
335        name as the key
336        and the list of categories belonging to that model
337        along with the enabled mapping
338        """
339        self.by_model_dict = defaultdict(list)
340        for category in self.master_category_dict:
341            for (model, enabled) in self.master_category_dict[category]:
342                self.by_model_dict[model].append(category)
343                self.model_enabled_dict[model] = enabled
344
345    def _regenerate_master_dict(self):
346        """
347        regenerates self.master_category_dict from
348        self.by_model_dict and self.model_enabled_dict
349        """
350        self.master_category_dict = defaultdict(list)
351        for model in self.by_model_dict:
352            for category in self.by_model_dict[model]:
353                self.master_category_dict[category].append\
354                    ((model, self.model_enabled_dict[model]))
355   
356
357
358class ChangeCat(wx.Dialog):
359    """
360    dialog for changing the categories of a model
361    """
362
363    def __init__(self, parent, title, cat_list, current_cats):
364        """
365        Actual editor for a certain category
366        :param parent: Window parent
367        :param title: Window title
368        :param cat_list: List of all categories
369        :param current_cats: List of categories applied to current model
370        """
371        wx.Dialog.__init__(self, parent, title = 'Change Category: '+title, size=(485, 425))
372
373        self.current_cats = current_cats
374        if str(self.current_cats[0]) == 'Uncategorized':
375            self.current_cats = []
376        self.parent = parent
377        self.selcted_model = title
378        vbox = wx.BoxSizer(wx.VERTICAL)
379        self.add_sb = wx.StaticBox(self, label = "Add Category")
380        self.add_sb_sizer = wx.StaticBoxSizer(self.add_sb, wx.VERTICAL)
381        gs = wx.GridSizer(3, 2, 5, 5)
382        self.cat_list = cat_list
383       
384        self.cat_text = wx.StaticText(self, label = "Current categories: ")
385        self.current_categories = wx.ListBox(self, 
386                                             choices = self.current_cats
387                                             , size=(300, 100))
388        self.existing_check = wx.RadioButton(self, 
389                                             label = 'Choose Existing')
390        self.new_check = wx.RadioButton(self, label = 'Create new')
391        self.exist_combo = wx.ComboBox(self, style = wx.CB_READONLY, 
392                                       size=(220,-1), choices = cat_list)
393        self.exist_combo.SetSelection(0)
394       
395       
396        self.remove_sb = wx.StaticBox(self, label = "Remove Category")
397       
398        self.remove_sb_sizer = wx.StaticBoxSizer(self.remove_sb, 
399                                                 wx.VERTICAL)
400
401        self.new_text = wx.TextCtrl(self, size=(220, -1))
402        self.ok_button = wx.Button(self, wx.ID_OK, "Done")
403        self.add_button = wx.Button(self, label = "Add")
404        self.add_button.Bind(wx.EVT_BUTTON, self.on_add)
405        self.remove_button = wx.Button(self, label = "Remove Selected")
406        self.remove_button.Bind(wx.EVT_BUTTON, self.on_remove)
407
408        self.existing_check.Bind(wx.EVT_RADIOBUTTON, self.on_existing)
409        self.new_check.Bind(wx.EVT_RADIOBUTTON, self.on_newcat)
410        self.existing_check.SetValue(True)
411
412        vbox.Add(self.cat_text, flag = wx.LEFT | wx.TOP | wx.ALIGN_LEFT, 
413                 border = 10)
414        vbox.Add(self.current_categories, flag = wx.ALL | wx.EXPAND, 
415                 border = 10  )
416
417        gs.AddMany( [ (self.existing_check, 5, wx.ALL),
418                      (self.exist_combo, 5, wx.ALL),
419                      (self.new_check, 5, wx.ALL),
420                      (self.new_text, 5, wx.ALL ),
421                      ((-1,-1)),
422                      (self.add_button, 5, wx.ALL | wx.ALIGN_RIGHT) ] )
423
424        self.add_sb_sizer.Add(gs, proportion = 1, flag = wx.ALL, border = 5)
425        vbox.Add(self.add_sb_sizer, flag = wx.ALL | wx.EXPAND, border = 10)
426
427        self.remove_sb_sizer.Add(self.remove_button, border = 5, 
428                                 flag = wx.ALL | wx.ALIGN_RIGHT)
429        vbox.Add(self.remove_sb_sizer, 
430                 flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 
431                 border = 10)
432        vbox.Add(self.ok_button, flag = wx.ALL | wx.ALIGN_RIGHT, 
433                 border = 10)
434       
435        if self.current_categories.GetCount() > 0:
436                self.current_categories.SetSelection(0)
437        self.new_text.Disable()
438        self.SetSizer(vbox)
439        self.Centre()
440        self.Show(True)
441        if IS_MAC:
442            self.ok_button.Bind(wx.EVT_BUTTON, self.on_ok_mac)
443
444    def on_ok_mac(self, event):
445        """
446        On OK pressed (MAC only)
447        """
448        event.Skip()
449        self.parent.dial_ok(self, self.selcted_model)
450        self.Destroy()
451
452    def on_add(self, event):
453        """
454        Callback for new category added
455        """
456        new_cat = ''
457        if self.existing_check.GetValue():
458            new_cat = str(self.exist_combo.GetValue())
459        else:
460            new_cat = str(self.new_text.GetValue())
461            if new_cat in self.cat_list:
462                wx.MessageBox('%s is already a model' % new_cat, 'Error',
463                              wx.OK | wx.ICON_EXCLAMATION )
464                return
465
466        if new_cat in self.current_cats:
467            wx.MessageBox('%s is already included in this model' \
468                              % new_cat, 'Error',
469                          wx.OK | wx.ICON_EXCLAMATION )
470            return
471
472        self.current_cats.append(new_cat)
473        self.current_categories.SetItems(self.current_cats)
474           
475       
476    def on_remove(self, event):
477        """
478        Callback for a category removed
479        """
480        if self.current_categories.GetSelection() == wx.NOT_FOUND:
481            wx.MessageBox('Please select a category to remove', 'Error',
482                          wx.OK | wx.ICON_EXCLAMATION )
483        else:
484            self.current_categories.Delete( \
485                self.current_categories.GetSelection())
486            self.current_cats = self.current_categories.GetItems()
487
488       
489
490    def on_newcat(self, event):
491        """
492        Callback for new category added
493        """
494        self.new_text.Enable()
495        self.exist_combo.Disable()
496
497
498    def on_existing(self, event):   
499        """
500        Callback for existing category selected
501        """
502        self.new_text.Disable()
503        self.exist_combo.Enable()
504
505    def get_category(self):
506        """
507        Returns a list of categories applying to this model
508        """
509        if not self.current_cats:
510            self.current_cats.append("Uncategorized")
511
512        ret = list()
513        for cat in self.current_cats:
514            ret.append(str(cat))
515        return ret
516
517if __name__ == '__main__':
518       
519   
520    if(len(sys.argv) > 1):
521        app = wx.App()
522        CategoryManager(None, -1, 'Category Manager', sys.argv[1])
523        app.MainLoop()
524    else:
525        app = wx.App()
526        CategoryManager(None, -1, 'Category Manager', sys.argv[1])
527        app.MainLoop()
528
Note: See TracBrowser for help on using the repository browser.