# -*- coding: utf-8 -*-

# Copyright (c) 2002 - 2007 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Package implementing the preferences interface.

The preferences interface consists of a class, which defines the default
values for all configuration items and stores the actual values. These
values are read and written to the eric4 preferences file by module
functions. On Windows the data is located in the registry, everywhere 
else it is stored in a file in a subdirectory of the users home directory.
The individual configuration data is accessed by accessor functions defined
on the module level. The module is simply imported wherever it is needed
with the statement 'import Preferences'. Do not use 'from Preferences import *'
to import it.
"""

import sys
import os
import fnmatch

from PyQt4 import QtCore, QtGui
from PyQt4 import Qsci

import QScintilla.Lexers

from ViewManager.Config import ConfigViewManagers
from Globals import settingsNameOrganization, settingsNameGlobal, settingsNameRecent

class Prefs(object):
    """
    A class to hold all configuration items for the application.
    """
    # defaults for the variables window
    varDefaults = {
        "LocalsFilter" : [],
        "GlobalsFilter" : []
    }
    
    # defaults for the debugger
    debuggerDefaults = {
        "RemoteDbgEnabled" : 0,
        "RemoteHost" : "",
        "RemoteExecution" : "",
        "PassiveDbgEnabled" : 0,
        "PassiveDbgPort" : 42424,
        "AutomaticReset" : 0,
        "Autosave" : 0,
        "CustomPythonInterpreter" : 0,
        "PythonInterpreter" : "",
        "RubyInterpreter" : "/usr/bin/ruby",
        "DebugClientType" : "standard",     # supported "standard", "threaded", "custom"
        "DebugClient" : "",
        "DebugEnvironmentReplace" : 0,
        "DebugEnvironment" : "",
        "PythonRedirect" : 1,
        "PythonNoEncoding" : 0,
        "RubyRedirect" : 1,
        "ConsoleDbgEnabled" : 0,
        "ConsoleDbgCommand" : "",
        "PathTranslation" : 0,
        "PathTranslationRemote" : "",
        "PathTranslationLocal" : "",
        "NetworkInterface" : "127.0.0.1",
    }
    debuggerDefaults["AllowedHosts"] = QtCore.QStringList("127.0.0.1")
    
    uiDefaults = {
        "Language" : "System",
        "Style" : "System",
        "StyleSheet" : "",
        "ViewManager" : "tabview",
        "LayoutType" : "DockWindows",
        # allowed values are "DockWindows" and "FloatingWindows"
        "LayoutShellEmbedded" : 0,          # 0 = separate
                                            # 1 = embedded in debug browser
        "LayoutFileBrowserEmbedded" : 1,    # 0 = separate
                                            # 1 = embedded in debug browser
                                            # 2 = embedded in project browser
        "BrowsersListFoldersFirst" : 1,
        "BrowsersHideNonPublic" : 0,
        "SingleApplicationMode" : 0,
        "CaptionShowsFilename" : 1,
        "CaptionFilenameLength" : 100,
        "TabViewManagerFilenameLength" : 40,
        # the order in ViewProfiles is Project-Browser, File-Browser,
        # Debug-Browser, Python-Shell, Log-Viewer, Task-Viewer,
        # Templates-Viewer
        "ViewProfiles" : {
            "edit"  : [
                        # visibility
                        [ 1,  0,  0,  1,  1,  1,  1],
                        # saved state main window with dock windows
                        "",
                        # saved states floating windows
                        ["", "", "", "", "", "", ""],
                        # saved state main window with floating windows
                        ""
                      ],
            "debug" : [
                        # visibility
                        [ 0,  0,  1,  1,  1,  1,  0], 
                        # saved state main window with dock windows
                        "",
                        # saved states floating windows
                        ["", "", "", "", "", "", ""],
                        # saved state main window with floating windows
                        ""
                      ],
        },
        "ShowSplash" : 1,
        
        "PerformVersionCheck" : 4,      # 0 = off
                                        # 1 = at startup
                                        # 2 = daily
                                        # 3 = weekly
                                        # 4 = monthly
        "UseProxy" : 0,
        "ProxyHost" : "",
        "ProxyPort" : 80,
        "ProxyUser" : "",
        "ProxyPassword" : "",
        "UseIconProvider" : 1,
    }
    if sys.platform == "win32" or sys.platform == "darwin":
        uiDefaults["UseKDEDialogs"] = 0
    else:
        uiDefaults["UseKDEDialogs"] = 1
    viewProfilesLength = len(uiDefaults["ViewProfiles"]["edit"][2])
    
    iconsDefaults = {
        "Path" : QtCore.QStringList(),
    }
    
    # defaults for the editor settings
    editorDefaults = {
        "AutosaveInterval" : 0,
        "TabWidth" : 4,
        "IndentWidth" : 4,
        "LinenoWidth" : 4,
        "IndentationGuides" : 1,
        "LinenoMargin" : 1,
        "FoldingMargin" : 1,
        "FoldingStyle" : 1,
        "TabForIndentation" : 0,
        "TabIndents" : 1,
        "ConvertTabsOnLoad" : 0,
        "AutomaticEOLConversion" : 1,
        "ShowWhitespace" : 0,
        "ShowEOL" : 0,
        "UseMonospacedFont" : 0,
        "WrapLongLines" : 1,
        "WarnFilesize" : 512,
        "ClearBreaksOnClose" : 1,
        
        "EdgeMode" : Qsci.QsciScintilla.EdgeNone,
        "EdgeColumn" : 80,
        
        "AutoIndentation" : 1,
        "BraceHighlighting" : 1,
        "CreateBackupFile" : 0,
        "CaretLineVisible" : 0,
        "CaretWidth" : 1,
        "ColourizeSelText" : 0,
        "CustomSelectionColours" : 0,
        "ExtendSelectionToEol" : 0,
        
        "AutoPrepareAPIs" : 0,
        
        "AutoCompletionEnabled" : 0,
        "AutoCompletionCaseSensitivity" : 1,
        "AutoCompletionReplaceWord" : 0,
        "AutoCompletionShowSingle" : 0,
        "AutoCompletionSource" : Qsci.QsciScintilla.AcsDocument,
        "AutoCompletionThreshold" : 2,
        "AutoCompletionFillups" : 0,
        
        "CallTipsEnabled" : 0,
        "CallTipsVisible" : -1,
        "CallTipsStyle"   : Qsci.QsciScintilla.CallTipsNoContext,
        
        "AutoCheckSyntax" : 1,
        "AutoReopen" : 0,
        
        "MiniContextMenu" : 0,
        
        "DefaultEncoding" : "utf8",
        "DefaultOpenFilter" : "",
        "DefaultSaveFilter" : "",
        
        # All (most) lexers
        "AllFoldCompact" : 1,
        
        # Python specifics
        "PythonBadIndentation" : 1,
        "PythonFoldComment" : 1,
        "PythonFoldString" : 1,
        "PythonAutoIndent" : 0,
        
        # C++ specifics
        "CppCaseInsensitiveKeywords" : 0, 
        "CppFoldComment" : 1,
        "CppFoldPreprocessor" : 0,
        "CppFoldAtElse" : 0,
        "CppIndentOpeningBrace" : 0,
        "CppIndentClosingBrace" : 0,
        
        # SQL specifics
        "SqlFoldComment" : 1,
        "SqlBackslashEscapes" : 0,
        
        # HTML specifics
        "HtmlFoldPreprocessor" : 0,
        "HtmlCaseSensitiveTags" : 0,
        
        # Perl specifics
        "PerlFoldComment" : 1,
        
        # Bash specifics
        "BashFoldComment" : 1,
        
        # CSS specifics
        "CssFoldComment" : 1,
        
        # D specifics
        "DFoldComment" : 1,
        "DFoldAtElse" : 0,
        "DIndentOpeningBrace" : 0,
        "DIndentClosingBrace" : 0,
        
        # Povray specifics
        "PovFoldComment" : 1,
        "PovFoldDirectives" : 0,
        
        # CMake specifics
        "CMakeFoldAtElse" : 0,
        
        # VHDL specifics
        "VHDLFoldComment" : 1,
        "VHDLFoldAtElse" : 1,
        "VHDLFoldAtBegin" : 1, 
        "VHDLFoldAtParenthesis" : 1, 
    }
    
    if sys.platform == "win32":
        editorDefaults["EOLMode"] = Qsci.QsciScintilla.EolWindows
    else:
        editorDefaults["EOLMode"] = Qsci.QsciScintilla.EolUnix
    
    editorColourDefaults = {
        "CurrentMarker"        : QtGui.QColor(QtCore.Qt.yellow),
        "ErrorMarker"          : QtGui.QColor(QtCore.Qt.red),
        "MatchingBrace"        : QtGui.QColor(QtCore.Qt.green),
        "MatchingBraceBack"    : QtGui.QColor(QtCore.Qt.white),
        "NonmatchingBrace"     : QtGui.QColor(QtCore.Qt.red),
        "NonmatchingBraceBack" : QtGui.QColor(QtCore.Qt.white),
        "CallTipsBackground"   : QtGui.QColor(QtCore.Qt.white),
        "CaretForeground"      : QtGui.QColor(QtCore.Qt.black),
        "CaretLineBackground"  : QtGui.QColor(QtCore.Qt.white),
        "Edge"                 : QtGui.QColor(QtCore.Qt.lightGray),
        "SelectionBackground"  : QtGui.QColor(QtCore.Qt.black),
        "SelectionForeground"  : QtGui.QColor(QtCore.Qt.white),
    }
    
    editorOtherFontsDefaults = {
        "MarginsFont"    : "Sans Serif,10,-1,5,50,0,0,0,0,0",
        "DefaultFont"    : "Sans Serif,10,-1,5,50,0,0,0,0,0",
        "MonospacedFont" : "Courier,10,-1,5,50,0,0,0,0,0"
    }
    
    editorAPIDefaults = {}
    for language in QScintilla.Lexers.getSupportedLanguages().keys():
        editorAPIDefaults[language] = QtCore.QStringList()
    
    editorLexerAssocDefaults = QScintilla.Lexers.getDefaultLexerAssociations()
    
    editorTypingDefaults = {
        "Python/EnabledTypingAids"  : 1, 
        "Python/InsertClosingBrace" : 1,
        "Python/IndentBrace"        : 1,
        "Python/SkipBrace"          : 1,
        "Python/InsertQuote"        : 1,
        "Python/DedentElse"         : 1,
        "Python/DedentExcept"       : 1,
        "Python/Py24StyleTry"       : 1, 
        "Python/InsertImport"       : 1,
        "Python/InsertSelf"         : 1,
        "Python/InsertBlank"        : 1,
        "Python/ColonDetection"     : 1,
        
        "Ruby/EnabledTypingAids"    : 1, 
        "Ruby/InsertClosingBrace"   : 1,
        "Ruby/IndentBrace"          : 1,
        "Ruby/SkipBrace"            : 1,
        "Ruby/InsertQuote"          : 1,
        "Ruby/InsertBlank"          : 1,
        "Ruby/InsertHereDoc"        : 1, 
        "Ruby/InsertInlineDoc"      : 1, 
    }
    
    # defaults for the printer settings
    printerDefaults = {
        "PrinterName" : "",
        "ColorMode" : 1,
        "FirstPageFirst" : 1,
        "Magnification" : -3,
        "Orientation" : 0,
        "PageSize": 0,
        "HeaderFont" : "Serif,10,-1,5,50,0,0,0,0,0"
    }
    
    # defaults for the project settings
    projectDefaults = {
        "SearchNewFiles" : 0,
        "AutoIncludeNewFiles" : 0,
        "AutoLoadSession" : 0,
        "AutoSaveSession" : 0,
        "SessionAllBreakpoints" : 0,
        "CompressedProjectFiles" : 0,
        "XMLTimestamp" : 1,
        "AutoCompileForms" : 0,
        "AutoCompileResources" : 0,
        "AutoLoadDbgProperties" : 0,
        "AutoSaveDbgProperties" : 0,
        "HideGeneratedForms" : 0,
    }
    
    # defaults for the project browser colour settings
    projectBrowserColourDefaults = {
        "Highlighted"        : QtGui.QColor(QtCore.Qt.red),
        
        "VcsAdded"           : QtGui.QColor(QtCore.Qt.blue),
        "VcsConflict"        : QtGui.QColor(QtCore.Qt.red),
        "VcsModified"        : QtGui.QColor(QtCore.Qt.yellow),
        "VcsUpdate"          : QtGui.QColor(QtCore.Qt.green),
    }
    
    # defaults for the help settings
    helpDefaults = {
        "HelpViewerType" : 1,      # this coresponds with the radio button id
        "CustomViewer" : "",
        "PythonDocDir" : "",
        "QtDocDir" : "",
        "Qt4DocDir" : "",
        "PyQt4DocDir" : "",
        "SingleHelpWindow" : 1,
        "SaveGeometry" : 1,
    }
    
    # defaults for system settings
    sysDefaults = {
        "StringEncoding" : "utf8",
        "IOEncoding"     : "utf8",
    }
    
    # defaults for the shell settings
    shellDefaults = {
        "LinenoWidth" : 4,
        "LinenoMargin" : 1,
        "AutoCompletionEnabled" : 1,
        "CallTipsEnabled" : 1,
        "WrapEnabled" : 1,
        "MaxHistoryEntries" : 100,
        "SyntaxHighlightingEnabled" : 1,
    }

    # defaults for Qt related stuff
    qtDefaults = {
        "QtDir" : "",
        "ExportQtDir" : 0,
        "DisableQt3" : 0,
        "Qt4Dir" : "",
        "ExportQt4Dir" : 0,
        "Qt4TranslationsDir" : "",
        "QtToolsPrefix3" : "", 
        "QtToolsPostfix3" : "", 
        "QtToolsPrefix4" : "", 
        "QtToolsPostfix4" : "", 
    }
    
    # defaults for corba related stuff
    corbaDefaults = {
        "omniidl" : "omniidl"
    }
    
    # defaults for the refactoring related stuff
    refactoringDefaults = {
        "Logging" : 1
    }
    
    # defaults for user related stuff
    userDefaults = {
        "Email" : "",
        "MailServer" : "",
        "Signature" : "",
        "MailServerAuthentication" : 0,
        "MailServerUser" : "",
        "MailServerPassword" : "",
    }
    
    # defaults for vcs related stuff
    vcsDefaults = {
        "AutoClose" : 0,
        "AutoSaveFiles" : 1,
        "AutoSaveProject" : 1,
        "StatusMonitorInterval" : 30,
        "SvnInterfaceGlobalOverride" : 0,
        # 0 = no override, 1 = use svn, 2 = use pysvn
    }
    
    # defaults for tasks related stuff
    tasksDefaults = {
        "TasksMarkers"       : "TO" + "DO:", 
        "TasksMarkersBugfix" : "FIX" + "ME:",
        # needed to keep it from being recognized as a task
        "TasksColour"          : QtGui.QColor(QtCore.Qt.black),
        "TasksBugfixColour"    : QtGui.QColor(QtCore.Qt.red),
        "TasksBgColour"        : QtGui.QColor(QtCore.Qt.white),
        "TasksProjectBgColour" : QtGui.QColor(QtCore.Qt.lightGray),
    }
    
    # defaults for templates related stuff
    templatesDefaults = {
        "AutoOpenGroups" : 1,
        "SingleDialog"   : 0,
        "ShowTooltip"    : 0,
        "SeparatorChar"  : "$",
    }
    
    # defaults for the printer settings
    graphicsDefaults = {
        "Font" : "SansSerif,10,-1,5,50,0,0,0,0,0"
    }
    
    # defaults for geometry
    geometryDefaults = {
        "HelpViewerGeometry" : QtCore.QByteArray(),
        "MainGeometry"       : QtCore.QByteArray(),
    }

    # if true, revert layouts to factory defaults
    resetLayout = False

def readPreferences(prefClass = Prefs):
    """
    Module function to read the preferences and transfer them into the central store.
    
    @param prefClass preferences class used as the storage area
    """
    # read the general entries
    prefClass.configured, ok = \
        prefClass.settings.value("General/Configured", QtCore.QVariant(0)).toInt()
    
    # read the entries for the variables display
    prefClass.varPrefs = {}
    for key in prefClass.varDefaults.keys():
        v = prefClass.settings.value("Variables/" + key, 
            QtCore.QVariant(unicode(prefClass.varDefaults[key])))
        v=v.toString()
        prefClass.varPrefs[key] = eval(unicode(v))

    # read the entries for the debugger
    prefClass.debuggerPrefs = {}
    for key in ["RemoteDbgEnabled", "PassiveDbgEnabled", \
                "PassiveDbgPort", "CustomPythonInterpreter", \
                "AutomaticReset", "DebugEnvironmentReplace", \
                "PythonRedirect", "PythonNoEncoding", "RubyRedirect", \
                "ConsoleDbgEnabled", "PathTranslation", "Autosave"]:
        prefClass.debuggerPrefs[key], ok = \
            prefClass.settings.value("Debugger/" + key,
                QtCore.QVariant(prefClass.debuggerDefaults[key])).toInt()
    
    for key in ["RemoteHost", "RemoteExecution", "PythonInterpreter", \
                "RubyInterpreter", "DebugClient", "DebugClientType", \
                "DebugEnvironment", "ConsoleDbgCommand", \
                "PathTranslationRemote", "PathTranslationLocal", \
                "NetworkInterface"]:
        prefClass.debuggerPrefs[key] = \
            prefClass.settings.value("Debugger/" + key,
                QtCore.QVariant(prefClass.debuggerDefaults[key])).toString()
    
    for key in ["AllowedHosts"]:
        prefClass.debuggerPrefs[key] = \
            prefClass.settings.value("Debugger/" + key,
                QtCore.QVariant(prefClass.debuggerDefaults[key])).toStringList()
    
    # read the entries for the general ui settings
    prefClass.uiPrefs = {}
    lang = \
        prefClass.settings.value("UI/Language",
            QtCore.QVariant(prefClass.uiDefaults["Language"])).toString()
    if unicode(lang) == "None" or unicode(lang) == "" or lang is None:
        prefClass.uiPrefs["Language"] = None
    else:
        prefClass.uiPrefs["Language"] = unicode(lang)
    
    vm = \
        prefClass.settings.value("UI/ViewManager",
            QtCore.QVariant(prefClass.uiDefaults["ViewManager"])).toString()
    if unicode(vm) in ConfigViewManagers:
        prefClass.uiPrefs["ViewManager"] = unicode(vm)
    else:
        prefClass.uiPrefs["ViewManager"] = prefClass.uiDefaults["ViewManager"]

    for key in ["LayoutShellEmbedded", "LayoutFileBrowserEmbedded",
                "BrowsersListFoldersFirst", "BrowsersHideNonPublic",
                "SingleApplicationMode", "TabViewManagerFilenameLength",
                "CaptionShowsFilename", "CaptionFilenameLength",
                "UseKDEDialogs", "ShowSplash", "PerformVersionCheck",
                "UseProxy", "ProxyPort", "UseIconProvider"]:
        prefClass.uiPrefs[key], ok = \
            prefClass.settings.value("UI/" + key,
                QtCore.QVariant(prefClass.uiDefaults[key])).toInt()
    for key in ["Style", "StyleSheet", "LayoutType", 
                "ProxyHost", "ProxyUser", "ProxyPassword"]:
        prefClass.uiPrefs[key] = \
            prefClass.settings.value("UI/" + key,
                QtCore.QVariant(prefClass.uiDefaults[key])).toString()

    v = prefClass.settings.value("UI/ViewProfiles")
    if v.isValid():
        prefClass.uiPrefs["ViewProfiles"] = eval(unicode(v.toString()))
        for name in ["edit", "debug"]:
            vpLength = len(prefClass.uiPrefs["ViewProfiles"][name][0])
            if vpLength < prefClass.viewProfilesLength:
                prefClass.uiPrefs["ViewProfiles"][name][0].extend(\
                    prefClass.uiDefaults["ViewProfiles"][name][0][vpLength:])
            vpLength = len(prefClass.uiPrefs["ViewProfiles"][name][2])
            if vpLength < prefClass.viewProfilesLength:
                prefClass.uiPrefs["ViewProfiles"][name][2].extend(\
                    prefClass.uiDefaults["ViewProfiles"][name][2][vpLength:])
    else:
        prefClass.uiPrefs["ViewProfiles"] = prefClass.uiDefaults["ViewProfiles"]
    
    prefClass.iconsPrefs = {}
    for key in prefClass.iconsDefaults.keys():
        dirlist = prefClass.settings.value("UI/Icons/" + key)
        if dirlist.isValid():
            prefClass.iconsPrefs[key] = dirlist.toStringList()
        else:
            prefClass.iconsPrefs[key] = prefClass.iconsDefaults[key]
    
    # read the entries for the editor settings
    prefClass.editorPrefs = {}
    for key in prefClass.editorDefaults.keys():
        if key in ["DefaultEncoding", "DefaultOpenFilter", "DefaultSaveFilter"]:
            prefClass.editorPrefs[key] = \
                prefClass.settings.value("Editor/" + key,
                    QtCore.QVariant(prefClass.editorDefaults[key])).toString()
        else:
            prefClass.editorPrefs[key], ok = \
                prefClass.settings.value("Editor/" + key,
                    QtCore.QVariant(prefClass.editorDefaults[key])).toInt()
    
    prefClass.editorColourPrefs = {}
    for key in prefClass.editorColourDefaults.keys():
        col = prefClass.settings.value("Editor/Colour/" + key)
        if col.isValid():
            prefClass.editorColourPrefs[key] = QtGui.QColor(col.toString())
        else:
            prefClass.editorColourPrefs[key] = prefClass.editorColourDefaults[key]
    
    prefClass.editorOtherFontsPrefs = {}
    for key in prefClass.editorOtherFontsDefaults.keys():
        prefClass.editorOtherFontsPrefs[key] = \
            prefClass.settings.value("Editor/Other Fonts/" + key,
                QtCore.QVariant(prefClass.editorOtherFontsDefaults[key])).toString()
    
    prefClass.editorAPI = {}
    for key in prefClass.editorAPIDefaults.keys():
        ap = prefClass.settings.value("Editor/APIs/" + key)
        if ap.isValid():
            apis = ap.toStringList()
            if len(apis) and apis[0].isEmpty():
                prefClass.editorAPI[key] = prefClass.editorAPIDefaults[key]
            else:
                prefClass.editorAPI[key] = apis
        else:
            prefClass.editorAPI[key] = prefClass.editorAPIDefaults[key]
    
    prefClass.editorLexerAssoc = {}
    prefClass.settings.beginGroup("Editor/LexerAssociations")
    keyList = prefClass.settings.childKeys()
    prefClass.settings.endGroup()
    if len(keyList) == 0:
        # build from scratch
        for key in prefClass.editorLexerAssocDefaults.keys():
            prefClass.editorLexerAssoc[key] = \
                QtCore.QString(prefClass.editorLexerAssocDefaults[key])
    else:
        for key in keyList:
            key = unicode(key)
            if prefClass.editorLexerAssocDefaults.has_key(key):
                defaultValue = prefClass.editorLexerAssocDefaults[key]
            else:
                defaultValue = QtCore.QString()
            prefClass.editorLexerAssoc[key] = \
                prefClass.settings.value("Editor/LexerAssociations/" + key,
                    QtCore.QVariant(defaultValue)).toString()
    # new default lexer associations
    for key in prefClass.editorLexerAssocDefaults.keys():
        if not prefClass.editorLexerAssoc.has_key(key):
            prefClass.editorLexerAssoc[key] = \
                QtCore.QString(prefClass.editorLexerAssocDefaults[key])
    
    prefClass.editorTypingPrefs = {}
    for key in prefClass.editorTypingDefaults.keys():
        prefClass.editorTypingPrefs[key], ok = \
            prefClass.settings.value("Editor/Typing/" + key,
                QtCore.QVariant(prefClass.editorTypingDefaults[key])).toInt()
    
    # read the entries for the project settings
    prefClass.projectPrefs = {}
    for key in prefClass.projectDefaults.keys():
        prefClass.projectPrefs[key], ok = \
            prefClass.settings.value("Project/" + key,
                QtCore.QVariant(prefClass.projectDefaults[key])).toInt()
    
    # read the entries for the project browser settings
    prefClass.projectBrowserColourPrefs = {}
    for key in prefClass.projectBrowserColourDefaults.keys():
        col = prefClass.settings.value("Project/Colour/" + key)
        if col.isValid():
            prefClass.projectBrowserColourPrefs[key] = QtGui.QColor(col.toString())
        else:
            prefClass.projectBrowserColourPrefs[key] = \
                prefClass.projectBrowserColourDefaults[key]
    
    # read the entries for the help settings
    prefClass.helpPrefs = {}
    for key in ["HelpViewerType", "SingleHelpWindow", "SaveGeometry"]:
        prefClass.helpPrefs[key], ok = \
            prefClass.settings.value("Help/" + key,
                QtCore.QVariant(prefClass.helpDefaults[key])).toInt()
    for key in ["CustomViewer", \
                "PythonDocDir", "QtDocDir", "Qt4DocDir", "PyQt4DocDir"]:
        prefClass.helpPrefs[key] = \
            prefClass.settings.value("Help/" + key,
                QtCore.QVariant(prefClass.helpDefaults[key])).toString()
    
    # read the entries for system settings
    prefClass.sysPrefs = {}
    for key in ["StringEncoding", "IOEncoding"]: 
        prefClass.sysPrefs[key] = \
            prefClass.settings.value("System/" + key, 
                QtCore.QVariant(prefClass.sysDefaults[key])).toString()
    
    # read the entries for Qt settings
    prefClass.qtPrefs = {}
    for key in ["QtDir", "Qt4Dir", "Qt4TranslationsDir", "QtToolsPrefix3", 
                "QtToolsPostfix3", "QtToolsPrefix4", "QtToolsPostfix4"]: 
        prefClass.qtPrefs[key] = \
            prefClass.settings.value("Qt/" + key, 
                QtCore.QVariant(prefClass.qtDefaults[key])).toString()
    for key in ["DisableQt3", "ExportQtDir", "ExportQt4Dir"]: 
        prefClass.qtPrefs[key], ok = \
            prefClass.settings.value("Qt/" + key, 
                QtCore.QVariant(prefClass.qtDefaults[key])).toInt()
    
    # read the entries for the display geometry
    prefClass.geometryPrefs = {}
    for key in prefClass.geometryDefaults.keys():
        v = prefClass.settings.value("Geometry/" + key)
        if v.isValid():
            prefClass.geometryPrefs[key] = v.toByteArray()
        else:
            prefClass.geometryPrefs[key] = prefClass.geometryDefaults[key]

    # read the entries for the printer settings
    prefClass.printerPrefs = {}
    for key in ["ColorMode", "FirstPageFirst", "Magnification", 
                "Orientation", "PageSize"]:
        prefClass.printerPrefs[key], ok = \
            prefClass.settings.value("Printer/" + key,
                QtCore.QVariant(prefClass.printerDefaults[key])).toInt()
    for key in ["PrinterName", "HeaderFont"]:
        prefClass.printerPrefs[key] = \
            prefClass.settings.value("Printer/" + key,
                QtCore.QVariant(prefClass.printerDefaults[key])).toString()
    
    # read the entries for the shell settings
    prefClass.shellPrefs = {}
    for key in prefClass.shellDefaults.keys():
        prefClass.shellPrefs[key], ok = \
            prefClass.settings.value("Shell/" + key,
                QtCore.QVariant(prefClass.shellDefaults[key])).toInt()
    
    # read the entries for the corba settings
    prefClass.corbaPrefs = {}
    for key in ["omniidl"]:
        prefClass.corbaPrefs[key] = \
            prefClass.settings.value("Corba/" + key,
                QtCore.QVariant(prefClass.corbaDefaults[key])).toString()
    
    # read the entries for the refactoring settings
    prefClass.refactoringPrefs = {}
    for key in prefClass.refactoringDefaults.keys():
        prefClass.refactoringPrefs[key], ok = \
            prefClass.settings.value("Refactoring/" + key,
                QtCore.QVariant(prefClass.refactoringDefaults[key])).toInt()
    
    # read the entries for the user settings
    prefClass.userPrefs = {}
    for key in prefClass.userDefaults.keys():
        if key in ["MailServerAuthentication"]:
            prefClass.userPrefs[key], ok = \
                prefClass.settings.value("User/" + key,
                    QtCore.QVariant(prefClass.userDefaults[key])).toInt()
        else:
            prefClass.userPrefs[key] = \
                prefClass.settings.value("User/" + key,
                    QtCore.QVariant(prefClass.userDefaults[key])).toString()
    
    # read the entries for the VCS settings
    prefClass.vcsPrefs = {}
    for key in prefClass.vcsDefaults.keys():
        prefClass.vcsPrefs[key], ok = \
            prefClass.settings.value("VCS/" + key,
                QtCore.QVariant(prefClass.vcsDefaults[key])).toInt()
    
    # read the entries for the tasks settings
    prefClass.tasksPrefs = {}
    for key in prefClass.tasksDefaults.keys():
        if key in ["TasksColour", "TasksBugfixColour", 
                   "TasksBgColour", "TasksProjectBgColour"]:
            col = prefClass.settings.value("Tasks/" + key)
            if col.isValid():
                prefClass.tasksPrefs[key] = QtGui.QColor(col.toString())
            else:
                prefClass.tasksPrefs[key] = prefClass.tasksDefaults[key]
        else:
            prefClass.tasksPrefs[key] = \
                prefClass.settings.value("Tasks/" + key,
                    QtCore.QVariant(prefClass.tasksDefaults[key])).toString()

    # read the entries for templates settings
    prefClass.templatesPrefs = {}
    for key in prefClass.templatesDefaults.keys():
        if key in ["SeparatorChar"]:
            prefClass.templatesPrefs[key] = \
                prefClass.settings.value("Templates/" + key,
                    QtCore.QVariant(prefClass.templatesDefaults[key])).toString()
        else:
            prefClass.templatesPrefs[key], ok = \
                prefClass.settings.value("Templates/" + key,
                    QtCore.QVariant(prefClass.templatesDefaults[key])).toInt()
    
    # read the entries for the graphics settings
    prefClass.graphicsPrefs = {}
    for key in ["Font"]:
        prefClass.graphicsPrefs[key] = \
            prefClass.settings.value("Graphics/" + key,
                QtCore.QVariant(prefClass.graphicsDefaults[key])).toString()
    
def savePreferences(prefClass = Prefs):
    """
    Module function to write the preferences from the central store.
    
    @param prefClass preferences class used as the storage area
    """
    # write the general entries
    prefClass.settings.setValue("General/Configured", 
        QtCore.QVariant(int(prefClass.configured)))
    
    # write the entries for the variables display
    for key in prefClass.varPrefs.keys():
        prefClass.settings.setValue("Variables/" + key,
            QtCore.QVariant(unicode(prefClass.varPrefs[key])))

    # write the entries for the debugger
    for key in prefClass.debuggerPrefs.keys():
        prefClass.settings.setValue("Debugger/" + key,
            QtCore.QVariant(prefClass.debuggerPrefs[key]))

    # write the entries for the general ui settings
    for key in prefClass.uiPrefs.keys():
        if key == "Language":
            if prefClass.uiPrefs["Language"] is None:
                prefClass.settings.setValue("UI/Language", QtCore.QVariant("None"))
            else:
                prefClass.settings.setValue("UI/Language", 
                    QtCore.QVariant(prefClass.uiPrefs["Language"]))
        elif key == "ViewProfiles":
            prefClass.settings.setValue("UI/" + key,
                QtCore.QVariant(unicode(prefClass.uiPrefs[key])))
        else:
            prefClass.settings.setValue("UI/" + key,
                QtCore.QVariant(prefClass.uiPrefs[key]))

    # write the entries for the icon settings
    for key in prefClass.iconsPrefs.keys():
        prefClass.settings.setValue("UI/Icons/" + key,
            QtCore.QVariant(prefClass.iconsPrefs[key]))
    
    # write the entries for the editor settings
    for key in prefClass.editorPrefs.keys():
        prefClass.settings.setValue("Editor/" + key,
            QtCore.QVariant(prefClass.editorPrefs[key]))
    
    for key in prefClass.editorColourPrefs.keys():
        prefClass.settings.setValue("Editor/Colour/" + key,
            QtCore.QVariant(prefClass.editorColourPrefs[key].name()))

    for key in prefClass.editorOtherFontsPrefs.keys():
        prefClass.settings.setValue("Editor/Other Fonts/" + key,
            QtCore.QVariant(prefClass.editorOtherFontsPrefs[key]))

    for key in prefClass.editorAPI.keys():
        prefClass.settings.setValue("Editor/APIs/" + key,
            QtCore.QVariant(prefClass.editorAPI[key]))
    
    # first remove lexer associations that no longer exist, than save the rest
    prefClass.settings.beginGroup("Editor/LexerAssociations")
    keyList = prefClass.settings.childKeys()
    prefClass.settings.endGroup()
    for key in keyList:
        key = unicode(key)
        if not prefClass.editorLexerAssoc.has_key(key):
            prefClass.settings.remove("Editor/LexerAssociations/" + key)
    for key in prefClass.editorLexerAssoc.keys():
        prefClass.settings.setValue("Editor/LexerAssociations/" + key,
            QtCore.QVariant(prefClass.editorLexerAssoc[key]))
    
    for key in prefClass.editorTypingPrefs.keys():
        prefClass.settings.setValue("Editor/Typing/" + key,
            QtCore.QVariant(prefClass.editorTypingPrefs[key]))
    
    # write the entries for the project settings
    for key in prefClass.projectPrefs.keys():
        prefClass.settings.setValue("Project/" + key,
            QtCore.QVariant(prefClass.projectPrefs[key]))
    
    # write the entries for the project browser settings
    for key in prefClass.projectBrowserColourPrefs.keys():
        prefClass.settings.setValue("Project/Colour/" + key,
            QtCore.QVariant(prefClass.projectBrowserColourPrefs[key].name()))

    # write the entries for the help settings
    for key in prefClass.helpPrefs.keys():
        prefClass.settings.setValue("Help/" + key,
            QtCore.QVariant(prefClass.helpPrefs[key]))
    
    # write the entries for the system settings
    for key in prefClass.sysPrefs.keys():
        prefClass.settings.setValue("System/" + key,
            QtCore.QVariant(prefClass.sysPrefs[key]))
    
    # write the entries for the Qt settings
    for key in prefClass.qtPrefs.keys():
        prefClass.settings.setValue("Qt/" + key,
            QtCore.QVariant(prefClass.qtPrefs[key]))
    
    # write the entries for the display geometry
    for key in prefClass.geometryPrefs.keys():
        prefClass.settings.setValue("Geometry/" + key,
            QtCore.QVariant(prefClass.geometryPrefs[key]))
    
    # write the entries for the printer settings
    for key in prefClass.printerPrefs.keys():
        prefClass.settings.setValue("Printer/" + key,
            QtCore.QVariant(prefClass.printerPrefs[key]))
    
    # write the entries for the shell settings
    for key in prefClass.shellPrefs.keys():
        prefClass.settings.setValue("Shell/" + key,
            QtCore.QVariant(prefClass.shellPrefs[key]))
    
    # write the entries for the corba settings
    for key in prefClass.corbaPrefs.keys():
        prefClass.settings.setValue("Corba/" + key,
            QtCore.QVariant(prefClass.corbaPrefs[key]))
    
    # write the entries for the refactoring settings
    for key in prefClass.refactoringPrefs.keys():
        prefClass.settings.setValue("Refactoring/" + key,
            QtCore.QVariant(prefClass.refactoringPrefs[key]))
    
    # write the entries for the user settings
    for key in prefClass.userPrefs.keys():
        prefClass.settings.setValue("User/" + key,
            QtCore.QVariant(prefClass.userPrefs[key]))
    
    # write the entries for the VCS settings
    for key in prefClass.vcsPrefs.keys():
        prefClass.settings.setValue("VCS/" + key,
            QtCore.QVariant(prefClass.vcsPrefs[key]))
    
    # write the entries for the tasks settings
    for key in prefClass.tasksPrefs.keys():
        if key in ["TasksColour", "TasksBugfixColour",
                   "TasksBgColour", "TasksProjectBgColour"]:
            prefClass.settings.setValue("Tasks/" + key,
                QtCore.QVariant(prefClass.tasksPrefs[key].name()))
        else:
            prefClass.settings.setValue("Tasks/" + key,
                QtCore.QVariant(prefClass.tasksPrefs[key]))
    
    # write the entries for the templates settings
    for key in prefClass.templatesPrefs.keys():
        prefClass.settings.setValue("Templates/" + key,
            QtCore.QVariant(prefClass.templatesPrefs[key]))
    
    # write the entries for the graphics settings
    for key in prefClass.graphicsPrefs.keys():
        prefClass.settings.setValue("Graphics/" + key,
            QtCore.QVariant(prefClass.graphicsPrefs[key]))
    
def readToolGroups(prefClass = Prefs):
    """
    Module function to read the tool groups configuration.
    
    @param prefClass preferences class used as the storage area
    @return list of tuples defing the tool groups
    """
    toolGroups = []
    groups, ok = prefClass.settings.value("Toolgroups/Groups", 
        QtCore.QVariant(0)).toInt()
    for groupIndex in range(groups):
        groupName = \
            prefClass.settings.value("Toolgroups/%02d/Name" % groupIndex).toString()
        group = [unicode(groupName), []]
        items, ok = prefClass.settings.value("Toolgroups/%02d/Items" % groupIndex, 
            QtCore.QVariant(0)).toInt()
        for ind in range(items):
            menutext = prefClass.settings.value(\
                "Toolgroups/%02d/%02d/Menutext" % (groupIndex, ind)).toString()
            icon = prefClass.settings.value(\
                "Toolgroups/%02d/%02d/Icon" % (groupIndex, ind)).toString()
            executable = prefClass.settings.value(\
                "Toolgroups/%02d/%02d/Executable" % (groupIndex, ind)).toString()
            arguments = prefClass.settings.value(\
                "Toolgroups/%02d/%02d/Arguments" % (groupIndex, ind)).toString()
            redirect = prefClass.settings.value(\
                "Toolgroups/%02d/%02d/Redirect" % (groupIndex, ind)).toString()
            
            if not menutext.isEmpty():
                if unicode(menutext) == '--':
                    tool = {
                        'menutext' : '--',
                        'icon' : '',
                        'executable' : '',
                        'arguments' : '',
                        'redirect' : 'no',
                    }
                    group[1].append(tool)
                elif not executable.isEmpty():
                    tool = {
                        'menutext' : unicode(menutext),
                        'icon' : unicode(icon),
                        'executable' : unicode(executable),
                        'arguments' : unicode(arguments),
                        'redirect' : unicode(redirect),
                    }
                    group[1].append(tool)
        toolGroups.append(group)
    currentGroup, ok = prefClass.settings.value("Toolgroups/Current Group", 
        QtCore.QVariant(-1)).toInt()
    return toolGroups, currentGroup
    
def saveToolGroups(toolGroups, currentGroup, prefClass = Prefs):
    """
    Module function to write the tool groups configuration.
    
    @param toolGroups reference to the list of tool groups
    @param currentGroup index of the currently selected tool group (integer)
    @param prefClass preferences class used as the storage area
    """
    # first step, remove all tool group entries
    prefClass.settings.remove("Toolgroups")
    
    # second step, write the tool group entries
    prefClass.settings.setValue("Toolgroups/Groups", QtCore.QVariant(len(toolGroups)))
    groupIndex = 0
    for group in toolGroups:
        prefClass.settings.setValue("Toolgroups/%02d/Name" % groupIndex,
            QtCore.QVariant(group[0]))
        prefClass.settings.setValue("Toolgroups/%02d/Items" % groupIndex,
            QtCore.QVariant(len(group[1])))
        ind = 0
        for tool in group[1]:
            prefClass.settings.setValue(\
                "Toolgroups/%02d/%02d/Menutext" % (groupIndex, ind), 
                QtCore.QVariant(tool['menutext']))
            prefClass.settings.setValue(\
                "Toolgroups/%02d/%02d/Icon" % (groupIndex, ind), 
                QtCore.QVariant(tool['icon']))
            prefClass.settings.setValue(\
                "Toolgroups/%02d/%02d/Executable" % (groupIndex, ind), 
                QtCore.QVariant(tool['executable']))
            prefClass.settings.setValue(\
                "Toolgroups/%02d/%02d/Arguments" % (groupIndex, ind), 
                QtCore.QVariant(tool['arguments']))
            prefClass.settings.setValue(\
                "Toolgroups/%02d/%02d/Redirect" % (groupIndex, ind), 
                QtCore.QVariant(tool['redirect']))
            ind += 1
        groupIndex += 1
    prefClass.settings.setValue(\
        "Toolgroups/Current Group", QtCore.QVariant(currentGroup))
    
def initPreferences():
    """
    Module function to initialize the central configuration store. 
    """
    Prefs.settings = QtCore.QSettings(QtCore.QSettings.UserScope, 
        settingsNameOrganization, settingsNameGlobal)
    if sys.platform != "win32":
        hp = QtCore.QDir.homePath()
        dn = QtCore.QDir(hp)
        dn.mkdir(".eric4")
    readPreferences(Prefs)
    
def syncPreferences(prefClass = Prefs):
    """
    Module function to sync the preferences to disk.
    
    In addition to syncing, the central configuration store is reinitialized as well.
    
    @param prefClass preferences class used as the storage area
    """
    prefClass.configured = 1
    savePreferences(prefClass)
    initPreferences()
    
def isConfigured(prefClass = Prefs):
    """
    Module function to check, if the the application has been configured.
    
    @param prefClass preferences class used as the storage area
    @return flag indicating the configured status (boolean)
    """
    return prefClass.configured
    
def initRecentSettings():
    """
    Module function to initialize the central configuration store for recently
    opened files and projects. 
    
    This function is called once upon import of the module.
    """
    Prefs.rsettings = QtCore.QSettings(QtCore.QSettings.UserScope, 
        settingsNameOrganization, settingsNameRecent)
    
def getVarFilters(prefClass = Prefs):
    """
    Module function to retrieve the variables filter settings.
    
    @param prefClass preferences class used as the storage area
    @return a tuple defing the variables filter
    """
    return (prefClass.varPrefs["LocalsFilter"], prefClass.varPrefs["GlobalsFilter"])
    
def setVarFilters(filters, prefClass = Prefs):
    """
    Module function to store the variables filter settings.
    
    @param prefClass preferences class used as the storage area
    """
    prefClass.varPrefs["LocalsFilter"], prefClass.varPrefs["GlobalsFilter"] = filters
    
def getDebugger(key, prefClass = Prefs):
    """
    Module function to retrieve the debugger settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested debugger setting
    """
    return prefClass.debuggerPrefs[key]
    
def setDebugger(key, value, prefClass = Prefs):
    """
    Module function to store the debugger settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.debuggerPrefs[key] = value

