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

# Copyright (c) 2002, 2003 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 eric3 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

from qt import *
from qtext import QextScintilla

from ViewManager.Config import ConfigViewManagers

class Prefs:
    """
    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,
        "CustomPythonInterpreter" : 0,
        "PythonInterpreter" : "",
        "DebugClientType" : 1,      # this coresponds with the radio button id
        "DebugClient" : ""
    }
        
    uiDefaults = {
        "Language" : "None",
        "ViewManager" : "tabview",
        "Layout" : 3,
    }
        
    # defaults for the editor settings
    editorDefaults = {
        "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,
        "PythonBadIndentation" : 1,
        "PythonFoldComment" : 1,
        "PythonFoldString" : 1,
        "CppFoldComment" : 1,
        "CppFoldPreprocessor" : 0,
        "CppFoldAtElse" : 0,
        "HtmlFoldPreprocessor" : 0,
        "HtmlCaseSensitiveTags" : 0,
        "AutoIndentation" : 1,
        "BraceHighlighting" : 1,
        "CreateBackupFile" : 0,
        "AutoCompletionEnabled" : 0,
        "AutoCompletionCaseSensitivity" : 1,
        "AutoCompletionReplaceWord" : 0,
        "AutoCompletionShowSingle" : 0,
        "AutoCompletionSource" : QextScintilla.AcsDocument,
        "AutoCompletionThreshold" : 2,
        "CallTipsEnabled" : 0,
        "CallTipsVisible" : -1
    }
    if sys.platform == "win32":
        editorDefaults["EOLMode"] = QextScintilla.EolWindows
    else:
        editorDefaults["EOLMode"] = QextScintilla.EolUnix
    
    editorColourDefaults = {
        "CurrentMarker" : Qt.yellow,
        "ErrorMarker" : Qt.red,
        "MatchingBrace" : Qt.blue,
        "NonmatchingBrace" : Qt.red,
        "CallTipsBackground" : Qt.white
    }
    
    editorOtherFontsDefaults = {
        "MarginsFont" : "Helvetica,12,-1,5,50,0,0,0,0,0"
    }
    
    editorAPIDefaults = {
        "Python" : QStringList(),
        "C++" : QStringList(),
        "C#" : QStringList(),
        "IDL" : QStringList(),
        "Java" : QStringList(),
        "JavaScript" : QStringList()
    }
    # the following languages are only supported for QScintilla > 1.0
    try:
        from qtext import QextScintillaLexerHTML
        editorAPIDefaults["HTML"] = QStringList()
    except ImportError:
        pass
    try:
        from qtext import QextScintillaLexerSQL
        editorAPIDefaults["SQL"] = QStringList()
    except ImportError:
        pass
    
    # defaults for the printer settings
    printerDefaults = {
        "PrinterName" : "",
        "ColorMode" : 1,
        "FirstPageFirst" : 1,
        "Magnification" : -3,
        "HeaderFont" : "Times,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,
        "XMLProjectFile" : 1
    }
    
    # defaults for the help settings
    helpDefaults = {
        "UseQtAssistant" : 0,
        "Webbrowser" : ""
    }
    
    # defaults for system settings
    sysDefaults = {
        "StringEncoding" : "latin-1"
    }
    
    # defaults for the shell settings
    shellDefaults = {
        "Font" : "Courier,12,-1,5,50,0,0,0,0,0"
    }

    # defaults for Qt related stuff
    qtDefaults = {
        "QtDir" : "",
        "ExportQtDir" : 0
    }
    
    # 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" : ""
    }
    
    # defaults for geometry
    geometryDefaults = {
        "MainGeometry" : [0,0,0,0],
        "MainSplitter0" : [0,0,0,0,0],
        "MainSplitter1" : [0,0,0,0,0,0,0]
    }

    # defaults for dock windows
    dockDefaults = {
        "MainDockLayout0" : "",
        "MainDockLayout1" : ""
    }

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

def readPreferences(prefClass = Prefs):
    """
    Module function to read the preferences and transfer them into the central store.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
    """
    # read the entries for the variables display
    prefClass.varPrefs = {}
    for key in prefClass.varDefaults.keys():
        v, ok = prefClass.settings.readEntry("/eric3/Variables/" + key)
        if ok:
            prefClass.varPrefs[key] = eval(str(v))
        else:
            prefClass.varPrefs[key] = prefClass.varDefaults[key]

    # read the entries for the debugger
    prefClass.debuggerPrefs = {}
    for key in "RemoteDbgEnabled", "PassiveDbgEnabled", \
                "PassiveDbgPort", "CustomPythonInterpreter", \
                "DebugClientType", "AutomaticReset":
        prefClass.debuggerPrefs[key], ok = \
            prefClass.settings.readNumEntry("/eric3/Debugger/" + key,
                prefClass.debuggerDefaults[key])
                
    for key in "RemoteHost", "RemoteExecution", "PythonInterpreter", \
                "DebugClient":
        prefClass.debuggerPrefs[key], ok = \
            prefClass.settings.readEntry("/eric3/Debugger/" + key,
                prefClass.debuggerDefaults[key])
    
    # read the entries for the general ui settings
    prefClass.uiPrefs = {}
    lang, ok = \
        prefClass.settings.readEntry("/eric3/UI/Language",
            prefClass.uiDefaults["Language"])
    if str(lang) == "None" or str(lang) == "" or lang is None:
        prefClass.uiPrefs["Language"] = None
    else:
        prefClass.uiPrefs["Language"] = str(lang)
        
    vm, ok = \
        prefClass.settings.readEntry("/eric3/UI/ViewManager",
            prefClass.uiDefaults["ViewManager"])
    if str(vm) in ConfigViewManagers:
        prefClass.uiPrefs["ViewManager"] = str(vm)
    else:
        prefClass.uiPrefs["ViewManager"] = prefClass.uiDefaults["ViewManager"]

    for key in ["Layout"]:
        prefClass.uiPrefs[key], ok = \
            prefClass.settings.readNumEntry("/eric3/UI/" + key,
                prefClass.uiDefaults[key])
            
    # read the entries for the editor settings
    prefClass.editorPrefs = {}
    for key in prefClass.editorDefaults.keys():
        prefClass.editorPrefs[key], ok = \
            prefClass.settings.readNumEntry("/eric3/Editor/" + key,
                prefClass.editorDefaults[key])
    
    prefClass.editorColourPrefs = {}
    for key in prefClass.editorColourDefaults.keys():
        col, ok = prefClass.settings.readEntry("/eric3/Editor/Colour/" + key)
        if ok:
            prefClass.editorColourPrefs[key] = QColor(col)
        else:
            prefClass.editorColourPrefs[key] = prefClass.editorColourDefaults[key]
            
    prefClass.editorOtherFontsPrefs = {}
    for key in prefClass.editorOtherFontsDefaults.keys():
        prefClass.editorOtherFontsPrefs[key], ok = \
            prefClass.settings.readEntry("/eric3/Editor/Other Fonts/" + key,
                prefClass.editorOtherFontsDefaults[key])
                
    prefClass.editorAPI = {}
    for key in prefClass.editorAPIDefaults.keys():
        ap, ok = prefClass.settings.readListEntry("/eric3/Editor/APIs/" + key)
        if ok:
            prefClass.editorAPI[key] = ap
        else:
            prefClass.editorAPI[key] = prefClass.editorAPIDefaults[key]
        
    # read the entries for the project settings
    prefClass.projectPrefs = {}
    for key in prefClass.projectDefaults.keys():
        prefClass.projectPrefs[key], ok = \
            prefClass.settings.readNumEntry("/eric3/Project/" + key,
                prefClass.projectDefaults[key])
    
    # read the entries for the help settings
    prefClass.helpPrefs = {}
    for key in ["UseQtAssistant"]:
        prefClass.helpPrefs[key], ok = \
            prefClass.settings.readNumEntry("/eric3/Help/" + key,
                prefClass.helpDefaults[key])
    for key in ["Webbrowser"]:
        prefClass.helpPrefs[key], ok = \
            prefClass.settings.readEntry("/eric3/Help/" + key,
                prefClass.helpDefaults[key])
    
    # read the entries for system settings
    prefClass.sysPrefs = {}
    prefClass.sysPrefs["StringEncoding"], ok = \
        prefClass.settings.readEntry("/eric3/System/StringEncoding",
            prefClass.sysDefaults["StringEncoding"])
            
    # read the entries for Qt settings
    prefClass.qtPrefs = {}
    prefClass.qtPrefs["QtDir"], ok = \
        prefClass.settings.readEntry("/eric3/Qt/QtDir",
            prefClass.qtDefaults["QtDir"])
    prefClass.qtPrefs["ExportQtDir"], ok = \
        prefClass.settings.readNumEntry("/eric3/Qt/ExportQtDir",
            prefClass.qtDefaults["ExportQtDir"])
            
    # read the entries for the display geometry
    prefClass.geometryPrefs = {}
    for key in prefClass.geometryDefaults.keys():
        v, ok = prefClass.settings.readEntry("/eric3/Geometry/" + key)
        if ok:
            prefClass.geometryPrefs[key] = eval(str(v))
        else:
            prefClass.geometryPrefs[key] = prefClass.geometryDefaults[key]

    # read the entries for the dock window layout
    prefClass.dockPrefs = {}
    for key in prefClass.dockDefaults.keys():
        v, ok = prefClass.settings.readEntry("/eric3/Docks/" + key)
        if ok:
            prefClass.dockPrefs[key] = str(v)
        else:
            prefClass.dockPrefs[key] = prefClass.dockDefaults[key]
        
    # read the entries for the printer settings
    prefClass.printerPrefs = {}
    for key in ["ColorMode", "FirstPageFirst", "Magnification"]:
        prefClass.printerPrefs[key], ok = \
            prefClass.settings.readNumEntry("/eric3/Printer/" + key,
                prefClass.printerDefaults[key])
    for key in ["PrinterName", "HeaderFont"]:
        prefClass.printerPrefs[key], ok = \
            prefClass.settings.readEntry("/eric3/Printer/" + key,
                prefClass.printerDefaults[key])
                
    # read the entries for the shell settings
    prefClass.shellPrefs = {}
    for key in ["Font"]:
        prefClass.shellPrefs[key], ok = \
            prefClass.settings.readEntry("/eric3/Shell/" + key,
                prefClass.shellDefaults[key])
                
    # read the entries for the corba settings
    prefClass.corbaPrefs = {}
    for key in ["omniidl"]:
        prefClass.corbaPrefs[key], ok = \
            prefClass.settings.readEntry("/eric3/Corba/" + key,
                prefClass.corbaDefaults[key])
                
    # read the entries for the refactoring settings
    prefClass.refactoringPrefs = {}
    for key in prefClass.refactoringDefaults.keys():
        prefClass.refactoringPrefs[key], ok = \
            prefClass.settings.readNumEntry("/eric3/Refactoring/" + key,
                prefClass.refactoringDefaults[key])
                
    # read the entries for the user settings
    prefClass.userPrefs = {}
    for key in prefClass.userDefaults.keys():
        prefClass.userPrefs[key], ok = \
            prefClass.settings.readEntry("/eric3/User/" + key,
                prefClass.userDefaults[key])
    
def savePreferences(prefClass = Prefs):
    """
    Module function to write the preferences from the central store.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
    """
    # write the entries for the variables display
    for key in prefClass.varPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Variables/" + key,
            str(prefClass.varPrefs[key]))

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

    # write the entries for the general ui settings
    if prefClass.uiPrefs["Language"] is None:
        prefClass.settings.writeEntry("/eric3/UI/Language", "None")
    else:
        prefClass.settings.writeEntry("/eric3/UI/Language", prefClass.uiPrefs["Language"])
    prefClass.settings.writeEntry("/eric3/UI/ViewManager", prefClass.uiPrefs["ViewManager"])
    prefClass.settings.writeEntry("/eric3/UI/Layout", prefClass.uiPrefs["Layout"])

    # write the entries for the editor settings
    for key in prefClass.editorPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Editor/" + key,
            prefClass.editorPrefs[key])
            
    for key in prefClass.editorColourDefaults.keys():
        prefClass.settings.writeEntry("/eric3/Editor/Colour/" + key,
            prefClass.editorColourPrefs[key].name())

    for key in prefClass.editorOtherFontsDefaults.keys():
        prefClass.settings.writeEntry("/eric3/Editor/Other Fonts/" + key,
            prefClass.editorOtherFontsPrefs[key])

    for key in prefClass.editorAPI.keys():
        prefClass.settings.writeEntry("/eric3/Editor/APIs/" + key,
            prefClass.editorAPI[key])
            
    # write the entries for the project settings
    for key in prefClass.projectPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Project/" + key,
            prefClass.projectPrefs[key])
            
    # write the entries for the help settings
    for key in prefClass.helpPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Help/" + key,
            prefClass.helpPrefs[key])
            
    # write the entries for the system settings
    prefClass.settings.writeEntry("/eric3/System/StringEncoding",
        prefClass.sysPrefs["StringEncoding"])
        
    # write the entries for the Qt settings
    for key in prefClass.qtPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Qt/" + key,
            prefClass.qtPrefs[key])
        
    # write the entries for the display geometry
    for key in prefClass.geometryPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Geometry/" + key,
            str(prefClass.geometryPrefs[key]))
        
    # write the entries for the dock layout
    for key in prefClass.dockPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Docks/" + key,
            str(prefClass.dockPrefs[key]))
        
    # write the entries for the printer settings
    for key in prefClass.printerPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Printer/" + key,
                prefClass.printerPrefs[key])
        
    # write the entries for the shell settings
    for key in prefClass.shellPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Shell/" + key,
                prefClass.shellPrefs[key])
                
    # write the entries for the corba settings
    for key in prefClass.corbaPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Corba/" + key,
                prefClass.corbaPrefs[key])
        
    # write the entries for the refactoring settings
    for key in prefClass.refactoringPrefs.keys():
        prefClass.settings.writeEntry("/eric3/Refactoring/" + key,
                prefClass.refactoringPrefs[key])
                
    # write the entries for the user settings
    for key in prefClass.userPrefs.keys():
        prefClass.settings.writeEntry("/eric3/User/" + key,
                prefClass.userPrefs[key])
        
def readToolbarSettings(mw, tbs, prefClass = Prefs):
    """
    Module function to read the toolbar settings from the central store.
    
    In addition to reading and storing the values, the toolbars are
    set accordingly.
    
    Arguments
    
        mw -- reference to the main window (QMainWindow)
        
        tbs -- list of tuples defining the different toolbars
        
        prefClass -- preferences class used as the storage area
    """
    for ind, (dummy, tb) in tbs.items():
        hidden, ok = prefClass.settings.readNumEntry("/eric3/Toolbars/%d/hidden" % ind, 0)
        dock, ok = prefClass.settings.readNumEntry("/eric3/Toolbars/%d/dockarea" % ind, Qt.DockTop)
        index, ok = prefClass.settings.readNumEntry("/eric3/Toolbars/%d/index" % ind, ind)
        nl, ok = prefClass.settings.readNumEntry("/eric3/Toolbars/%d/nl" % ind, 0)
        eo, ok = prefClass.settings.readNumEntry("/eric3/Toolbars/%d/extraOffset" % ind, 0)

        mw.moveDockWindow(tb, dock, nl, index, eo)
        if hidden:
            tb.hide()
        else:
            tb.show()
        
def saveToolbarSettings(mw, tbs, prefClass = Prefs):
    """
    Module function to write the toolbar settings to the central store.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
    """
    for ind, (text, tb) in tbs.items():
        ok, dock, index, nl, eo = mw.getLocation(tb)
        prefClass.settings.writeEntry("/eric3/Toolbars/%d/hidden" % ind, tb.isHidden())
        prefClass.settings.writeEntry("/eric3/Toolbars/%d/text" % ind, text)
        if ok:
            prefClass.settings.writeEntry("/eric3/Toolbars/%d/dockarea" % ind, dock)
            prefClass.settings.writeEntry("/eric3/Toolbars/%d/index" % ind, index)
            prefClass.settings.writeEntry("/eric3/Toolbars/%d/nl" % ind, nl)
            prefClass.settings.writeEntry("/eric3/Toolbars/%d/extraOffset" % ind, eo)
        
def readToolsMenu(prefClass = Prefs):
    """
    Module function to read the tools menu configuration.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
        
    Returns
    
        list of tuples defing the tools menu entries
    """
    toollist = []
    items, ok = prefClass.settings.readNumEntry("/eric3/Toolsmenu/Items", 0)
    for ind in range(items):
        menutext, ok1 = prefClass.settings.readEntry("/eric3/Toolsmenu/%d/Menutext" % ind)
        executable, ok2 = prefClass.settings.readEntry("/eric3/Toolsmenu/%d/Executable" % ind)
        arguments, ok3 = prefClass.settings.readEntry("/eric3/Toolsmenu/%d/Arguments" % ind)
        redirect, ok4 = prefClass.settings.readNumEntry("/eric3/Toolsmenu/%d/Redirect" % ind, 0)
        
        if ok1 and ok2 and ok3:
            tool = (str(menutext), str(executable), str(arguments), redirect)
            toollist.append(tool)
            
    return toollist
    
def saveToolsMenu(toollist, prefClass = Prefs):
    """
    Module function to write the tools menu configuration.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
    """
    # first step, remove all tool menu entries
    items, ok = prefClass.settings.readNumEntry("/eric3/Toolsmenu/Items", 0)
    for ind in range(items):
        prefClass.settings.removeEntry("/eric3/Toolsmenu/%d/Menutext" % ind)
        prefClass.settings.removeEntry("/eric3/Toolsmenu/%d/Executable" % ind)
        prefClass.settings.removeEntry("/eric3/Toolsmenu/%d/Arguments" % ind)
        prefClass.settings.removeEntry("/eric3/Toolsmenu/%d/Redirect" % ind)
        
    # second step, write the menu entries
    prefClass.settings.writeEntry("/eric3/Toolsmenu/Items", len(toollist))
    ind = 0
    for tool in toollist:
        prefClass.settings.writeEntry("/eric3/Toolsmenu/%d/Menutext" % ind, tool[0])
        prefClass.settings.writeEntry("/eric3/Toolsmenu/%d/Executable" % ind, tool[1])
        prefClass.settings.writeEntry("/eric3/Toolsmenu/%d/Arguments" % ind, tool[2])
        prefClass.settings.writeEntry("/eric3/Toolsmenu/%d/Redirect" % ind, tool[3])
        ind += 1
    
def readShortcuts(ui, prefClass = Prefs):
    """
    Module function to read the keyboard shortcuts for the defined QActions.
    
    Arguments
    
        ui -- reference to the main widget (UI.UserInterface)
        
        prefClass -- preferences class used as the storage area
    """
    for act in ui.getProject().getActions():
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/Project/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getActions():
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/General/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getDebugger().getActions():
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/Debug/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getWizards().getActions():
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/Wizards/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getViewManager().getActions('edit'):
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/Edit/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getViewManager().getActions('file'):
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/File/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getViewManager().getActions('search'):
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/Search/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getViewManager().getActions('view'):
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/View/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getViewManager().getActions('macro'):
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/Macro/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    for act in ui.getViewManager().getActions('bookmark'):
        accel, ok = prefClass.settings.readEntry(\
            QString("/eric3/Shortcuts/Bookmarks/%1").arg(act.text()))
        if ok:
            act.setAccel(QKeySequence(accel))
            
    actions = ui.getViewManager().getActions('window')
    if actions:
        for act in actions:
            accel, ok = prefClass.settings.readEntry(\
                QString("/eric3/Shortcuts/Window/%1").arg(act.text()))
            if ok:
                act.setAccel(QKeySequence(accel))
                
    ref = ui.getRefactoring()
    if ref is not None:
        actions = ref.getActions()
        for act in actions:
            accel, ok = prefClass.settings.readEntry(\
                QString("/eric3/Shortcuts/Refactoring/%1").arg(act.text()))
            if ok:
                act.setAccel(QKeySequence(accel))
    
def saveShortcuts(prefClass = Prefs):
    """
    Module function to write the keyboard shortcuts for the defined QActions.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
    """
    ui = qApp.mainWidget()
    
    # step 1: clear all previously saved shortcuts
    subkeyList = prefClass.settings.subkeyList("/eric3/Shortcuts")
    for subkey in subkeyList:
        entryList = prefClass.settings.entryList(QString("/eric3/Shortcuts/%1").arg(subkey))
        for entry in entryList:
            prefClass.settings.removeEntry(\
                QString("/eric3/Shortcuts/%1/%2").arg(subkey).arg(entry))
                
    # step 2: save the various shortcuts
    for act in ui.getProject().getActions():
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/Project/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getActions():
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/General/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getDebugger().getActions():
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/Debug/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getWizards().getActions():
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/Wizards/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getViewManager().getActions('edit'):
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/Edit/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getViewManager().getActions('file'):
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/File/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getViewManager().getActions('search'):
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/Search/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getViewManager().getActions('view'):
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/View/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getViewManager().getActions('macro'):
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/Macro/%1").arg(act.text()), QString(act.accel()))
        
    for act in ui.getViewManager().getActions('bookmark'):
        prefClass.settings.writeEntry(\
            QString("/eric3/Shortcuts/Bookmarks/%1").arg(act.text()), QString(act.accel()))
        
    actions = ui.getViewManager().getActions('window')
    if actions:
        for act in actions:
            prefClass.settings.writeEntry(\
                QString("/eric3/Shortcuts/Window/%1").arg(act.text()), QString(act.accel()))
                
    ref = ui.getRefactoring()
    if ref is not None:
        actions = ref.getActions()
        for act in actions:
            prefClass.settings.writeEntry(\
                QString("/eric3/Shortcuts/Refactoring/%1").arg(act.text()), QString(act.accel()))
    
def initPreferences():
    """
    Module function to initialize the central configuration store. 
    
    This function is called once upon import of the module.
    """
    Prefs.settings = QSettings()
    if sys.platform == "win32":
        Prefs.settings.insertSearchPath(QSettings.Windows, "/Eric")
    else:
        hp = QDir.homeDirPath()
        dn = QDir(hp)
        dn.mkdir(".eric3")
        Prefs.settings.insertSearchPath(QSettings.Unix,
            hp.append("/").append(".eric3"))
    readPreferences(Prefs)
    
def syncPreferences():
    """
    Module function to sync the preferences to disk.
    
    In addition to synching, the central configuration store is reinitialized as well.
    """
    savePreferences(Prefs)
    initPreferences()
    
def getConfigDir():
    """
    Module function to get the name of the directory storing the config data.
    
    Returns
    
        directory name of the config dir (string)
    """
    if sys.platform == "win32":
        cdn = "_eric3"
    else:
        cdn = ".eric3"
        
    hp = QDir.homeDirPath()
    dn = QDir(hp)
    dn.mkdir(cdn)
    hp.append("/").append(cdn)
    return str(QDir.convertSeparators(hp))
    
def getVarFilters(prefClass = Prefs):
    """
    Module function to retrieve the variables filter settings.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
        
    Returns
    
        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.
    
    Arguments
    
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested debugger setting
    """
    return prefClass.debuggerPrefs[key]
    
def setDebugger(key, value, prefClass = Prefs):
    """
    Module function to store the debugger settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        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.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the language for the UI
    """
    return prefClass.uiPrefs["Language"]
    
def setUILanguage(lang, prefClass = Prefs):
    """
    Module function to store the language for the user interface.
    
    Arguments
    
        lang -- the language
        
        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.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the UI layout
    """
    return prefClass.uiPrefs["Layout"]
    
def setUILayout(layout, prefClass = Prefs):
    """
    Module function to store the layout for the user interface.
    
    Arguments
    
        layout -- the layout type
        
        prefClass -- preferences class used as the storage area
    """
    prefClass.uiPrefs["Layout"] = layout

def getViewManager(prefClass = Prefs):
    """
    Module function to retrieve the selected viewmanager type.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the viewmanager type
    """
    return prefClass.uiPrefs["ViewManager"]
    
def setViewManager(vm, prefClass = Prefs):
    """
    Module function to store the selected viewmanager type.
    
    Arguments
    
        vm -- the viewmanager type
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested UI setting
    """
    return prefClass.uiPrefs[key]
    
def setUI(key, value, prefClass = Prefs):
    """
    Module function to store the various UI settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        prefClass -- preferences class used as the storage area
    """
    prefClass.uiPrefs[key] = value
    
def getEditor(key, prefClass = Prefs):
    """
    Module function to retrieve the various editor settings.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested editor setting
    """
    return prefClass.editorPrefs[key]
    
def setEditor(key, value, prefClass = Prefs):
    """
    Module function to store the various editor settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested editor colour
    """
    return prefClass.editorColourPrefs[key]
    
def setEditorColour(key, value, prefClass = Prefs):
    """
    Module function to store the various editor marker colours.
    
    Arguments
    
        key -- the key of the colour to be set
        
        value -- the colour to be set
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested editor font (QFont)
    """
    f = 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.
    
    Arguments
    
        key -- the key of the font to be set
        
        font -- the font to be set (QFont)
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        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.
    
    Arguments
    
        key -- the key of the font to be set
        
        apilist -- the list of api files (QStringList)
        
        prefClass -- preferences class used as the storage area
    """
    prefClass.editorAPI[key] = apilist
    
