Coverage Report - orca.orca_prefs

ModuleCoverage %
orca.orca_prefs
15%
1
# Orca
2
#
3
# Copyright 2004-2007 Sun Microsystems Inc.
4
#
5
# This library is free software; you can redistribute it and/or
6
# modify it under the terms of the GNU Library General Public
7
# License as published by the Free Software Foundation; either
8
# version 2 of the License, or (at your option) any later version.
9
#
10
# This library is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
# Library General Public License for more details.
14
#
15
# You should have received a copy of the GNU Library General Public
16
# License along with this library; if not, write to the
17
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18
# Boston, MA 02111-1307, USA.
19
20 1
"""Common utilities to manage the writing of the user preferences file."""
21
22 1
__id__        = "$Id: orca_prefs.py 2096 2007-03-05 17:05:38Z richb $"
23 1
__version__   = "$Revision: 2096 $"
24 1
__date__      = "$Date: 2007-03-05 09:05:38 -0800 (Mon, 05 Mar 2007) $"
25 1
__copyright__ = "Copyright (c) 2005-2007 Sun Microsystems Inc."
26 1
__license__   = "LGPL"
27
28 1
import os
29 1
import commands
30 1
import pprint
31 1
import settings
32
33 1
from orca_i18n import _  # for gettext support
34
35
# The same fields than in orca_gui_prefs.py:
36 1
(HANDLER, DESCRIP, MOD_MASK1, MOD_USED1, KEY1, TEXT1, MOD_MASK2, MOD_USED2, KEY2, TEXT2, MODIF, EDITABLE) = range(12)
37
38 1
def _createDir(dirname):
39
    """Creates the given directory if it doesn't already exist.
40
    """
41 0
    try:
42 0
        os.chdir(dirname)
43 0
    except:
44 0
        os.mkdir(dirname)
45
46 1
def _writePreferencesPreamble(prefs):
47
    """Writes the preamble to the user-settings.py file."""
48
49 0
    prefs.writelines("# user-settings.py - custom Orca settings\n")
50 0
    prefs.writelines("# Generated by orca.  DO NOT EDIT THIS FILE!!!\n")
51 0
    prefs.writelines("# If you want permanent customizations that will not\n")
52 0
    prefs.writelines("# be overwritten, edit orca-customizations.py.\n")
53 0
    prefs.writelines("#\n")
54 0
    prefs.writelines("import re\n")
55 0
    prefs.writelines("import time\n")
56 0
    prefs.writelines("\n")
57 0
    prefs.writelines("import orca.debug\n")
58 0
    prefs.writelines("import orca.settings\n")
59 0
    prefs.writelines("import orca.acss\n")
60 0
    prefs.writelines("\n")
61 0
    prefs.writelines("# Set the logging level to INFO if you want to log\n")
62 0
    prefs.writelines("# Orca's output of speech and braille using the\n")
63 0
    prefs.writelines("# Python logging API.  Note that setting the\n")
64 0
    prefs.writelines("# orca.debug.debugLevel to orca.debug.LEVEL_INFO\n")
65 0
    prefs.writelines("# will output the same information using Orca's\n")
66 0
    prefs.writelines("# debug facility.\n")
67 0
    prefs.writelines("#\n")
68 0
    prefs.writelines("# import logging\n")
69 0
    prefs.writelines("# orca.debug.log.setLevel(logging.INFO)\n")
70 0
    prefs.writelines("\n")
71
72 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_OFF\n")
73 0
    prefs.writelines("orca.debug.debugLevel = orca.debug.LEVEL_SEVERE\n")
74 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_WARNING\n")
75 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_INFO\n")
76 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_CONFIGURATION\n")
77 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_FINE\n")
78 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_FINER\n")
79 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_FINEST\n")
80 0
    prefs.writelines("#orca.debug.debugLevel = orca.debug.LEVEL_ALL\n")
81 0
    prefs.writelines("\n")
82 0
    prefs.writelines("#orca.debug.eventDebugLevel = orca.debug.LEVEL_OFF\n")
83 0
    prefs.writelines("#orca.debug.eventDebugFilter =  None\n")
84 0
    prefs.writelines("#orca.debug.eventDebugFilter = re.compile('[\S]*focus|[\S]*activ')\n")
85 0
    prefs.writelines("#orca.debug.eventDebugFilter = re.compile('nomatch')\n")