def getUILanguage(prefClass = Prefs):
    """
    Module function to retrieve the language for the user interface.
    
    @param prefClass preferences class used as the storage area
    @return the language for the UI
    """
    return prefClass.uiPrefs["Language"]
    
def setUILanguage(lang, prefClass = Prefs):
    """
    Module function to store the language for the user interface.
    
    @param lang the language
    @param prefClass preferences class used as the storage area
    """
    prefClass.uiPrefs["Language"] = lang

def getUILayout(prefClass = Prefs):
    """
    Module function to retrieve the layout for the user interface.
    
    @param prefClass preferences class used as the storage area
    @return the UI layout as a tuple of main layout, flag for
        an embedded shell and a value for an embedded file browser
    """
    layout = (prefClass.uiPrefs["LayoutType"],
              prefClass.uiPrefs["LayoutShellEmbedded"],
              prefClass.uiPrefs["LayoutFileBrowserEmbedded"])
    return layout
    
def setUILayout(layout, prefClass = Prefs):
    """
    Module function to store the layout for the user interface.
    
    @param layout the layout type
    @param prefClass preferences class used as the storage area
    """
    prefClass.uiPrefs["LayoutType"], \
    prefClass.uiPrefs["LayoutShellEmbedded"], \
    prefClass.uiPrefs["LayoutFileBrowserEmbedded"] = layout

