source: sasview/src/sas/sasgui/guiframe/CategoryInstaller.py @ 42fe90c

Last change on this file since 42fe90c was a26f67f, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

fixup api doc errors

  • Property mode set to 100644
File size: 6.1 KB
Line 
1"""
2Class for making sure all category stuff is installed
3and works fine.
4
5Copyright (c) Institut Laue-Langevin 2012
6
7@author kieranrcampbell@gmail.com
8@modified by NIST/MD sasview team
9"""
10
11import os
12import sys
13import json
14import logging
15from collections import defaultdict, OrderedDict
16
17from sas import get_user_dir
18
19USER_FILE = 'categories.json'
20
21logger = logging.getLogger(__name__)
22
23class CategoryInstaller(object):
24    """
25    Class for making sure all category stuff is installed
26
27    Note - class is entirely static!
28    """
29
30    @staticmethod
31    def _get_installed_model_dir():
32        """
33        returns the dir where installed_models.txt should be
34        """
35        from sas.sascalc.dataloader.readers import get_data_path
36        return get_data_path()
37
38    @staticmethod
39    def _get_default_cat_file_dir():
40        """
41        returns the dir where default_cat.j should be
42        """
43        # The default categories file is usually found with the code, except
44        # when deploying using py2app (it will be in Contents/Resources), or
45        # py2exe (it will be in the exec dir).
46        import sas.sasview
47        cat_file = "default_categories.json"
48
49        possible_cat_file_paths = [
50            os.path.join(os.path.split(sas.sasview.__file__)[0], cat_file),           # Source
51            os.path.join(os.path.dirname(sys.executable), '..', 'Resources', cat_file), # Mac
52            os.path.join(os.path.dirname(sys.executable), cat_file)                     # Windows
53        ]
54
55        for path in possible_cat_file_paths:
56            if os.path.isfile(path):
57                return os.path.dirname(path)
58
59        raise RuntimeError('CategoryInstaller: Could not find folder containing default categories')
60
61    @staticmethod
62    def _get_home_dir():
63        """
64        returns the users sasview config dir
65        """
66        return os.path.join(os.path.expanduser("~"), ".sasview")
67
68    @staticmethod
69    def _regenerate_model_dict(master_category_dict):
70        """
71        regenerates self.by_model_dict which has each model name as the key
72        and the list of categories belonging to that model
73        along with the enabled mapping
74        returns tuplet (by_model_dict, model_enabled_dict)
75        """
76        by_model_dict = defaultdict(list)
77        model_enabled_dict = defaultdict(bool)
78
79        for category in master_category_dict:
80            for (model, enabled) in master_category_dict[category]:
81                by_model_dict[model].append(category)
82                model_enabled_dict[model] = enabled
83
84        return (by_model_dict, model_enabled_dict)
85
86    @staticmethod
87    def _regenerate_master_dict(by_model_dict, model_enabled_dict):
88        """
89        regenerates master_category_dict from by_model_dict
90        and model_enabled_dict
91        returns the master category dictionary
92        """
93        master_category_dict = defaultdict(list)
94        for model in by_model_dict:
95            for category in by_model_dict[model]:
96                master_category_dict[category].append(\
97                    (model, model_enabled_dict[model]))
98        return OrderedDict(sorted(master_category_dict.items(), key=lambda t: t[0]))
99
100    @staticmethod
101    def get_user_file():
102        """
103        returns the user data file, eg .sasview/categories.json.json
104        """
105        return os.path.join(get_user_dir(), USER_FILE)
106
107    @staticmethod
108    def get_default_file():
109        logger.warning("CategoryInstaller.get_default_file is deprecated.")
110
111    @staticmethod
112    def check_install(homedir = None, model_list=None):
113        """
114        Makes sure categories.json exists and if not compile it and install.
115
116        This is the main method of this class.
117
118        :param homefile: Override the default home directory
119        :param model_list: List of model names except those in
120            Plugin Models which are user supplied.
121        """
122        _model_dict = {model.name: model for model in model_list}
123        _model_list = _model_dict.keys()
124
125        serialized_file = None
126        if homedir is None:
127            serialized_file = CategoryInstaller.get_user_file()
128        else:
129            serialized_file = os.path.join(homedir, USER_FILE)
130        if os.path.isfile(serialized_file):
131            with open(serialized_file, 'rb') as f:
132                master_category_dict = json.load(f)
133        else:
134            master_category_dict = defaultdict(list)
135
136        (by_model_dict, model_enabled_dict) = \
137                CategoryInstaller._regenerate_model_dict(master_category_dict)
138        add_list = _model_list
139        del_name = False
140        for cat in master_category_dict.keys():
141            for ind in range(len(master_category_dict[cat])):
142                model_name, enabled = master_category_dict[cat][ind]
143                if model_name not in _model_list:
144                    del_name = True
145                    try:
146                        by_model_dict.pop(model_name)
147                        model_enabled_dict.pop(model_name)
148                    except Exception:
149                        logger.error("CategoryInstaller: %s", sys.exc_value)
150                else:
151                    add_list.remove(model_name)
152        if del_name or (len(add_list) > 0):
153            for model in add_list:
154                model_enabled_dict[model] = True
155                # TODO: should be:  not _model_dict[model].category
156                if (_model_dict[model].category is None
157                        or len(str(_model_dict[model].category.capitalize())) == 0):
158                    by_model_dict[model].append('Uncategorized')
159                else:
160                    category = _model_dict[model].category
161                    toks = category.split(':')
162                    category = toks[-1]
163                    toks = category.split('-')
164                    capitalized_words = [t.capitalize() for t in toks]
165                    category = ' '.join(capitalized_words)
166
167                    by_model_dict[model].append(category)
168
169            master_category_dict = \
170                CategoryInstaller._regenerate_master_dict(by_model_dict,
171                                                          model_enabled_dict)
172
173            json.dump(master_category_dict, open(serialized_file, 'wb'))
Note: See TracBrowser for help on using the repository browser.