Preferences.py 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#MDANSE : Molecular Dynamics Analysis for Neutron Scattering Experiments
#------------------------------------------------------------------------------------------
#Copyright (C)
#2015- Eric C. Pellegrini Institut Laue-Langevin
#BP 156
#6, rue Jules Horowitz
#38042 Grenoble Cedex 9
#France
#pellegrini[at]ill.fr
#goret[at]ill.fr
#aoun[at]ill.fr
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

''' 
Created on Mar 30, 2015

30
:author: Eric C. Pellegrini
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'''

import abc
import collections
import ConfigParser
import os

from MDANSE.Core.Platform import PLATFORM, PlatformError
from MDANSE.Core.Error import Error
from MDANSE.Core.Singleton import Singleton

class PreferencesError(Error):
    '''
    This class handles the errors that occurs in Preferences.
    '''
    
    pass

class PreferencesItem(object):
    '''
    This is the base class for defining a preferences item.
    
53
    A preferences item implements is a light object used to check preferences before setting them 
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    but also classify preferences according to their section for a further use in MDANSE GUI.
    '''
    
    __metaclass__ = abc.ABCMeta

    def __init__(self, name, section, default, *args, **kwargs):
        '''
        Constructor a new prferences item.
        
        :param name: the name of the preference item
        :type name: str 
        :param section: the section of the preferences item
        :type section: str
        :param default: the default value for the preferences item
        :type default: str
        '''
        
        self._name = name
        
        self._section = section
        
        self._default = default
        
        self._value = self._default
                
    @property
    def default(self):
        '''
        Returns the default value of the preferences item.
        
        :return: the default value of the preferences item
        :rtype: str
        '''
        
        return self._default
    
    def get_default(self):
        '''
        Returns the default value of the preferences item.
        
        :return: the default value of the preferences item
        :rtype: str
        '''
        
        return self._default
        
    @property
    def name(self):
        '''
        Returns the name of the preferences item.
        
        :return: the name of the preferences item
        :rtype: str
        '''

        return self._name

    def get_name(self):
        '''
        Returns the name of the preferences item.
        
        :return: the name of the preferences item
        :rtype: str
        '''

        return self._name
        
    @property
    def section(self):
        '''
        Returns the section of the preferences item.
        
        :return: the section of the preferences item
        :rtype: str
        '''

        return self._section
    
    def get_section(self):
        '''
        Returns the section of the preferences item.
        
        :return: the section of the preferences item
        :rtype: str
        '''
        
        return self._section
    
    def reset(self):
        '''
        Reset the preferences item to its default value
        '''
        
        self._value = self._default
        
    @property
    def value(self):
        '''
        Returns the value of the preferences item.
        
        :return: the value of the preferences item
        :rtype: str
        '''

        return self._value

    def get_value(self):
        '''
        Returns the value of the preferences item.
        
        :return: the value of the preferences item
        :rtype: str
        '''

        return self._value

170
171
172
173
174
175
176
177
178
179
180
    @abc.abstractmethod
    def check_value(self,value):
        '''
        Set the value of the preferences item.
        
        :param value: the value of the preferences item
        :type value: str
        '''
        
        pass

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    @abc.abstractmethod
    def set_value(self,value):
        '''
        Set the value of the preferences item.
        
        :param value: the value of the preferences item
        :type value: str
        '''
        
        pass

class InputDirectory(PreferencesItem):
    '''
    This class implements a preferences item that handles an input directory.
    
    When set to a given input directory, if this one does not exists, it will be be created.
    '''
    
    type = "input_directory"

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    def check_value(self,value):
        '''
        Check the value of the preferences item.
        
        :param value: the value of the preferences item
        :type value: str
        
        :return: True if the value is correct, False otherwise.
        :rtype: bool
        '''
        
        value = PLATFORM.get_path(value)
        
        try:
            PLATFORM.create_directory(value)
        except PlatformError:
            return False
        else:        
            return True
    
221
222
223
224
225
226
227
228
229
    def set_value(self, value):
        '''
        Set the value of the input directory preferences item.
        
        :param value: the input directory
        :type value: str
        '''
        
        value = PLATFORM.get_path(value)
eric pellegrini's avatar
eric pellegrini committed
230
                
231
232
233
        try:
            PLATFORM.create_directory(value)
        except PlatformError:
234
            raise PreferencesError('Invalid value for %r preferences item. Set the default value instead.' % self._name)
235
236
237
            self._value = self._default
        else:        
            self._value = value
238
239
        
    def get_value(self):
eric pellegrini's avatar
eric pellegrini committed
240
                
241
        return self._value
242
                
243
class Preferences(collections.OrderedDict):
244
245
246
    '''
    This class implements the MDANSE preferences.
    
247
    :note: Preferences are defined using the ConfigParser python module that allows to read and write \
248
249
250
251
252
    preferences stored in a formatted INI file (RFC822).
    '''
    
    __metaclass__ = Singleton
    
253
    def __init__(self,*args,**kwargs):
254
255
256
257
        '''
        Constructs the preferences
        '''
        
258
259
260
261
        collections.OrderedDict.__init__(self,*args,**kwargs)
        
        collections.OrderedDict.__setitem__(self,"working_directory",InputDirectory("working_directory", "paths", PLATFORM.home_directory())) 
        collections.OrderedDict.__setitem__(self,"macros_directory",InputDirectory("macros_directory", "paths", os.path.join(PLATFORM.home_directory(), "mdanse_macros"))) 
262
                                
263
264
        self._parser = ConfigParser.ConfigParser()

265
        for s in self.values():
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            try:
                self._parser.add_section(s.section)
            except ConfigParser.DuplicateSectionError:
                pass
                                                                    
        # Overwrite the default preferences with the user defined loaded ones.
        try:
            self.load()
        except PreferencesError:
            pass
        
    @property
    def parser(self):
        '''
        Returns the configuration parser object used to serialize the preferences.
        
        :return: the configuration parser bound to the preferences
        :rtype: ConfigParser.ConfigParser
        '''
        return self._parser
286
287
288
289
290
291
292
293
294
295
    
    def __setitem__(self,item,value):
        
        pass
    
    def clear(self):
        
        pass
    
    def __getitem__(self, item):
296
297
298
299
300
301
302
        '''
        Get the value of a selected preferences item.
        
        :param item: the preferences item
        :type item: str

        :return: the values of the preferences item.
303
        :rtype: ``PreferencesItem`` subclass
304
305
306
        '''
        
        try:
307
            return collections.OrderedDict.__getitem__(self,item)
308
        except KeyError:
309
            raise PreferencesError("Unknown preferences item")
310
                        
311
    def load(self, path=None):
312
        '''
313
314
315
316
317
318
        Load the preferences from an existing Preferences file.

        The default value is the default location for loading Preferences file.
        
        :param path: the path for the preferences file
        :type path: str   
319
320
        '''
                    
321
322
        if path is None:
            path = PLATFORM.preferences_file()
323
324
325
326
327

        if not isinstance(path,basestring):
            raise PreferencesError("Invalid type for preferences filename: %s" % path)
        
        if not os.path.exists(path):
328
            raise PreferencesError("The preferences files %s does not exists. MDANSE will use the default preferences." % path)
329
330
                
        try:
331
            # Read the preferences and overwrites the MDANSE default preferences.
332
333
334
335
336
337
            self._parser.read(path)
        except ConfigParser.ParsingError as e:
            raise PreferencesError(e)
        
        for s in self._parser.sections():
            for k, v in self._parser.items(s):
338
                if self.has_key(k):
339
340
341
342
                    try:
                        self[k].set_value(v)
                    except PreferencesError:
                        continue                        
343
344
345
346
347
                else:
                    self._parser.remove_option(s,k)
            if not self._parser.items(s):
                self._parser.remove_section(s)
                                                                 
348
    def save(self,path=None):
349
        '''
350
351
352
353
354
355
        Save the preferences to a file.
        
        The default value is the default location for loading Preferences file.
        
        :param path: the path for the preferences file
        :type path: str   
356
357
        '''
        
358
359
        if path is None:
            path = PLATFORM.preferences_file()
360
361
362
363
364
365
            
        try:
            f = open(path, "w")
        except (IOError,TypeError) as e:
            raise PreferencesError(e)

366
        for v in self.values():
367
368
369
370
371
372
373
374
375
            self._parser.set(v.section,v.name,v.value)
                
        # Write the preferences.
        self._parser.write(f)
        
        # Closes the preferences file.
        f.close()
        
PREFERENCES = Preferences()