def getViewManager(prefClass = Prefs):
    """
    Module function to retrieve the selected viewmanager type.
    
    @param prefClass preferences class used as the storage area
    @return the viewmanager type
    """
    return prefClass.uiPrefs["ViewManager"]
    
def setViewManager(vm, prefClass = Prefs):
    """
    Module function to store the selected viewmanager type.
    
    @param vm the viewmanager type
    @param prefClass preferences class used as the storage area
    """
    prefClass.uiPrefs["ViewManager"] = vm

def getUI(key, prefClass = Prefs):
    """
    Module function to retrieve the various UI settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested UI setting
    """
    return prefClass.uiPrefs[key]
    
def setUI(key, value, prefClass = Prefs):
    """
    Module function to store the various UI settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.uiPrefs[key] = value
    
def getIcons(key, prefClass = Prefs):
    """
    Module function to retrieve the various Icons settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested Icons setting
    """
    return prefClass.iconsPrefs[key]
    
def setIcons(key, value, prefClass = Prefs):
    """
    Module function to store the various Icons settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.iconsPrefs[key] = value
    
def getEditor(key, prefClass = Prefs):
    """
    Module function to retrieve the various editor settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested editor setting
    """
    return prefClass.editorPrefs[key]
    
def setEditor(key, value, prefClass = Prefs):
    """
    Module function to store the various editor settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.editorPrefs[key] = value
    
def getEditorColour(key, prefClass = Prefs):
    """
    Module function to retrieve the various editor marker colours.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested editor colour
    """
    return prefClass.editorColourPrefs[key]
    
def setEditorColour(key, value, prefClass = Prefs):
    """
    Module function to store the various editor marker colours.
    
    @param key the key of the colour to be set
    @param value the colour to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.editorColourPrefs[key] = value
    