86 0
    prefs.writelines("#orca.debug.eventDebugFilter = re.compile('[\S]*:accessible-name')\n")
87 0
    prefs.writelines("#orca.debug.eventDebugFilter = re.compile('[\S]*:(?!bounds-changed')\n")
88
89 0
    prefs.writelines("\n")
90
91 0
    prefs.writelines("#orca.debug.debugFile = open(time.strftime('debug-%Y-%m-%d-%H:%M:%S.out'), 'w', 0)\n")
92 0
    prefs.writelines("#orca.debug.debugFile = open('debug.out', 'w', 0)\n")
93 0
    prefs.writelines("\n")
94
95 0
    prefs.writelines("#orca.settings.useBonoboMain=False\n")
96 0
    prefs.writelines("#orca.settings.debugEventQueue=True\n")
97 0
    prefs.writelines("#orca.settings.gilSleepTime=0\n")
98 0
    prefs.writelines("\n")
99
100 0
    prefs.writelines("if False:\n")
101 0
    prefs.writelines("    import sys\n")
102 0
    prefs.writelines("    import orca.debug\n")
103 0
    prefs.writelines("    sys.settrace(orca.debug.traceit)\n")
104 0
    prefs.writelines("    orca.debug.debugLevel = orca.debug.LEVEL_ALL\n")
105 0
    prefs.writelines("\n")
106
107 1
def _writePreferencesPostamble(prefs):
108
    """Writes the postamble to the user-settings.py file."""
109 0
    prefs.writelines("\ntry:\n")
110 0
    prefs.writelines("    __import__(\"orca-customizations\")\n")
111 0
    prefs.writelines("except ImportError:\n")
112 0
    prefs.writelines("    pass\n")
113
114 1
def _enableAccessibility():
115
    """Enables the GNOME accessibility flag.  Users need to log out and
116
    then back in for this to take effect.
117
118
    Returns True if an action was taken (i.e., accessibility was not
119
    set prior to this call).
120
    """
121
122 0
    alreadyEnabled = commands.getoutput(\
123
        "gconftool-2 --get /desktop/gnome/interface/accessibility")
124 0
    if alreadyEnabled != "true":
125 0
        os.system("gconftool-2 --type bool --set " \
126
                  + "/desktop/gnome/interface/accessibility true")
127
128 0
    return alreadyEnabled != "true"
129
130 1
def _getDisplayString(display):
131
    """Returns a string that represents the source or taget magnifier display.
132
133
    Arguments:
134
    - display: the magnifier source or taget display string.
135
136
    Returns a string suitable for the preferences file.
137
    """
138
139 0
    if not display:
140 0
        return "''"
141
    else:
142 0
        return "'%s'" % display
143
144 1
def _getSpeechServerFactoryString(factory):
145
    """Returns a string that represents the speech server factory passed in.
146
147
    Arguments:
148
    - factory: the speech server factory
149
150
    Returns a string suitable for the preferences file.
151
    """
152
153 0
    if not factory:
154 0
        return None
155 0
    elif isinstance(factory, basestring):
156 0
        return "'%s'" % factory
157
    else:
158 0
        return "'%s'" % factory.__name__
159
160 1
def _getSpeechServerString(server):
161
    """Returns a string that represents the speech server passed in.
162
163
    Arguments:
164
    - server: a speech server
165
166
    Returns a string suitable for the preferences file.
167
    """
168 0
    if not server:
169 0
        return None
170 0
    elif isinstance(server, [].__class__):
171 0
        return repr(server)
172
    else:
173 0
        return repr(server.getInfo())
174
175 1
def _getVoicesString(voices):
176
    """Returns a string that represents the list of voices passed in.
177
178
    Arguments:
179
    - voices: a list of ACSS instances.
180
181
    Returns a string suitable for the preferences file.
182
    """
183
184 0
    voicesStr = "{\n"
185 0
    for voice in voices:
186 0
        voicesStr += "'%s' : orca.acss.ACSS(" % voice
187 0
        voicesStr += pprint.pformat(voices[voice]) + "),\n"
188 0
    voicesStr += "}"
189
190 0
    return voicesStr
191
192 1
def _getKeyboardLayoutString(keyboardLayout):
193
    """Returns a string that represents the keyboard layout passed in."""
194
195 0
    if keyboardLayout == settings.GENERAL_KEYBOARD_LAYOUT_DESKTOP:
196 0
        return "orca.settings.GENERAL_KEYBOARD_LAYOUT_DESKTOP"
197
    else:
198 0
        return "orca.settings.GENERAL_KEYBOARD_LAYOUT_LAPTOP"
199
200 1
def _getOrcaModifierKeysString(orcaModifierKeys):
201
    """Returns a string that represents the Orca modifier keys passed in."""
202
203 0
    if orcaModifierKeys == settings.DESKTOP_MODIFIER_KEYS:
204 0
        return "orca.settings.DESKTOP_MODIFIER_KEYS"
205
    else:
206 0
        return "orca.settings.LAPTOP_MODIFIER_KEYS"
207
208 1
def _getVerbosityString(verbosityLevel):
209
    """Returns a string that represents the verbosity level passed in."""
210 0
    if verbosityLevel == settings.VERBOSITY_LEVEL_BRIEF:
211 0
        return "orca.settings.VERBOSITY_LEVEL_BRIEF"
212 0
    elif verbosityLevel == settings.VERBOSITY_LEVEL_VERBOSE:
213 0
        return "orca.settings.VERBOSITY_LEVEL_VERBOSE"
214
    else:
215 0
        return "orca.settings.VERBOSITY_LEVEL_VERBOSE"
216
217 1
def _getBrailleRolenameStyleString(rolenameStyle):
218
    """Returns a string that represents the rolename style passed in."""
219 0
    if rolenameStyle == settings.BRAILLE_ROLENAME_STYLE_SHORT:
220 0
        return "orca.settings.BRAILLE_ROLENAME_STYLE_SHORT"
221 0
    elif rolenameStyle == settings.BRAILLE_ROLENAME_STYLE_LONG:
222 0
        return "orca.settings.BRAILLE_ROLENAME_STYLE_LONG"
223
    else:
224 0
        return "orca.settings.BRAILLE_ROLENAME_STYLE_LONG"
225
226 1
def _getVerbalizePunctuationStyleString(punctuationStyle):
227
    """Returns a string that represents the punctuation style passed in."""
228 0
    if punctuationStyle == settings.PUNCTUATION_STYLE_NONE:
229 0
        return "orca.settings.PUNCTUATION_STYLE_NONE"
230 0
    elif punctuationStyle == settings.PUNCTUATION_STYLE_SOME:
231 0
        return "orca.settings.PUNCTUATION_STYLE_SOME"
232 0
    elif punctuationStyle == settings.PUNCTUATION_STYLE_MOST:
233 0
        return "orca.settings.PUNCTUATION_STYLE_MOST"
234 0
    elif punctuationStyle == settings.PUNCTUATION_STYLE_ALL:
235 0
        return "orca.settings.PUNCTUATION_STYLE_ALL"
236
    else:
237 0
        return "orca.settings.PUNCTUATION_STYLE_ALL"
238
239 1
def _getMagCursorColorString(cursorColor):
240
    """Returns a string that represents the magnification cursor color
241
    passed in.
242
243
    Arguments:
244
    - cursorColor: magnification cursor color
245
246
    Returns a string suitable for the preferences file.
247
    """
248
249 0
    cursorColorStr = "'%s'" % cursorColor
250
251 0
    return cursorColorStr
252
253 1
def _getMagSmoothingModeString(smoothingMode):
254
    """Returns a string that represents the magnification smoothing mode
255
    passed in.
256
257
    Arguments:
258
    - smoothingMode: magnification smoothing mode.
259
260
    Returns a string suitable for the preferences file.
261
    """
262
263 0
    if smoothingMode == settings.MAG_SMOOTHING_MODE_BILINEAR:
264 0
        return "orca.settings.MAG_SMOOTHING_MODE_BILINEAR"
265 0
    elif smoothingMode == settings.MAG_SMOOTHING_MODE_NONE:
266 0
        return "orca.settings.MAG_SMOOTHING_MODE_NONE"
267
    else:
268 0
        return "orca.settings.MAG_SMOOTHING_MODE_BILINEAR"
269
270 1
def _getMagMouseTrackingModeString(mouseTrackingMode):
271
    """Returns a string that represents the magnification mouse tracking
272
    mode passed in.
273
274
    Arguments:
275
    - mouseTrackingMode: magnification mouse tracking mode.
276
277
    Returns a string suitable for the preferences file.
278
    """
279
280 0
    if mouseTrackingMode == settings.MAG_MOUSE_TRACKING_MODE_CENTERED:
281 0
        return "orca.settings.MAG_MOUSE_TRACKING_MODE_CENTERED"
282 0
    elif mouseTrackingMode == settings.MAG_MOUSE_TRACKING_MODE_NONE:
283 0
        return "orca.settings.MAG_MOUSE_TRACKING_MODE_NONE"
284 0
    elif mouseTrackingMode == settings.MAG_MOUSE_TRACKING_MODE_PROPORTIONAL:
285 0
        return "orca.settings.MAG_MOUSE_TRACKING_MODE_PROPORTIONAL"
286 0
    elif mouseTrackingMode == settings.MAG_MOUSE_TRACKING_MODE_PUSH:
287 0
        return "orca.settings.MAG_MOUSE_TRACKING_MODE_PUSH"
288
    else:
289 0
        return "orca.settings.MAG_MOUSE_TRACKING_MODE_CENTERED"
290
291 1
def _writeKeyBindingsPreamble(prefs):
292
    """Writes the preamble to the user-settings.py keyBindings section."""
293
294 0
    prefs.writelines("\n")
295 0
    prefs.writelines("# Set up a user key-bindings profile\n")
296 0
    prefs.writelines("#\n")
297 0
    prefs.writelines('def overrideKeyBindings(script, keyB):\n')
298
299 0
    return
300
301 1
def _writeKeyBinding(prefs, tupl):
302
    """Writes a single keyBinding to the user-settings.py keyBindings section.
303
304
    Arguments:
305
    - prefs: text string - file to write the key binding to.
306
    - tupl:    tuple     - a tuple with the values of the
307
                             keybinding (gtk.TreeStore model columns)
308
    """
309
310 0
    prefs.writelines("   keyB.removeByHandler(script.inputEventHandlers['"+str(tupl[HANDLER])+"'])\n")
311
312 0
    if (tupl[TEXT1]):
313 0
        prefs.writelines("   keyB.add(orca.keybindings.KeyBinding(\n")
314 0
        prefs.writelines("      '" + str(tupl[KEY1]) + "',\n")
315 0
        if tupl[MOD_MASK1] or tupl[MOD_USED1]:
316 0
            prefs.writelines("      " + str(tupl[MOD_MASK1]) + ",\n")
317 0
            prefs.writelines("      " + str(tupl[MOD_USED1]) + ",\n")
318
        else:
319 0
            prefs.writelines("      0,\n")
320 0
            prefs.writelines("      0,\n")
321 0
        prefs.writelines('      script.inputEventHandlers["'+ str(tupl[HANDLER]) +'"]))\n\n')
322
323 0
    if (tupl[TEXT2]):
324 0
        prefs.writelines("   keyB.add(orca.keybindings.KeyBinding(\n")
325 0
        prefs.writelines("      '" + str(tupl[KEY2]) + "',\n")
326 0
        if tupl[MOD_MASK2] or tupl[MOD_USED2]:
327 0
            prefs.writelines("      " + str(tupl[MOD_MASK2]) + ",\n")
328 0
            prefs.writelines("      " + str(tupl[MOD_USED2]) + ",\n")
329
        else:
330 0
            prefs.writelines("      0,\n")
331 0
            prefs.writelines("      0,\n")
332 0
        prefs.writelines('      script.inputEventHandlers["'+ str(tupl[HANDLER]) +'"]))\n\n')
333 0
    return
334
335 1
def _writeKeyBindingsPostamble(prefs):
336
    """Writes the postamble to the user-settings.py keyBindings section."""
337
338 0
    prefs.writelines('   return keyB')
339 0
    prefs.writelines("\n\n")
340 0
    prefs.writelines('orca.settings.overrideKeyBindings = overrideKeyBindings')
341 0
    prefs.writelines("\n")
342 0
    return
343
344 1
def _writeKeyBindingsMap(prefs, treeModel):
345
    """Write to configuration file 'prefs' the key bindings passed in the
346
    model treeModel.
347
    """
348
349 0
    _writeKeyBindingsPreamble(prefs)
350
351 0
    iter = treeModel.get_iter_first()
352 0
    while iter != None:
353 0
        iterChild = treeModel.iter_children(iter)
354 0
        while iterChild != None:
355 0
            values = treeModel.get(iterChild, 0,1,2,3,4,5,6,7,8,9,10,11)
356 0
            if values[MODIF]:
357 0
                _writeKeyBinding(prefs, values)
358 0
            iterChild = treeModel.iter_next(iterChild)
359 0
        iter = treeModel.iter_next(iter)
360
361 0
    _writeKeyBindingsPostamble(prefs)
362
363 0
    return
364
365 1
def readPreferences():
366
    """Returns a dictionary containing the names and values of the
367
    customizable features of Orca."""
368
369 2
    prefsDict = {}
370 86
    for key in settings.userCustomizableSettings:
371 84
        if settings.__dict__.has_key(key):
372 84
            prefsDict[key] = settings.__dict__[key]
373
374 2
    return prefsDict
375
376 1
def writePreferences(prefsDict, treeModel=None):
377
    """Creates the directory and files to hold user preferences.  Note
378
    that callers of this method may want to consider using an ordered
379
    dictionary so that the keys are output in a deterministic order.
380
381
    Arguments:
382
    - prefsDict: a dictionary where the keys are orca preferences
383
    names and the values are the values for the preferences.
384
385
    Returns True if accessibility was enabled as a result of this
386
    call."""
387
388
    # Set up the user's preferences directory (~/.orca by default).
389
    #
390 0
    orcaDir = settings.userPrefsDir
391 0
    _createDir(orcaDir)
392
393
    # Set up ~/.orca/orca-scripts as a Python package
394
    #
395 0
    orcaScriptDir = os.path.join(orcaDir, "orca-scripts")
396 0
    _createDir(orcaScriptDir)
397 0
    initFile = os.path.join(orcaScriptDir, "__init__.py")
398 0
    if not os.path.exists(initFile):
399 0
        os.close(os.open(initFile, os.O_CREAT, 0700))
400
401
    # Set up ~/.orca/app-settings as a Python package.
402
    #
403 0
    orcaSettingsDir = os.path.join(orcaDir, "app-settings")
404 0
    _createDir(orcaSettingsDir)
405 0
    initFile = os.path.join(orcaSettingsDir, "__init__.py")
406 0
    if not os.path.exists(initFile):
407 0
        os.close(os.open(initFile, os.O_CREAT, 0700))
408
409
    # Write ~/.orca/user-settings.py
410
    #
411 0
    prefs = open(os.path.join(orcaDir, "user-settings.py"), "w")
412 0
    _writePreferencesPreamble(prefs)
413 0
    for key in settings.userCustomizableSettings:
414 0
        if prefsDict.has_key(key):
415 0
            if key == "voices":
416 0
                value = _getVoicesString(prefsDict[key])
417 0
            elif key == "speechServerInfo":
418 0
                value = _getSpeechServerString(prefsDict[key])
419 0
            elif key == "speechServerFactory":
420 0
                value = _getSpeechServerFactoryString(prefsDict[key])
421 0
            elif key.endswith("VerbosityLevel"):
422 0
                value = _getVerbosityString(prefsDict[key])
423 0
            elif key == "brailleRolenameStyle":
424 0
                value = _getBrailleRolenameStyleString(prefsDict[key])
425 0
            elif key == "verbalizePunctuationStyle":
426 0
                value = _getVerbalizePunctuationStyleString(prefsDict[key])
427 0
            elif key == "magCursorColor":
428 0
                value = _getMagCursorColorString(prefsDict[key])
429 0
            elif key == "magSmoothingMode":
430 0
                value = _getMagSmoothingModeString(prefsDict[key])
431 0
            elif key == "magMouseTrackingMode":
432 0
                value = _getMagMouseTrackingModeString(prefsDict[key])
433 0
            elif key == "magSourceDisplay" or key == "magTargetDisplay":
434 0
                value = _getDisplayString(prefsDict[key])
435 0
            elif key == "keyboardLayout":
436 0
                value = _getKeyboardLayoutString(prefsDict[key])
437 0
            elif key == "orcaModifierKeys":
438 0
                value = _getOrcaModifierKeysString(prefsDict[key])
439
            else:
440 0
                value = prefsDict[key]
441 0
            prefs.writelines("orca.settings.%s = %s\n" % (key, value))
442
443 0
    if treeModel:
444 0
        _writeKeyBindingsMap(prefs, treeModel)
445
446 0
    _writePreferencesPostamble(prefs)
447 0
    prefs.close()
448
449
    # Return True if this caused accessibility to be enabled
450
    # as a result of this call.
451
    #
452 0
    return _enableAccessibility()