def getPrinter(key, prefClass = Prefs):
    """
    Module function to retrieve the various printer settings.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested printer setting
    """
    if key in ["HeaderFont"]:
        f = 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.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested shell setting
    """
    if key in ["Font"]:
        f = QFont()
        f.fromString(prefClass.shellPrefs[key])
        return f
    else:
        return prefClass.shellPrefs[key]

def setShell(key, value, prefClass = Prefs):
    """
    Module function to store the various shell settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        prefClass -- preferences class used as the storage area
    """
    if key in ["Font"]:
        prefClass.shellPrefs[key] = value.toString()
    else:
        prefClass.shellPrefs[key] = value

def getProject(key, prefClass = Prefs):
    """
    Module function to retrieve the various project handling settings.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested project setting
    """
    return prefClass.projectPrefs[key]
    
def setProject(key, value, prefClass = Prefs):
    """
    Module function to store the various project handling settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        prefClass -- preferences class used as the storage area
    """
    prefClass.projectPrefs[key] = value
    
def getHelp(key, prefClass = Prefs):
    """
    Module function to retrieve the various help settings.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested help setting
    """
    return prefClass.helpPrefs[key]
    
def setHelp(key, value, prefClass = Prefs):
    """
    Module function to store the various help settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested system setting
    """
    return prefClass.sysPrefs[key]
    
def setSystem(key, value, prefClass = Prefs):
    """
    Module function to store the various system settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        prefClass -- preferences class used as the storage area
    """
    prefClass.sysPrefs[key] = value
    
def getQtDir(prefClass = Prefs):
    """
    Module function to retrieve the QtDir setting.
    
    Arguments
    
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested QtDir setting (string)
    """
    if prefClass.qtPrefs["QtDir"].isEmpty():
        return os.getenv("QTDIR")
    else:
        return str(prefClass.qtPrefs["QtDir"])
    
def getQt(key, prefClass = Prefs):
    """
    Module function to retrieve the various Qt settings.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested Qt setting
    """
    if key == "QtDir":
        return getQtDir(prefClass)
    else:
        return prefClass.qtPrefs[key]
    
def setQt(key, value, prefClass = Prefs):
    """
    Module function to store the various Qt settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested corba setting
    """
    return prefClass.corbaPrefs[key]
    
def setCorba(key, value, prefClass = Prefs):
    """
    Module function to store the various corba settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested refactoring setting
    """
    return prefClass.refactoringPrefs[key]
    
def setRefactoring(key, value, prefClass = Prefs):
    """
    Module function to store the various refactoring settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        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.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested user setting
    """
    return prefClass.userPrefs[key]
    
def setUser(key, value, prefClass = Prefs):
    """
    Module function to store the various user settings.
    
    Arguments
    
        key -- the key of the setting to be set
        
        value -- the value to be set
        
        prefClass -- preferences class used as the storage area
    """
    prefClass.userPrefs[key] = value
    
def getGeometry(key, prefClass = Prefs):
    """
    Module function to retrieve the display geometry.
    
    Arguments
    
        key -- the key of the value to get
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        the requested geometry setting
    """
    return prefClass.geometryPrefs[key]

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

def getMainDockLayout(mw, which, prefClass = Prefs):
    """
    Module function to retrieve the layout of the dock windows.
    
    Arguments
    
        mw -- reference to the main window (QMainWindow)
        
        which -- basic type of the dock layout (0 or 1)
        
        prefClass -- preferences class used as the storage area
        
    Returns
    
        flag indicating success
    """
    s = QString(prefClass.dockPrefs["MainDockLayout%d" % which])
    if s.isEmpty():
        return 0
    ts = QTextStream(s, IO_ReadOnly)
    ts >> mw
    return 1

def setMainDockLayout(mw, which, prefClass = Prefs):
    """
    Module function to store the layout of the dock windows.
    
    Arguments
    
        mw -- reference to the main window (QMainWindow)
        
        which -- basic type of the dock layout (0 or 1)
        
        prefClass -- preferences class used as the storage area
    """
    key = "MainDockLayout%d" % which
    if prefClass.resetLayout:
        s = QString(prefClass.dockDefaults[key])
    else:
        s = QString()
        ts = QTextStream(s, IO_WriteOnly)
        ts << mw
    prefClass.dockPrefs[key] = str(s)

def resetLayout(which, prefClass = Prefs):
    """
    Module function to set a flag not storing the current layout.
    """
    prefClass.resetLayout = 1

initPreferences()