def getEditorOtherFonts(key, prefClass = Prefs):
    """
    Module function to retrieve the various editor fonts except the lexer fonts.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested editor font (QFont)
    """
    f = QtGui.QFont()
    f.fromString(prefClass.editorOtherFontsPrefs[key])
    return f
    
def setEditorOtherFonts(key, font, prefClass = Prefs):
    """
    Module function to store the various editor fonts except the lexer fonts.
    
    @param key the key of the font to be set
    @param font the font to be set (QFont)
    @param prefClass preferences class used as the storage area
    """
    prefClass.editorOtherFontsPrefs[key] = font.toString()
    
def getEditorAPI(key, prefClass = Prefs):
    """
    Module function to retrieve the various lists of api files.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested list of api files (QStringList)
    """
    return prefClass.editorAPI[key]
    
def setEditorAPI(key, apilist, prefClass = Prefs):
    """
    Module function to store the various lists of api files.
    
    @param key the key of the api to be set
    @param apilist the list of api files (QStringList)
    @param prefClass preferences class used as the storage area
    """
    prefClass.editorAPI[key] = apilist
    
def getEditorLexerAssocs(prefClass = Prefs):
    """
    Module function to retrieve all lexer associations.
    
    @param prefClass preferences class used as the storage area
    @return a reference to the list of lexer associations
        (dictionary of strings)
    """
    return prefClass.editorLexerAssoc
    
