summaryrefslogtreecommitdiffstats
path: root/linux/osd/Settings.py
blob: e20bccc2f463a5a93336d475244f31f3a9be6d77 (plain)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# -*- coding: utf-8 -*-

"""OSD Neo2
   ========
   On screen display for learning the keyboard layout Neo2

   Copyright (c) 2009 Martin Zuther (http://www.mzuther.de/)

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

   Thank you for using free software!

"""

# Here follows a plea in German to keep the comments in English so
# that you may understand them, dear visitor ...
#
# Meine Kommentare in den Quellcodes sind absichtlich auf Englisch
# gehalten, damit Leute, die im Internet nach Lösungen suchen, den
# Code nachvollziehen können.  Daher bitte ich darum, zusätzliche
# Kommentare ebenfalls auf Englisch zu schreiben.  Vielen Dank!

import ConfigParser
import gettext
import locale
import os
import types

# initialise localisation settings
module_path = os.path.dirname(os.path.realpath(__file__))
gettext.bindtextdomain('OSDneo2', os.path.join(module_path, 'po/'))
gettext.textdomain('OSDneo2')
_ = gettext.lgettext

class Settings:
    """Store user and application settings in one place and make them available.
    """
    def __init__(self):
        """Initialise user settings and application information.

        Keyword arguments:
        None

        Return value:
        None

        """
        # common application copyrights and information (only set here, private)
        self.__application__ = 'OSD Neo2'
        self.__cmd_line__ = 'OSDneo2'
        self.__version__ = '0.12'
        self.__years__ = '2009'
        self.__authors__ = 'Martin Zuther'
        self.__license_short__ = 'GPL version 3 (or later)'
        self.__license_long__ = """This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Thank you for using free software!"""
        self.__description__ = _('On screen display for learning the keyboard layout Neo2')

        # set INI file path
        self.__config_file_path__ = os.path.expanduser('~/.OSDneo2')

        # if not found otherwise, INI file can be accessed
        self.__can_access_config_file__ = True

        # if INI file doesn't exist or cannot be read, ...
        if not os.access(self.__config_file_path__, os.F_OK | os.R_OK):
            print _('File "%s" not found.\nUsing default settings') % \
                self.__config_file_path__
            # ... try to create it
            try:
                configfile = open(self.__config_file_path__, 'w')
                configfile.close()
            # failed to create INI file
            except IOError, e:
                self.__can_access_config_file__ = False
                print _('No read access to file "%s".\nChanged settings cannot be stored.') % \
                    self.__config_file_path__

        # if INI file cannot be accessed, read or written to, ...
        if self.__can_access_config_file__  and not os.access( \
                self.__config_file_path__, os.F_OK | os.R_OK | os.W_OK):
            # ... then notify the user
            self.__can_access_config_file__ = False
            print _('No write access to file "%s".\nChanged settings cannot be stored.') % \
                self.__config_file_path__

        # read application settings from INI file
        self.__settings__ = ConfigParser.RawConfigParser()
        self.__settings__.read(self.__config_file_path__)


    def __repr__(self):
        """Return all the contents of the INI file as string.

        Keyword arguments:
        None

        Return value:
        Formatted string containing all settings from the INI file

        """
        output = ''
        # sort and output sections
        for section in self.sections():
            output += '\n[%s]\n' % section
            # sort and output settings
            for item in self.items(section):
                output += '%s: %s\n' % (item[0], item[1])
        # dump the whole thing
        return output.lstrip('\n')


    def get(self, section, setting, default):
        """Get an application setting.

        Keyword arguments:
        section -- string that specifies the section to be queried
        setting -- string that specifies the setting to be queried
        value -- string that specifies a default value

        Return value:
        String containing the specified application setting

        """
        # return default value if INI file can't be accessed
        if not self.__can_access_config_file__:
            return default

        try:
            value = self.__settings__.get(section, setting)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            value = default
            if type(default) != types.NoneType:
                self.set(section, setting, default)
        return value


    def set(self, section, setting, value):
        """Set an application setting.

        Keyword arguments:
        section -- string that specifies the section to be changed
        setting -- string that specifies the setting to be changed
        value -- string that specifies the new value

        Return value:
        None

        """
        # do nothing if INI file can't be accessed
        if not self.__can_access_config_file__:
            return

        assert (type(value) == types.StringType) or \
            (type(value) == types.UnicodeType)

        if section not in self.sections():
            self.__settings__.add_section(section)

        old_value = self.get(section, setting, None)

        if value != old_value:
            self.__settings__.set(section, setting, value)

            configfile = open(self.__config_file_path__, 'w')
            configfile.write(self.__repr__())
            configfile.close()


    def items(self, section):
        """Get all application setting names of a section

        Keyword arguments:
        section -- string that specifies the section to be queried

        Return value:
        List containing application setting names of the given section

        """
        items = self.__settings__.items(section)
        items.sort()
        return items


    def sections(self):
        """Get all sections.

        Keyword arguments:
        None

        Return value:
        List containing all section names

        """
        sections = self.__settings__.sections()
        sections.sort()
        return sections


    def get_variable(self, variable):
        """Return application describing variable as string.

        Keyword arguments:
        variable -- variable to query

        Return value:
        Formatted string containing variable's value (or None for
        invalid queries)

        """
        # list of variable names that may be queried (as a security measure)
        valid_variable_names = ('application', 'cmd_line', 'version', \
                                    'years', 'authors', 'license_short', \
                                    'license_long', 'description')

        if variable in valid_variable_names:
            return eval('self.__%s__' % variable)
        else:
            return None


    def get_description(self, long):
        """Return application description as string.

        Keyword arguments:
        long -- Boolean indication whether to output long version of description

        Return value:
        Formatted string containing application description

        """
        if long:
            description = '%(application)s v%(version)s' % \
                {'application':self.get_variable('application'), \
                     'version':self.get_variable('version')}
            description += '\n' + '=' * len(description) + '\n'
            description += '%(description)s' % \
                {'description':self.get_variable('description')}
        else:
            description = '%(application)s %(version)s' % \
                {'application':self.get_variable('application'), \
                     'version':self.get_variable('version')}

        return description


    def get_copyrights(self):
        """Return application copyrights as string.

        Keyword arguments:
        None

        Return value:
        Formatted string containing application copyrights

        """
        return '(c) %(years)s %(authors)s' % \
            {'years':self.get_variable('years'),\
                 'authors':self.get_variable('authors')}


    def get_license(self, long):
        """Return application license as string.

        Keyword arguments:
        long -- Boolean indication whether to output long version of description

        Return value:
        Formatted string containing application license

        """
        if long:
            return self.get_variable('license_long')
        else:
            return self.get_variable('license_short')


# make everything available ("from Settings import *")
settings = Settings()