def setEditorLexerAssocs(assocs, prefClass = Prefs):
    """
    Module function to retrieve all lexer associations.
    
    @param assocs dictionary of lexer associations to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.editorLexerAssoc = assocs.copy()
    
def getEditorLexerAssoc(filename, prefClass = Prefs):
    """
    Module function to retrieve a lexer association.
    
    @param filename filename used to determine the associated lexer language (string)
    @param prefClass preferences class used as the storage area
    @return the requested lexer language (string)
    """
    for pattern, language in prefClass.editorLexerAssoc.items():
        if fnmatch.fnmatch(filename, pattern):
            return unicode(language)
    
    return ""
    
def getEditorTyping(key, prefClass = Prefs):
    """
    Module function to retrieve the various editor typing settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested editor setting
    """
    return prefClass.editorTypingPrefs[key]
    
def setEditorTyping(key, value, prefClass = Prefs):
    """
    Module function to store the various editor typing settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.editorTypingPrefs[key] = value
    
def getPrinter(key, prefClass = Prefs):
    """
    Module function to retrieve the various printer settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested printer setting
    """
    if key in ["HeaderFont"]:
        f = QtGui.QFont()
        f.fromString(prefClass.printerPrefs[key])
        return f
    else:
        return prefClass.printerPrefs[key]

def setPrinter(key, value, prefClass = Prefs):
    """
    Module function to store the various printer settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    if key in ["HeaderFont"]:
        prefClass.printerPrefs[key] = value.toString()
    else:
        prefClass.printerPrefs[key] = value

def getShell(key, prefClass = Prefs):
    """
    Module function to retrieve the various shell settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested shell setting
    """
    return prefClass.shellPrefs[key]

def setShell(key, value, prefClass = Prefs):
    """
    Module function to store the various shell settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.shellPrefs[key] = value

def getProject(key, prefClass = Prefs):
    """
    Module function to retrieve the various project handling settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested project setting
    """
    return prefClass.projectPrefs[key]
    
def setProject(key, value, prefClass = Prefs):
    """
    Module function to store the various project handling settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.projectPrefs[key] = value
    
def getProjectBrowserColour(key, prefClass = Prefs):
    """
    Module function to retrieve the various project browser colours.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested project browser colour
    """
    return prefClass.projectBrowserColourPrefs[key]
    
def setProjectBrowserColour(key, value, prefClass = Prefs):
    """
    Module function to store the various project browser colours.
    
    @param key the key of the colour to be set
    @param value the colour to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.projectBrowserColourPrefs[key] = value
    
def getQt4DocDir(prefClass = Prefs):
    """
    Module function to retrieve the Qt4DocDir setting.
    
    @param prefClass preferences class used as the storage area
    @return the requested Qt4DocDir setting (string)
    """
    if prefClass.helpPrefs["Qt4DocDir"].isEmpty():
        return os.getenv("QT4DOCDIR", "")
    else:
        return unicode(prefClass.helpPrefs["Qt4DocDir"])
    
def getHelp(key, prefClass = Prefs):
    """
    Module function to retrieve the various help settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested help setting
    """
    return prefClass.helpPrefs[key]
    
def setHelp(key, value, prefClass = Prefs):
    """
    Module function to store the various help settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.helpPrefs[key] = value
    
def getSystem(key, prefClass = Prefs):
    """
    Module function to retrieve the various system settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested system setting
    """
    return prefClass.sysPrefs[key]
    
def setSystem(key, value, prefClass = Prefs):
    """
    Module function to store the various system settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.sysPrefs[key] = value
    
def getQtDir(prefClass = Prefs):
    """
    Module function to retrieve the QtDir setting.
    
    @param prefClass preferences class used as the storage area
    @return the requested QtDir setting (string)
    """
    if prefClass.qtPrefs["QtDir"].isEmpty():
        return os.getenv("QTDIR", "")
    else:
        return unicode(prefClass.qtPrefs["QtDir"])
    
def getQt4Dir(prefClass = Prefs):
    """
    Module function to retrieve the Qt4Dir setting.
    
    @param prefClass preferences class used as the storage area
    @return the requested Qt4Dir setting (string)
    """
    if prefClass.qtPrefs["Qt4Dir"].isEmpty():
        return os.getenv("QT4DIR", "")
    else:
        return unicode(prefClass.qtPrefs["Qt4Dir"])
    
def getQt4TranslationsDir(prefClass = Prefs):
    """
    Module function to retrieve the Qt4TranslationsDir setting.
    
    @param prefClass preferences class used as the storage area
    @return the requested Qt4TranslationsDir setting (string)
    """
    if prefClass.qtPrefs["Qt4TranslationsDir"].isEmpty():
        return os.getenv("QT4TRANSLATIONSDIR", "")
    else:
        return unicode(prefClass.qtPrefs["Qt4TranslationsDir"])
    
def getQt(key, prefClass = Prefs):
    """
    Module function to retrieve the various Qt settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested Qt setting
    """
    if key == "QtDir":
        return getQtDir(prefClass)
    elif key == "Qt4Dir":
        return getQt4Dir(prefClass)
    else:
        return prefClass.qtPrefs[key]
    
def setQt(key, value, prefClass = Prefs):
    """
    Module function to store the various Qt settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.qtPrefs[key] = value
    
def getCorba(key, prefClass = Prefs):
    """
    Module function to retrieve the various corba settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested corba setting
    """
    return prefClass.corbaPrefs[key]
    
def setCorba(key, value, prefClass = Prefs):
    """
    Module function to store the various corba settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.corbaPrefs[key] = value
    
def getRefactoring(key, prefClass = Prefs):
    """
    Module function to retrieve the various refactoring settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested refactoring setting
    """
    return prefClass.refactoringPrefs[key]
    
def setRefactoring(key, value, prefClass = Prefs):
    """
    Module function to store the various refactoring settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.refactoringPrefs[key] = value
    
def getUser(key, prefClass = Prefs):
    """
    Module function to retrieve the various user settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested user setting
    """
    return prefClass.userPrefs[key]
    
def setUser(key, value, prefClass = Prefs):
    """
    Module function to store the various user settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.userPrefs[key] = value
    
def getVCS(key, prefClass = Prefs):
    """
    Module function to retrieve the VCS related settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested user setting
    """
    return prefClass.vcsPrefs[key]
    
def setVCS(key, value, prefClass = Prefs):
    """
    Module function to store the VCS related settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.vcsPrefs[key] = value
    
def getTasks(key, prefClass = Prefs):
    """
    Module function to retrieve the Tasks related settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested user setting
    """
    return prefClass.tasksPrefs[key]
    
def setTasks(key, value, prefClass = Prefs):
    """
    Module function to store the Tasks related settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.tasksPrefs[key] = value
    
def getTemplates(key, prefClass = Prefs):
    """
    Module function to retrieve the Templates related settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested user setting
    """
    return prefClass.templatesPrefs[key]
    
def setTemplates(key, value, prefClass = Prefs):
    """
    Module function to store the Templates related settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.templatesPrefs[key] = value
    
def getGraphics(key, prefClass = Prefs):
    """
    Module function to retrieve the Graphics related settings.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested user setting
    """
    if key in ["Font"]:
        f = QtGui.QFont()
        f.fromString(prefClass.graphicsPrefs[key])
        return f
    else:
        return prefClass.graphicsPrefs[key]
    
def setGraphics(key, value, prefClass = Prefs):
    """
    Module function to store the Graphics related settings.
    
    @param key the key of the setting to be set
    @param value the value to be set
    @param prefClass preferences class used as the storage area
    """
    prefClass.graphicsPrefs[key] = value
    
def getGeometry(key, prefClass = Prefs):
    """
    Module function to retrieve the display geometry.
    
    @param key the key of the value to get
    @param prefClass preferences class used as the storage area
    @return the requested geometry setting
    """
    return prefClass.geometryPrefs[key]

def setGeometry(key, value, prefClass = Prefs):
    """
    Module function to store the display geometry.
    
    @param key the key of the setting to be set
    @param value the geometry to be set
    @param prefClass preferences class used as the storage area
    """
    if prefClass.resetLayout:
        prefClass.geometryPrefs[key] = prefClass.geometryDefaults[key]
    else:
        prefClass.geometryPrefs[key] = value

def resetLayout(prefClass = Prefs):
    """
    Module function to set a flag not storing the current layout.
    
    @param prefClass preferences class used as the storage area
    """
    prefClass.resetLayout = True

def shouldResetLayout(prefClass = Prefs):
    """
    Module function to indicate a reset of the layout.
    
    @param prefClass preferences class used as the storage area
    @return flag indicating a reset of the layout (boolean)
    """
    return prefClass.resetLayout
    
def saveResetLayout(prefClass = Prefs):
    """
    Module function to save the reset layout.
    """
    if prefClass.resetLayout:
        for key in prefClass.geometryDefaults.keys():
            prefClass.geometryPrefs[key] = prefClass.geometryDefaults[key]
    
from Shortcuts import readShortcuts, saveShortcuts, exportShortcuts, importShortcuts

initPreferences()
initRecentSettings()
