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

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

"""
Module implementing a dialog for the configuration of eric3.
"""

import os, sys, glob

from qt import *
from qtext import QextScintilla

from KdeQt import KQFileDialog, KQColorDialog, KQFontDialog

from ViewManager.Config import ConfigViewManagersDispStrings, ConfigViewManagers
import Preferences
import Utilities
from ConfigurationForm import ConfigurationForm
from PreferencesLexer import PreferencesLexer
from IconsPreviewDialog import IconsPreviewDialog
import UI.PixmapCache

from eric3config import getConfig

class ConfigurationDialog(ConfigurationForm):
    """
    Class implementing a dialog for the configuration of eric3.
    """
    def __init__(self,parent = None,name = None,modal = 0,fl = 0):
        """
        Constructor
        
        @param parent The parent widget of this dialog. (QWidget)
        @param name The name of this dialog. (QString)
        @param modal Flag indicating a modal dialog. (boolean)
        @param fl The window flags.
        """
        ConfigurationForm.__init__(self,parent,name,modal,fl)
        
        self.configList.header().hide()
        self.configList.setColumnWidthMode(1,QListView.Manual)
        self.configList.setColumnWidth(1,0)
        
        # generate the list entries
        
        # editor pages
        itm = QListViewItem(self.configList, self.trUtf8("Editor"), "")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-editor.png"))
        
        sitm = QListViewItem(itm, self.trUtf8("Highlighting Styles"), "editorSourcePage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-highlighting-styles.png"))
        sitm = QListViewItem(itm, self.trUtf8("Highlighter Association"), "editorHighlighterPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-highlighter-association.png"))
        sitm = QListViewItem(itm, self.trUtf8("General"), "editorGeneralPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-general.png"))
        sitm = QListViewItem(itm, self.trUtf8("Style"), "editorStylePage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-styles.png"))
        sitm = QListViewItem(itm, self.trUtf8("Colours"), "editorColoursPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-colours.png"))
        sitm = QListViewItem(itm, self.trUtf8("Properties"), "editorPropertiesPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-properties.png"))
        sitm = QListViewItem(itm, self.trUtf8("APIs"), "editorAPIsPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-api.png"))
        sitm = QListViewItem(itm, self.trUtf8("Autocompletion"), 
            "editorAutocompletionPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-autocompletion.png"))
        sitm = QListViewItem(itm, self.trUtf8("Calltips"), 
            "editorCalltipsPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-calltips.png"))
        
        itm.setOpen(1)
        
        # debugger pages
        itm = QListViewItem(self.configList, self.trUtf8("Debugger"), "")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-debugger.png"))
        
        sitm = QListViewItem(itm, self.trUtf8("General"), "debuggerGeneralPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-debugger.png"))
        sitm = QListViewItem(itm, self.trUtf8("Python"), "debuggerPythonPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-pyDebugger.png"))
        sitm = QListViewItem(itm, self.trUtf8("Ruby"), "debuggerRubyPage")
        sitm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-rbDebugger.png"))
        
        itm.setOpen(1)
        
        # the other pages
        itm = QListViewItem(self.configList, self.trUtf8("Printer"), "printerPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-printer.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Project"), "projectPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-project.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Interface"), "interfacePage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-interface.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Viewmanager"), "viewmanagerPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-viewmanager.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Icons"), "iconsPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-icons.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Help"), "helpPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-help.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Qt"), "qtPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-qtlogo.png"))
        itm = QListViewItem(self.configList, self.trUtf8("CORBA"), "corbaPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-orbit.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Shell"), "pythonPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-python.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Refactoring"), "refactoringPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-refactoring.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Email"), "emailPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-mail_generic.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Application"), "applicationPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-application.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Version Control Systems"), "vcsPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-vcs.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Tasks Viewer"), "tasksPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("task.png"))
        
        ericPic = QPixmap(os.path.join(getConfig('ericPixDir'), 'eric.png'))
        self.emptyPagePixmap.setPixmap(ericPic)
        self.configStack.raiseWidget(self.configStack.child(str("emptyPage")))
        
        try:
            self.extsep = os.extsep
        except:
            self.extsep = "."
            
        self.autosaveInterval = Preferences.getEditor("AutosaveInterval")
        self.tabStopWidth = Preferences.getEditor("TabWidth")
        self.indentWidth = Preferences.getEditor("IndentWidth")
        self.linenoWidth = Preferences.getEditor("LinenoWidth")
        self.edgeColumn = Preferences.getEditor("EdgeColumn")
        self.editorColours = {}
        
        self.uiLanguage = Preferences.getUILanguage()
        self.viewManager = Preferences.getViewManager()
        
        self.lexers = {}
        self.lexers['Python'] = PreferencesLexer('Python', self)
        self.lexers['C++'] = PreferencesLexer('C++', self)
        self.lexers['C#'] = PreferencesLexer('C#', self)
        self.lexers['IDL'] = PreferencesLexer('IDL', self)
        self.lexers['Java'] = PreferencesLexer('Java', self)
        self.lexers['JavaScript'] = PreferencesLexer('JavaScript', self)
        # the following lexers are only supported for QScintilla > 1.0
        try:
            self.lexers['HTML'] = PreferencesLexer('HTML', self)
        except ImportError:
            pass
        try:
            self.lexers['SQL'] = PreferencesLexer('SQL', self)
        except ImportError:
            pass
        # the following lexers are only supported for QScintilla > 1.2
        try:
            self.lexers['Perl'] = PreferencesLexer('Perl', self)
        except ImportError:
            pass
        # the following lexers are only supported for QScintilla > 1.3
        try:
            self.lexers['Bash'] = PreferencesLexer('Bash', self)
        except ImportError:
            pass
        # the following lexers are only supported for QScintilla > 1.4
        try:
            self.lexers['Ruby'] = PreferencesLexer('Ruby', self)
        except ImportError:
            pass
        try:
            self.lexers['Lua'] = PreferencesLexer('Lua', self)
        except ImportError:
            pass
        
        self.foldStyles = [
            QextScintilla.PlainFoldStyle,
            QextScintilla.CircledFoldStyle,
            QextScintilla.BoxedFoldStyle,
            QextScintilla.CircledTreeFoldStyle,
            QextScintilla.BoxedTreeFoldStyle
        ]
        
        self.initEditorPages()
        self.initPrinterPage()
        self.initProjectPage()
        self.initInterfacePage()
        self.initApplicationPage()
        self.initIconsPage()
        self.initDebuggerPages()
        self.initVariousPages()
        self.initHelpPage()
        
    def initEditorPages(self):
        """
        Private method to initialize the editor pages.
        """
        # init syntax highlighting page
        languages = [''] + self.lexers.keys()
        languages.sort()
        for lang in languages:
            self.lexerLanguageComboBox.insertItem(lang)
        self.handleLexerSelected(QString(''))
        
        # init lexer associations page
        for lang in languages:
            self.editorLexerCombo.insertItem(lang)
        lexerAssocs = Preferences.getEditorLexerAssocs()
        for ext in lexerAssocs.keys():
            QListViewItem(self.editorLexerList, ext, lexerAssocs[ext])
        
        # init general page
        self.autosaveSlider.setValue(self.autosaveInterval)
        self.tabwidthSlider.setValue(self.tabStopWidth)
        self.indentwidthSlider.setValue(self.indentWidth)
        self.linenowidthSlider.setValue(self.linenoWidth)
        self.indentguidesCheckBox.setChecked(Preferences.getEditor("IndentationGuides"))
        self.linenoCheckBox.setChecked(Preferences.getEditor("LinenoMargin"))
        self.foldingCheckBox.setChecked(Preferences.getEditor("FoldingMargin"))
        self.tabforindentationCheckBox.setChecked(Preferences.getEditor("TabForIndentation"))
        self.tabindentsCheckBox.setChecked(Preferences.getEditor("TabIndents"))
        self.converttabsCheckBox.setChecked(Preferences.getEditor("ConvertTabsOnLoad"))
        self.whitespaceCheckBox.setChecked(Preferences.getEditor("ShowWhitespace"))
        self.eolCheckBox.setChecked(Preferences.getEditor("ShowEOL"))
        self.autoindentCheckBox.setChecked(Preferences.getEditor("AutoIndentation"))
        self.bracehighlightingCheckBox.setChecked(Preferences.getEditor("BraceHighlighting"))
        self.automaticEolConversionCheckBox.setChecked(Preferences.getEditor("AutomaticEOLConversion"))
        self.createBackupFileCheckBox.setChecked(Preferences.getEditor("CreateBackupFile"))
        self.automaticSyntaxCheckCheckBox.setChecked(Preferences.getEditor("AutoCheckSyntax"))
        
        # init style page
        self.editorColours["CurrentMarker"] = \
            Preferences.getEditorColour("CurrentMarker")
        size = self.currentLineMarkerButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["CurrentMarker"])
        self.currentLineMarkerButton.setPixmap(pm)
        
        self.editorColours["ErrorMarker"] = \
            Preferences.getEditorColour("ErrorMarker")
        size = self.errorMarkerButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["ErrorMarker"])
        self.errorMarkerButton.setPixmap(pm)
        
        self.editorColours["MatchingBrace"] = \
            Preferences.getEditorColour("MatchingBrace")
        size = self.matchingBracesButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["MatchingBrace"])
        self.matchingBracesButton.setPixmap(pm)
        
        self.editorColours["MatchingBraceBack"] = \
            Preferences.getEditorColour("MatchingBraceBack")
        size = self.matchingBracesBackButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["MatchingBraceBack"])
        self.matchingBracesBackButton.setPixmap(pm)
        
        self.editorColours["NonmatchingBrace"] = \
            Preferences.getEditorColour("NonmatchingBrace")
        size = self.nonmatchingBracesButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["NonmatchingBrace"])
        self.nonmatchingBracesButton.setPixmap(pm)
        
        self.editorColours["NonmatchingBraceBack"] = \
            Preferences.getEditorColour("NonmatchingBraceBack")
        size = self.nonmatchingBracesBackButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["NonmatchingBraceBack"])
        self.nonmatchingBracesBackButton.setPixmap(pm)
        
        self.editorColours["CallTipsBackground"] = \
            Preferences.getEditorColour("CallTipsBackground")
        size = self.calltipsBackgroundButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["CallTipsBackground"])
        self.calltipsBackgroundButton.setPixmap(pm)
        
        self.editorColours["CaretForeground"] = \
            Preferences.getEditorColour("CaretForeground")
        size = self.caretForegroundButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["CaretForeground"])
        self.caretForegroundButton.setPixmap(pm)
        
        self.editorColours["CaretLineBackground"] = \
            Preferences.getEditorColour("CaretLineBackground")
        size = self.caretlineBackgroundButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["CaretLineBackground"])
        self.caretlineBackgroundButton.setPixmap(pm)
        
        eolMode = Preferences.getEditor("EOLMode")
        if eolMode == QextScintilla.EolWindows:
            self.crlfRadioButton.setChecked(1)
        elif eolMode == QextScintilla.EolMac:
            self.crRadioButton.setChecked(1)
        elif eolMode == QextScintilla.EolUnix:
            self.lfRadioButton.setChecked(1)
            
        self.foldingStyleComboBox.setCurrentItem(
            self.foldStyles.index(Preferences.getEditor("FoldingStyle")))
        self.marginsFont = Preferences.getEditorOtherFonts("MarginsFont")
        self.marginsFontSample.setFont(self.marginsFont)
        self.monospacedFont = Preferences.getEditorOtherFonts("MonospacedFont")
        self.monospacedFontSample.setFont(self.monospacedFont)
        self.monospacedCheckBox.setChecked(Preferences.getEditor("UseMonospacedFont"))
        self.caretlineVisibleCheckBox.setChecked(Preferences.getEditor("CaretLineVisible"))
        self.caretWidthSpinBox.setValue(Preferences.getEditor("CaretWidth"))
        self.colourizeSelTextCheckBox.setChecked(Preferences.getEditor("ColourizeSelText"))
        
        self.edgeModeCombo.setCurrentItem(Preferences.getEditor("EdgeMode"))
        self.edgeLineColumnSlider.setValue(self.edgeColumn)
        self.editorColours["Edge"] = \
            Preferences.getEditorColour("Edge")
        size = self.edgeBackgroundColorButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.editorColours["Edge"])
        self.edgeBackgroundColorButton.setPixmap(pm)
        
        # init properties page
        self.foldPythonCommentCheckBox.setChecked(Preferences.getEditor("PythonFoldComment"))
        self.foldPythonStringCheckBox.setChecked(Preferences.getEditor("PythonFoldString"))
        self.pythonBadIndentationCheckBox.setChecked(Preferences.getEditor("PythonBadIndentation"))
        self.pythonAutoindentCheckBox.setChecked(Preferences.getEditor("PythonAutoIndent"))
        
        self.foldCppCommentCheckBox.setChecked(Preferences.getEditor("CppFoldComment"))
        self.foldCppPreprocessorCheckBox.setChecked(Preferences.getEditor("CppFoldPreprocessor"))
        # enable the FoldAtElse checkbox only for recent QScintilla versions
        try:
            self.lexers['C++'].getLexer().foldAtElse()
            self.foldCppAtElseCheckBox.setEnabled(1)
        except AttributeError:
            self.foldCppAtElseCheckBox.setEnabled(0)
        self.foldCppAtElseCheckBox.setChecked(Preferences.getEditor("CppFoldAtElse"))
        
        # enable the HTML properties only for recent QScintilla versions
        try:
            self.lexers['HTML'].getLexer().caseSensitiveTags()
            self.htmlGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.htmlGroupBox.setEnabled(0)
        self.foldHtmlPreprocessorCheckBox.setChecked(Preferences.getEditor("HtmlFoldPreprocessor"))
        self.htmlCaseSensitiveTagsCheckBox.setChecked(Preferences.getEditor("HtmlCaseSensitiveTags"))
        
        # enable the Perl properties only for recent QScintilla versions
        try:
            self.lexers['Perl'].getLexer().foldComments()
            self.perlGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.perlGroupBox.setEnabled(0)
        self.foldPerlCommentCheckBox.setChecked(Preferences.getEditor("PerlFoldComment"))
        
        # enable the Bash properties only for recent QScintilla versions
        try:
            self.lexers['Bash'].getLexer().foldComments()
            self.bashGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.bashGroupBox.setEnabled(0)
        self.foldBashCommentCheckBox.setChecked(Preferences.getEditor("BashFoldComment"))
        
        # enable the Ruby properties only for recent QScintilla versions
        try:
            self.lexers['Ruby'].getLexer().indentationWarning()
            self.rubyGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.rubyGroupBox.setEnabled(0)
        self.rubyBadIndentationCheckBox.setChecked(Preferences.getEditor("RubyBadIndentation"))
        
        # enable the Lua properties only for recent QScintilla versions
        try:
            self.lexers['Lua'].getLexer().foldCompact()
            self.luaGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.luaGroupBox.setEnabled(0)
        self.luaFoldCompactCheckBox.setChecked(Preferences.getEditor("LuaFoldCompact"))
        
        # init api page
        self.apis = {}
        apiLanguages = [''] + Preferences.Prefs.editorAPIDefaults.keys()
        apiLanguages.sort()
        for lang in apiLanguages:
            self.apiLanguageComboBox.insertItem(lang)
        self.currentApiLanguage = QString('')
        self.handleApiLanguageSelected(self.currentApiLanguage)
        
        for lang in apiLanguages[1:]:
            self.apis[lang] = QStringList(Preferences.getEditorAPI(lang))
            
        # init autocompletion and calltips page
        self.acEnabledCheckBox.setChecked(Preferences.getEditor("AutoCompletionEnabled"))
        self.acCaseSensitivityCheckBox.setChecked(Preferences.getEditor("AutoCompletionCaseSensitivity"))
        self.acReplaceWordCheckBox.setChecked(Preferences.getEditor("AutoCompletionReplaceWord"))
        self.acShowSingleCheckBox.setChecked(Preferences.getEditor("AutoCompletionShowSingle"))
        self.acThresholdSlider.setValue(Preferences.getEditor("AutoCompletionThreshold"))
        
        acSource = Preferences.getEditor("AutoCompletionSource")
        if acSource == QextScintilla.AcsDocument:
            self.acSourceDocumentRadioButton.setChecked(1)
        elif acSource == QextScintilla.AcsAPIs:
            self.acSourceAPIsRadioButton.setChecked(1)
        
        self.ctEnabledCheckBox.setChecked(Preferences.getEditor("CallTipsEnabled"))
        self.ctVisibleSlider.setValue(Preferences.getEditor("CallTipsVisible"))
        
    def initPrinterPage(self):
        """
        Private method to initialize the printer page.
        """
        self.printerNameEdit.setText(\
            Preferences.getPrinter("PrinterName"))
        if Preferences.getPrinter("ColorMode"):
            self.printerColorButton.setChecked(1)
        else:
            self.printerGrayscaleButton.setChecked(1)
        if Preferences.getPrinter("FirstPageFirst"):
            self.printFirstPageFirstButton.setChecked(1)
        else:
            self.printFirstPageLastButton.setChecked(1)
        self.printMagnificationSpinBox.setValue(\
            Preferences.getPrinter("Magnification"))
        self.printheaderFont = Preferences.getPrinter("HeaderFont")
        self.printheaderFontSample.setFont(self.printheaderFont)
        
    def initProjectPage(self):
        """
        Private method to initialize the project page.
        """
        self.projectCompressedProjectFilesCheckBox.setChecked(\
            Preferences.getProject("CompressedProjectFiles"))
        self.projectSearchNewFilesCheckBox.setChecked(\
            Preferences.getProject("SearchNewFiles"))
        self.projectAutoIncludeNewFilesCheckBox.setChecked(\
            Preferences.getProject("AutoIncludeNewFiles"))
        self.projectLoadSessionCheckBox.setChecked(\
            Preferences.getProject("AutoLoadSession"))
        self.projectSaveSessionCheckBox.setChecked(\
            Preferences.getProject("AutoSaveSession"))
        self.projectSessionAllBpCheckBox.setChecked(\
            Preferences.getProject("SessionAllBreakpoints"))
        self.projectAutoCompileFormsCheckBox.setChecked(\
            Preferences.getProject("AutoCompileForms"))
        
    def initInterfacePage(self):
        """
        Private method to initialize the interface and viewmanager page.
        """
        # interface page
        self.initLanguageCombo()
        layout = Preferences.getUILayout()
        self.layoutComboBox.setCurrentItem(layout[0])
        self.embeddedShellGroup.setButton(layout[1])
        self.embeddedFileBrowserGroup.setButton(layout[2])
        self.uiBrowsersListFoldersFirstCheckBox.setChecked(\
            Preferences.getUI("BrowsersListFoldersFirst"))
        self.uiBrowsersHideNonPublicCheckBox.setChecked(\
            Preferences.getUI("BrowsersHideNonPublic"))
        self.uiCaptionShowsFilenameCheckBox.setChecked(\
            Preferences.getUI("CaptionShowsFilename"))
        
        # viewmanager page
        self.initWindowViewCombo()
        
    def initApplicationPage(self):
        """
        Private method to initialize the application page.
        """
        self.singleApplicationCheckBox.setChecked(\
            Preferences.getUI("SingleApplicationMode"))
        
    def initIconsPage(self):
        """
        Private method to initialize the icons page.
        """
        self.iconDirectoryList.header().hide()
        self.iconDirectoryList.setSorting(-1)
        
        dirList = QStringList(Preferences.getIcons("Path"))
        first = 1
        for dir in dirList:
            if first:
                itm = QListViewItem(self.iconDirectoryList, dir)
                first = 0
            else:
                itm = QListViewItem(self.iconDirectoryList, lastItem, dir)
            lastItem = itm
        
    def initDebuggerPages(self):
        """
        Private method to initialize the debugger pages.
        """
        # general page
        self.remoteCheckBox.setChecked(Preferences.getDebugger("RemoteDbgEnabled"))
        self.hostLineEdit.setText(Preferences.getDebugger("RemoteHost"))
        self.execLineEdit.setText(Preferences.getDebugger("RemoteExecution"))
        self.passiveDbgCheckBox.setChecked(Preferences.getDebugger("PassiveDbgEnabled"))
        self.passiveDbgPortSpinBox.setValue(Preferences.getDebugger("PassiveDbgPort"))
        self.debugEnvironReplaceCheckBox.setChecked(\
            Preferences.getDebugger("DebugEnvironmentReplace"))
        self.debugEnvironEdit.setText(Preferences.getDebugger("DebugEnvironment"))
        self.automaticResetCheckBox.setChecked(Preferences.getDebugger("AutomaticReset"))
        self.consoleDbgCheckBox.setChecked(Preferences.getDebugger("ConsoleDbgEnabled"))
        self.consoleDbgEdit.setText(Preferences.getDebugger("ConsoleDbgCommand"))

        # Python page
        self.customPyCheckBox.setChecked(Preferences.getDebugger("CustomPythonInterpreter"))
        self.interpreterEdit.setText(Preferences.getDebugger("PythonInterpreter"))
        dct = Preferences.getDebugger("DebugClientType")
        if dct == 1:
            self.standardButton.setChecked(1)
        elif dct == 2:
            self.threadedButton.setChecked(1)
        elif dct == 3:
            self.noqtButton.setChecked(1)
        else:
            self.customButton.setChecked(1)
        self.debugClientEdit.setText(Preferences.getDebugger("DebugClient"))
        self.pyRedirectCheckBox.setChecked(Preferences.getDebugger("PythonRedirect"))
        
        # Ruby page
        self.rubyInterpreterEdit.setText(Preferences.getDebugger("RubyInterpreter"))
        self.rbRedirectCheckBox.setChecked(Preferences.getDebugger("RubyRedirect"))
        
    def initHelpPage(self):
        """
        Private method to initialize the help page.
        """
        hvId = Preferences.getHelp("HelpViewerType")
        if hvId == 1:
            self.helpBrowserButton.setChecked(1)
        elif hvId == 2:
            self.qtAssistantButton.setChecked(1)
        elif hvId == 3:
            self.webBrowserButton.setChecked(1)
        else:
            self.customViewerButton.setChecked(1)
        self.customViewerEdit.setText(Preferences.getHelp("CustomViewer"))
        self.webbrowserEdit.setText(Preferences.getHelp("Webbrowser"))
        self.pdfviewerEdit.setText(Preferences.getHelp("Pdfviewer"))
        self.pythonDocDirEdit.setText(Preferences.getHelp("PythonDocDir"))
        self.qtDocDirEdit.setText(Preferences.getHelp("QtDocDir"))
        
    def initVariousPages(self):
        """
        Private method to initialize the various pages.
        """
        # init the shell settings
        self.stringEncodingComboBox.setCurrentText(Preferences.getSystem("StringEncoding"))
        self.shellLinenowidthSlider.setValue(\
            Preferences.getShell("LinenoWidth"))
        self.shellLinenoCheckBox.setChecked(\
            Preferences.getShell("LinenoMargin"))
        self.shellWordWrapCheckBox.setChecked(\
            Preferences.getShell("WrapEnabled"))
        self.shellACEnabledCheckBox.setChecked(\
            Preferences.getShell("AutoCompletionEnabled"))
        self.shellRACEnabledCheckBox.setChecked(\
            Preferences.getShell("RemoteAutoCompletionEnabled"))
        self.shellCTEnabledCheckBox.setChecked(\
            Preferences.getShell("CallTipsEnabled"))
        
        # init the Qt settings
        self.qtEdit.setText(Preferences.getQt("QtDir"))
        self.exportQtDirCheckBox.setChecked(Preferences.getQt("ExportQtDir"))
        
        # init the CORBA settings
        self.idlEdit.setText(Preferences.getCorba("omniidl"))
        
        # init the Refactoring settings
        self.refactorLoggingCheckBox.setChecked(Preferences.getRefactoring("Logging"))
        
        # init the mail server settings
        self.mailServerEdit.setText(Preferences.getUser("MailServer"))
        self.emailEdit.setText(Preferences.getUser("Email"))
        self.signatureEdit.setText(Preferences.getUser("Signature"))
        self.mailAuthenticationCheckBox.setChecked(\
            Preferences.getUser("MailServerAuthentication"))
        self.mailUserEdit.setText(Preferences.getUser("MailServerUser"))
        self.mailPasswordEdit.setText(Preferences.getUser("MailServerPassword"))
        
        # init the VCS settings
        self.vcsAutoCloseCheckBox.setChecked(Preferences.getVCS("AutoClose"))
        self.vcsAutoSaveCheckBox.setChecked(Preferences.getVCS("AutoSaveFiles"))
        self.vcsAutoSaveProjectCheckBox.setChecked(Preferences.getVCS("AutoSaveProject"))
        
        # init the tasks settings
        self.tasksMarkerEdit.setText(Preferences.getTasks("TasksMarkers"))
        
    def initLanguageCombo(self):
        """
        Private method to initialize the language combobox of the interface page.
        """
        self.languageComboBox.clear()
        
        fnlist = glob.glob("eric3_*.qm") + \
            glob.glob(os.path.join(getConfig('ericTranslationsDir'), "eric3_*.qm")) + \
            glob.glob(os.path.join(Utilities.getConfigDir(), "eric3_*.qm"))
        self.langlist = []
        for fn in fnlist:
            lang = fn[fn.rindex('_')+1:fn.index('.qm')]
            if not lang in self.langlist:
                self.langlist.append(lang)
        self.langlist.sort()
        self.langlist.insert(0, unicode(self.trUtf8('System')))
        self.langlist.insert(0, unicode(self.trUtf8('None')))
        
        try:
            currentIndex = self.langlist.index(self.uiLanguage)
        except:
            currentIndex = 0
        self.languageComboBox.clear()
        for lng in self.langlist:
            self.languageComboBox.insertItem(lng)
        self.languageComboBox.setCurrentItem(currentIndex)
        
    def initWindowViewCombo(self):
        """
        Private method to initialize the window view combobox of the interface page.
        """
        self.windowComboBox.clear()
        
        try:
            currentIndex = ConfigViewManagers.index(self.viewManager)
        except:
            currentIndex = 0
        self.viewManagers = []
        for vm in ConfigViewManagersDispStrings:
            self.viewManagers.append(unicode(self.trUtf8(vm)))
        for vm in self.viewManagers:
            self.windowComboBox.insertItem(vm)
        self.windowComboBox.setCurrentItem(currentIndex)
        self.handleWorkspacePreview(\
            self.viewManagers[currentIndex])
        
    def handleConfigPageSelected(self,itm):
        """
        Private slot to handle the selection of a new config page.
        
        @param itm reference to the selected list view item (QListViewItem)
        """
        if itm is None:
            pageName = "emptyPage"
        else:
            pageName = itm.text(1)
            if pageName.isEmpty():
                pageName = "emptyPage"
        page = self.configStack.child(str(pageName))
        if page is None:
            page = self.configStack.child("emptyPage")
        self.configStack.raiseWidget(page)

    def handleWorkspacePreview(self, workspace):
        """
        Private slot to show a preview of the selected workspace view type.
        
        @param workspace Workspace view type. (string or QString)
        """
        workspace = ConfigViewManagers[\
            self.viewManagers.index(unicode(workspace))]
        workspace = unicode(workspace) + ".png"
        pixmap = QPixmap(os.path.join("pixmaps", workspace))
        if pixmap.isNull():
            pixmap = QPixmap(os.path.join(getConfig('ericPixDir'), workspace))
        self.previewPixmap.setPixmap(pixmap)
    
    def handleLexerSelected(self, language):
        """
        Private slot to fill the style combo of the source page.
        
        @param language The lexer language (string or QString)
        """
        self.styleElementList.clear()
        self.enableStyleList(0)
        
        if language.isEmpty():
            return
            
        try:
            self.lexer = self.lexers[unicode(language)]
        except:
            return
            
        self.enableStyleList(1)
        self.styleElementList.insertStringList(self.lexer.styles)
        self.styleElementList.setCurrentItem(0)
        
    def enableStyleList(self, b):
        """
        Private method to enable/disable the style list and related widgets.
        
        @param b Flag indicatin enabled or disabled state.
        """
        self.styleElementList.setEnabled(b)
        self.foregroundButton.setEnabled(b)
        self.backgroundButton.setEnabled(b)
        self.fontButton.setEnabled(b)
        self.sampleText.setEnabled(b)
        self.eolfillCheckBox.setEnabled(b)
        self.allFontsButton.setEnabled(b)
        self.allBackgroundColoursButton.setEnabled(b)
        
    def handleStyleSelected(self, index):
        """
        Private method to set up the style element part of the source page.
        
        @param index the style index.
        """
        self.style = self.lexer.ind2style[index]
        
        colour = self.lexer.color(self.style)
        paper = self.lexer.paper(self.style)
        eolfill = self.lexer.eolFill(self.style)
        font = self.lexer.font(self.style)
        
        self.sampleText.setFont(font)
        pl = self.sampleText.palette()
        pl.setColor(QColorGroup.Text, colour)
        pl.setColor(QColorGroup.Base, paper)
        self.sampleText.repaint(1)
        self.eolfillCheckBox.setChecked(eolfill)
        
    def handleForegroundColour(self):
        """
        Private method used to select the foreground colour of the selected style and lexer.
        """
        colour = KQColorDialog.getColor(self.lexer.color(self.style))
        if colour.isValid():
            pl = self.sampleText.palette()
            pl.setColor(QColorGroup.Text, colour)
            self.sampleText.repaint(1)
            self.lexer.setColor(colour, self.style)
            
    def handleBackgroundColour(self):
        """
        Private method used to select the background colour of the selected style and lexer.
        """
        colour = KQColorDialog.getColor(self.lexer.paper(self.style))
        if colour.isValid():
            pl = self.sampleText.palette()
            pl.setColor(QColorGroup.Base, colour)
            self.sampleText.repaint(1)
            self.lexer.setPaper(colour, self.style)
            
    def handleAllBackgroundColours(self):
        """
        Private method used to select the background colour of all styles of a selected lexer.
        """
        colour = KQColorDialog.getColor(self.lexer.paper(self.style))
        if colour.isValid():
            pl = self.sampleText.palette()
            pl.setColor(QColorGroup.Base, colour)
            self.sampleText.repaint(1)
            for style in self.lexer.ind2style.values():
                self.lexer.setPaper(colour, style)
            
    def handleFont(self):
        """
        Private method used to select the font of the selected style and lexer.
        """
        font, ok = KQFontDialog.getFont(self.lexer.font(self.style))
        if ok:
            self.sampleText.setFont(font)
            self.lexer.setFont(font, self.style)
            
    def handleAllFonts(self):
        """
        Private method used to change the font of all styles of a selected lexer.
        """
        font, ok = KQFontDialog.getFont(self.lexer.font(self.style))
        if ok:
            self.sampleText.setFont(font)
            for style in self.lexer.ind2style.values():
                self.lexer.setFont(font, style)
            
    def handleEolFill(self, b):
        """
        Private method used to set the eolfill for the selected style and lexer.
        
        @param b Flag indicating enabled or disabled state.
        """
        self.lexer.setEolFill(b, self.style)
        
    def selectColour(self, colourstr, button):
        """
        Private method used by the buttons selecting the marker colours.
        
        @param colourstr Colour to be set. (string)
        @param button Reference to a QButton to show the colour on.
        """
        colour = KQColorDialog.getColor(self.editorColours[colourstr])
        if colour.isValid():
            button.pixmap().fill(colour)
            self.editorColours[colourstr] = colour
            button.repaint(1)
            
    def handleCurrentLineColour(self):
        """
        Private slot to set the colour for the highlight of the current line.
        """
        self.selectColour("CurrentMarker", 
            self.currentLineMarkerButton)
        
    def handleErrorLineColour(self):
        """
        Private slot to set the colour for the highlight of the error line.
        """
        self.selectColour("ErrorMarker", self.errorMarkerButton)
        
    def handleMatchingBracesColour(self):
        """
        Private slot to set the colour for highlighting matching braces.
        """
        self.selectColour("MatchingBrace", self.matchingBracesButton)
        
    def handleMatchingBracesBackColour(self):
        """
        Private slot to set the background colour for highlighting matching braces.
        """
        self.selectColour("MatchingBraceBack", self.matchingBracesBackButton)
        
    def handleNonMatchingBracesColour(self):
        """
        Private slot to set the colour for highlighting nonmatching braces.
        """
        self.selectColour("NonmatchingBrace", self.nonmatchingBracesButton)
        
    def handleNonMatchingBracesBackColour(self):
        """
        Private slot to set the background colour for highlighting nonmatching braces.
        """
        self.selectColour("NonmatchingBraceBack", self.nonmatchingBracesBackButton)
        
    def handleCallTipsBackgroundColour(self):
        """
        Private slot to set the background colour for calltips.
        """
        self.selectColour("CallTipsBackground", self.calltipsBackgroundButton)
        
    def handleCaretForegroundColour(self):
        """
        Private slot to set the foreground colour of the caret.
        """
        self.selectColour("CaretForeground", self.caretForegroundButton)
        
    def handleCaretlineBackgroundColour(self):
        """
        Private slot to set the background colour of the caretline.
        """
        self.selectColour("CaretLineBackground", self.caretlineBackgroundButton)
        
    def handleEdgeColour(self):
        """
        Private slot to set the colour for the edge background or line.
        """
        self.selectColour("Edge", self.edgeBackgroundColorButton)
        
    def handleLinenumbersFont(self):
        """
        Private method used to select the font for the editor margins.
        """
        font, ok = KQFontDialog.getFont(self.marginsFont)
        if ok:
            self.marginsFontSample.setFont(font)
            self.marginsFont = font
            
    def handleMonospacedFont(self):
        """
        Private method used to select the font to be used as the monospaced font.
        """
        font, ok = KQFontDialog.getFont(self.monospacedFont)
        if ok:
            self.monospacedFontSample.setFont(font)
            self.monospacedFont = font
            
    def handleUseTabs(self, checked):
        """
        Private slot used to set the tab conversion check box.
        
        @param checked flag received from the signal (boolean)
        """
        if checked and self.converttabsCheckBox.isChecked():
            self.converttabsCheckBox.setChecked(not checked)
        
    def handleHeaderFont(self):
        """
        Private method used to select the font for the page header.
        """
        font, ok = KQFontDialog.getFont(self.printheaderFont)
        if ok:
            self.printheaderFontSample.setFont(font)
            self.printheaderFont = font
        
    def handleLayoutReset(self):
        """
        Private method to reset layout to factory defaults
        """
        layout = Preferences.getUILayout()
        Preferences.resetLayout(layout[0])
        
    def handleLayoutSelected(self, layout):
        """
        Private slot to handle the layout selected signal of the layout combo.
        
        @param layout number of the selected layout
        """
        if layout == 0:     # splitters
            self.separateFileBrowserButton.setEnabled(0)
            if self.embeddedFileBrowserGroup.selectedId() == 0:
                self.embeddedFileBrowserGroup.setButton(1)
        else:
            self.separateFileBrowserButton.setEnabled(1)
        
    def handlePythonInterpreterSelection(self):
        """
        Private slot to handle the Python interpreter selection.
        """
        file = KQFileDialog.getOpenFileName(self.interpreterEdit.text(),
            None, self, None, self.trUtf8("Select Python interpreter for Debug Client"))
            
        if not file.isNull():
            self.interpreterEdit.setText(QDir.convertSeparators(file))
        
    def handleRubyInterpreterSelection(self):
        """
        Private slot to handle the Ruby interpreter selection.
        """
        file = KQFileDialog.getOpenFileName(self.rubyInterpreterEdit.text(),
            None, self, None, self.trUtf8("Select Ruby interpreter for Debug Client"))
            
        if not file.isNull():
            self.rubyInterpreterEdit.setText(QDir.convertSeparators(file))
        
    def handleDebugClientSelection(self):
        """
        Private slot to handle the Debug Client selection.
        """
        file = KQFileDialog.getOpenFileName(self.debugClientEdit.text(),
            "Python Files (*.py)", self, None,
            self.trUtf8("Select Debug Client"))
            
        if not file.isNull():
            self.debugClientEdit.setText(QDir.convertSeparators(file))
        
    def handleApiLanguageSelected(self, language):
        """
        Private slot to fill the api listbox of the api page.
        
        @param language The selecte API language. (QString)
        """
        if self.currentApiLanguage.compare(language) == 0:
            return
            
        self.apis[unicode(self.currentApiLanguage)] = self.getApisFromListBox()
        self.currentApiLanguage = QString(language)
        self.apiList.clear()
        
        if language.isEmpty():
            self.apiGroup.setEnabled(0)
            return
            
        self.apiGroup.setEnabled(1)
        self.apiList.insertStringList(self.apis[unicode(self.currentApiLanguage)])
        
    def getApisFromListBox(self):
        """
        Private slot to retrieve the api filenames from the listbox.
        
        Returns
        
            list of api filenames (QStringList)
        """
        itm = self.apiList.firstItem()
        apis = QStringList()
        while itm is not None:
            apis.append(itm.text())
            itm = itm.next()
        return apis
        
    def handleApiFile(self):
        """
        Private method to select an api file.
        """
        file = KQFileDialog.getOpenFileName(self.apiFileEdit.text(),
            self.trUtf8("API File (*.api);;All Files (*)"),
            self, None, self.trUtf8("Select API file"))
            
        if not file.isEmpty():
            self.apiFileEdit.setText(QDir.convertSeparators(file))
        
    def handleApiFileAdd(self):
        """
        Private slot to add the api file displayed to the listbox.
        """
        file = self.apiFileEdit.text()
        if not file.isEmpty():
            self.apiList.insertItem(QDir.convertSeparators(file))
            self.apiFileEdit.clear()
            
    def handleApiFileDelete(self):
        """
        Private slot to delete the currently selected file of the listbox.
        """
        self.apiList.removeItem(self.apiList.currentItem())
        
    def handleQtDirSelection(self):
        """
        Private slot to handle the Qt directory selection.
        """
        dir = KQFileDialog.getExistingDirectory(\
            self.qtEdit.text(),
            None, None,
            self.trUtf8("Select Qt Directory"),
            1, 1)
            
        if not dir.isNull():
            self.qtEdit.setText(QDir.convertSeparators(dir))
            
    def handleQtDirEntered(self, dir):
        """
        Private slot to handle a change in the entered Qt directory.
        
        @param dir the entered string (QString)
        """
        self.exportQtDirCheckBox.setEnabled(not dir.isEmpty())
        
    def handleCustomViewerSelection(self):
        """
        Private slot to handle the custom viewer selection.
        """
        file = KQFileDialog.getOpenFileName(self.customViewerEdit.text(),
            None, self, None, self.trUtf8("Select Custom Viewer"))
            
        if not file.isNull():
            self.customViewerEdit.setText(QDir.convertSeparators(file))
        
    def handleWebbrowserSelection(self):
        """
        Private slot to handle the Web browser selection.
        """
        file = KQFileDialog.getOpenFileName(self.webbrowserEdit.text(),
            None, self, None, self.trUtf8("Select Web-Browser"))
            
        if not file.isNull():
            self.webbrowserEdit.setText(QDir.convertSeparators(file))
        
    def handlePdfviewerSelection(self):
        """
        Private slot to handle the PDF viewer selection.
        """
        file = KQFileDialog.getOpenFileName(self.pdfviewerEdit.text(),
            None, self, None, self.trUtf8("Select PDF-Viewer"))
            
        if not file.isNull():
            self.pdfviewerEdit.setText(QDir.convertSeparators(file))
        
    def handlePythonDocDirSelection(self):
        """
        Private slot to select the Python documentation directory.
        """
        dir = KQFileDialog.getExistingDirectory(\
            self.pythonDocDirEdit.text(),
            None, None,
            self.trUtf8("Select Python documentation directory"),
            1, 1)
            
        if not dir.isEmpty():
            self.pythonDocDirEdit.setText(QDir.convertSeparators(dir))
    
    def handleQtDocDirSelection(self):
        """
        Private slot to select the Qt documentation directory.
        """
        dir = KQFileDialog.getExistingDirectory(\
            self.qtDocDirEdit.text(),
            None, None,
            self.trUtf8("Select Qt documentation directory"),
            1, 1)
            
        if not dir.isEmpty():
            self.qtDocDirEdit.setText(QDir.convertSeparators(dir))
    
    def handleIdlSelection(self):
        """
        Private slot to handle the IDL compiler selection.
        """
        file = KQFileDialog.getOpenFileName(self.idlEdit.text(),
            None, self, None, self.trUtf8("Select IDL compiler"))
            
        if not file.isNull():
            self.idlEdit.setText(QDir.convertSeparators(file))
        
    def moveIconDirectoryUp(self):
        """
        Private slot called to move the selected item up in the list.
        """
        itm = self.iconDirectoryList.currentItem()
        if itm is None:
            # nothing selected
            return
            
        itmAbove = itm.itemAbove()
        if itmAbove is None:
            # we're already at the top
            return
            
        itmAbove.moveItem(itm)
    
    def moveIconDirectoryDown(self):
        """
        Private slot called to move the selected item down in the list.
        """
        itm = self.iconDirectoryList.currentItem()
        if itm is None:
            # nothing selected
            return
            
        itmBelow = itm.itemBelow()
        if itmBelow is None:
            # we're already at the end
            return
            
        itm.moveItem(itmBelow)
    
    def handleIconDirectory(self):
        """
        Private slot to select an icon directory.
        """
        dir = KQFileDialog.getExistingDirectory(\
            None,
            None, None,
            self.trUtf8("Select icon directory"),
            0, 1)
            
        if not dir.isEmpty():
            self.iconDirectoryEdit.setText(QDir.convertSeparators(dir))
    
    def handleIconDirectoryAdd(self):
        """
        Private slot to add the icon directory displayed to the listbox.
        """
        dir = self.iconDirectoryEdit.text()
        if not dir.isEmpty():
            lastItem = self.iconDirectoryList.lastItem()
            if lastItem:
                itm = QListViewItem(self.iconDirectoryList, lastItem,
                    QDir.convertSeparators(dir))
            else:
                itm = QListViewItem(self.iconDirectoryList, QDir.convertSeparators(dir))
            self.iconDirectoryEdit.clear()
    
    def handleIconDirectoryDelete(self):
        """
        Private slot to delete the currently selected directory of the listbox.
        """
        itm = self.iconDirectoryList.currentItem()
        self.iconDirectoryList.takeItem(itm)
        del itm
        
    def handleShowIconsPreview(self):
        """
        Private slot to display a preview of an icons directory.
        """
        dir = self.iconDirectoryEdit.text()
        if not dir.isEmpty():
            dlg = IconsPreviewDialog(self, dir)
            dlg.exec_loop()
        
    def handleLexerAdd(self):
        """
        Private slot to add the lexer association displayed to the listbox.
        """
        ext = self.editorFileExtEdit.text()
        if ext.startsWith(self.extsep):
            ext.replace(self.extsep, "")
        lexer = self.editorLexerCombo.currentText()
        if not ext.isEmpty() and not lexer.isEmpty():
            itm = self.editorLexerList.findItem(ext, 0)
            if itm:
                self.editorLexerList.takeItem(itm)
                del itm
            itm = QListViewItem(self.editorLexerList, ext, lexer)
            self.editorFileExtEdit.clear()
            self.editorLexerCombo.setCurrentText("")
    
    def handleLexerDelete(self):
        """
        Private slot to delete the curremtly selected lexer association of the listbox.
        """
        itm = self.editorLexerList.selectedItem()
        if itm is not None:
            self.editorLexerList.takeItem(itm)
            del itm
            
            self.editorLexerList.clearSelection()
            self.editorFileExtEdit.clear()
            self.editorLexerCombo.setCurrentText("")
        
    def handleLexerAssocSelected(self, itm):
        """
        Private slot to handle the clicked signal of the lexer association list.
        
        @param itm reference to the selecte item (QListViewItem)
        """
        if itm is None:
            self.editorFileExtEdit.clear()
            self.editorLexerCombo.setCurrentText("")
        else:
            self.editorFileExtEdit.setText(itm.text(0))
            self.editorLexerCombo.setCurrentText(itm.text(1))
        
    def setPreferences(self):
        """
        Public method called to store the selected values into the preferences storage.
        """
        qApp.processEvents()
        
        # save the language settings
        uiLanguageIndex = self.languageComboBox.currentItem()
        if uiLanguageIndex:
            uiLanguage = self.langlist[uiLanguageIndex]
        else:
            uiLanguage = None
        Preferences.setUILanguage(uiLanguage)
        
        # save the selected viewmanager
        Preferences.setViewManager(\
            ConfigViewManagers[self.windowComboBox.currentItem()])
        
        # save the interface layout settings
        layout = (self.layoutComboBox.currentItem(),
                  self.embeddedShellGroup.selectedId(),
                  self.embeddedFileBrowserGroup.selectedId())
        Preferences.setUILayout(layout)
        
        # save the other UI related settings
        Preferences.setUI("BrowsersListFoldersFirst",
            self.uiBrowsersListFoldersFirstCheckBox.isChecked())
        Preferences.setUI("BrowsersHideNonPublic",
            self.uiBrowsersHideNonPublicCheckBox.isChecked())
        Preferences.setUI("CaptionShowsFilename",
            self.uiCaptionShowsFilenameCheckBox.isChecked())
        
        # save the application settings
        Preferences.setUI("SingleApplicationMode",
            self.singleApplicationCheckBox.isChecked())
        
        # save the icons settings
        dirList = QStringList()
        itm = self.iconDirectoryList.firstChild()
        while itm is not None:
            dirList.append(itm.text(0))
            itm = itm.itemBelow()
        Preferences.setIcons("Path", dirList)
        
        # save the debugger settings
        # general page
        Preferences.setDebugger("RemoteDbgEnabled", self.remoteCheckBox.isChecked())
        Preferences.setDebugger("RemoteHost", self.hostLineEdit.text())
        Preferences.setDebugger("RemoteExecution", self.execLineEdit.text())
        Preferences.setDebugger("PassiveDbgEnabled", self.passiveDbgCheckBox.isChecked())
        Preferences.setDebugger("PassiveDbgPort", self.passiveDbgPortSpinBox.value())
        Preferences.setDebugger("DebugEnvironmentReplace", 
            self.debugEnvironReplaceCheckBox.isChecked())
        Preferences.setDebugger("DebugEnvironment", self.debugEnvironEdit.text())
        Preferences.setDebugger("AutomaticReset", self.automaticResetCheckBox.isChecked())
        Preferences.setDebugger("ConsoleDbgEnabled", self.consoleDbgCheckBox.isChecked())
        Preferences.setDebugger("ConsoleDbgCommand", self.consoleDbgEdit.text())
        # Python page
        Preferences.setDebugger("CustomPythonInterpreter", self.customPyCheckBox.isChecked())
        Preferences.setDebugger("PythonInterpreter", self.interpreterEdit.text())
        sel = self.debugClientGroup.selected()
        Preferences.setDebugger("DebugClientType", 
            self.debugClientGroup.id(self.debugClientGroup.selected()))
        Preferences.setDebugger("DebugClient", self.debugClientEdit.text())
        Preferences.setDebugger("PythonRedirect", self.pyRedirectCheckBox.isChecked())
        # Ruby page
        Preferences.setDebugger("RubyInterpreter", self.rubyInterpreterEdit.text())
        Preferences.setDebugger("RubyRedirect", self.rbRedirectCheckBox.isChecked())
        
        # save the editor settings of general page
        Preferences.setEditor("AutosaveInterval", self.autosaveSlider.value())
        Preferences.setEditor("TabWidth", self.tabwidthSlider.value())
        Preferences.setEditor("IndentWidth", self.indentwidthSlider.value())
        Preferences.setEditor("LinenoWidth", self.linenowidthSlider.value())
        Preferences.setEditor("IndentationGuides",
            self.indentguidesCheckBox.isChecked())
        Preferences.setEditor("LinenoMargin", 
            self.linenoCheckBox.isChecked())
        Preferences.setEditor("FoldingMargin", 
            self.foldingCheckBox.isChecked())
        Preferences.setEditor("TabForIndentation", 
            self.tabforindentationCheckBox.isChecked())
        Preferences.setEditor("TabIndents", 
            self.tabindentsCheckBox.isChecked())
        Preferences.setEditor("ConvertTabsOnLoad",
            self.converttabsCheckBox.isChecked())
        Preferences.setEditor("ShowWhitespace", 
            self.whitespaceCheckBox.isChecked())
        Preferences.setEditor("ShowEOL", 
            self.eolCheckBox.isChecked())
        Preferences.setEditor("AutoIndentation", 
            self.autoindentCheckBox.isChecked())
        Preferences.setEditor("BraceHighlighting",
            self.bracehighlightingCheckBox.isChecked())
        Preferences.setEditor("AutomaticEOLConversion",
            self.automaticEolConversionCheckBox.isChecked())
        Preferences.setEditor("CreateBackupFile",
            self.createBackupFileCheckBox.isChecked())
        Preferences.setEditor("AutoCheckSyntax",
            self.automaticSyntaxCheckCheckBox.isChecked())
            
        # save the editor settings of style page
        for key in self.editorColours.keys():
            Preferences.setEditorColour(key, self.editorColours[key])
        if self.crlfRadioButton.isChecked():
            Preferences.setEditor("EOLMode", QextScintilla.EolWindows)
        elif self.crRadioButton.isChecked():
            Preferences.setEditor("EOLMode", QextScintilla.EolMac)
        elif self.lfRadioButton.isChecked():
            Preferences.setEditor("EOLMode", QextScintilla.EolUnix)
        Preferences.setEditor("FoldingStyle",
            self.foldStyles[self.foldingStyleComboBox.currentItem()])
        Preferences.setEditorOtherFonts("MarginsFont", self.marginsFont)
        Preferences.setEditorOtherFonts("MonospacedFont", self.monospacedFont)
        Preferences.setEditor("UseMonospacedFont",
            self.monospacedCheckBox.isChecked())
        Preferences.setEditor("CaretLineVisible",
            self.caretlineVisibleCheckBox.isChecked())
        Preferences.setEditor("ColourizeSelText",
            self.colourizeSelTextCheckBox.isChecked())
        
        Preferences.setEditor("CaretWidth", self.caretWidthSpinBox.value())
        Preferences.setEditor("EdgeMode",
            self.edgeModeCombo.currentItem()) # cheating
        Preferences.setEditor("EdgeColumn",
            self.edgeLineColumnSlider.value())
            
        # save the editor settings of properties page
        Preferences.setEditor("PythonFoldComment",
            self.foldPythonCommentCheckBox.isChecked())
        Preferences.setEditor("PythonFoldString",
            self.foldPythonStringCheckBox.isChecked())
        Preferences.setEditor("PythonBadIndentation",
            self.pythonBadIndentationCheckBox.isChecked())
        Preferences.setEditor("PythonAutoIndent",
            self.pythonAutoindentCheckBox.isChecked())
        if self.pythonAutoindentCheckBox.isChecked():
            self.lexers['Python'].setAutoIndentStyle(0)
        else:
            self.lexers['Python'].setAutoIndentStyle(QextScintilla.AiMaintain)

        Preferences.setEditor("CppFoldComment",
            self.foldCppCommentCheckBox.isChecked())
        Preferences.setEditor("CppFoldPreprocessor",
            self.foldCppPreprocessorCheckBox.isChecked())
        Preferences.setEditor("CppFoldAtElse",
            self.foldCppAtElseCheckBox.isChecked())
        Preferences.setEditor("CppIndentOpeningBrace",
            self.cppIndentOpeningBraceCheckBox.isChecked())
        Preferences.setEditor("CppIndentClosingBrace",
            self.cppIndentClosingBraceCheckBox.isChecked())
        cppIndentStyle = 0
        if self.cppIndentOpeningBraceCheckBox.isChecked():
            cppIndentStyle |= QextScintilla.AiOpening
        if self.cppIndentClosingBraceCheckBox.isChecked():
            cppIndentStyle |= QextScintilla.AiClosing
        self.lexers['C++'].setAutoIndentStyle(cppIndentStyle)
            
        Preferences.setEditor("HtmlFoldPreprocessor",
            self.foldHtmlPreprocessorCheckBox.isChecked())
        Preferences.setEditor("HtmlCaseSensitiveTags",
            self.htmlCaseSensitiveTagsCheckBox.isChecked())
            
        Preferences.setEditor("PerlFoldComment",
            self.foldPerlCommentCheckBox.isChecked())
            
        Preferences.setEditor("BashFoldComment",
            self.foldBashCommentCheckBox.isChecked())
            
        Preferences.setEditor("RubyBadIndentation",
            self.rubyBadIndentationCheckBox.isChecked())
            
        Preferences.setEditor("LuaFoldCompact",
            self.luaFoldCompactCheckBox.isChecked())
        
        # save the editor settings of api page
        lang = self.apiLanguageComboBox.currentText()
        self.apis[unicode(lang)] = self.getApisFromListBox()
        
        for lang, apis in self.apis.items():
            Preferences.setEditorAPI(lang, apis)
        
        # save the editor settings of the autocompletion/calltips page
        Preferences.setEditor("AutoCompletionEnabled",
            self.acEnabledCheckBox.isChecked())
        Preferences.setEditor("AutoCompletionCaseSensitivity",
            self.acCaseSensitivityCheckBox.isChecked())
        Preferences.setEditor("AutoCompletionReplaceWord",
            self.acReplaceWordCheckBox.isChecked())
        Preferences.setEditor("AutoCompletionShowSingle",
            self.acShowSingleCheckBox.isChecked())
        Preferences.setEditor("AutoCompletionThreshold",
            self.acThresholdSlider.value())
        if self.acSourceDocumentRadioButton.isChecked():
            Preferences.setEditor("AutoCompletionSource", QextScintilla.AcsDocument)
        elif self.acSourceAPIsRadioButton.isChecked():
            Preferences.setEditor("AutoCompletionSource", QextScintilla.AcsAPIs)
            
        Preferences.setEditor("CallTipsEnabled",
            self.ctEnabledCheckBox.isChecked())
        Preferences.setEditor("CallTipsVisible",
            self.ctVisibleSlider.value())
        
        # save the editor settings of the highlighter page
        lexerAssocs = {}
        itm = self.editorLexerList.firstChild()
        while itm is not None:
            lexerAssocs[unicode(itm.text(0))] = unicode(itm.text(1))
            itm = itm.nextSibling()
        Preferences.setEditorLexerAssocs(lexerAssocs)
        
        # save the printer settings
        Preferences.setPrinter("PrinterName",
            self.printerNameEdit.text())
        if self.printerColorButton.isChecked():
            Preferences.setPrinter("ColorMode", 1)
        else:
            Preferences.setPrinter("ColorMode", 0)
        if self.printFirstPageFirstButton.isChecked():
            Preferences.setPrinter("FirstPageFirst", 1)
        else:
            Preferences.setPrinter("FirstPageFirst", 0)
        Preferences.setPrinter("Magnification", 
            self.printMagnificationSpinBox.value())
        Preferences.setPrinter("HeaderFont", self.printheaderFont)
        
        # save the project settings
        Preferences.setProject("CompressedProjectFiles",
            self.projectCompressedProjectFilesCheckBox.isChecked())
        Preferences.setProject("SearchNewFiles",
            self.projectSearchNewFilesCheckBox.isChecked())
        Preferences.setProject("AutoIncludeNewFiles",
            self.projectAutoIncludeNewFilesCheckBox.isChecked())
        Preferences.setProject("AutoLoadSession",
            self.projectLoadSessionCheckBox.isChecked())
        Preferences.setProject("AutoSaveSession",
            self.projectSaveSessionCheckBox.isChecked())
        Preferences.setProject("SessionAllBreakpoints",
            self.projectSessionAllBpCheckBox.isChecked())
        Preferences.setProject("AutoCompileForms",
            self.projectAutoCompileFormsCheckBox.isChecked())
        
        # save the help settings
        Preferences.setHelp("HelpViewerType", 
            self.helpViewerGroup.id(self.helpViewerGroup.selected()))
        Preferences.setHelp("CustomViewer",
            self.customViewerEdit.text())
        Preferences.setHelp("Webbrowser",
            self.webbrowserEdit.text())
        Preferences.setHelp("Pdfviewer",
            self.pdfviewerEdit.text())
        Preferences.setHelp("PythonDocDir",
            self.pythonDocDirEdit.text())
        Preferences.setHelp("QtDocDir",
            self.qtDocDirEdit.text())
        
        # save the system settings
        Preferences.setSystem("StringEncoding",
            unicode(self.stringEncodingComboBox.currentText()))
            
        # write the shell settings
        Preferences.setShell("LinenoWidth",
            self.shellLinenowidthSlider.value())
        Preferences.setShell("LinenoMargin",
            self.shellLinenoCheckBox.isChecked())
        Preferences.setShell("WrapEnabled",
            self.shellWordWrapCheckBox.isChecked())
        Preferences.setShell("AutoCompletionEnabled",
            self.shellACEnabledCheckBox.isChecked())
        Preferences.setShell("RemoteAutoCompletionEnabled",
            self.shellRACEnabledCheckBox.isChecked())
        Preferences.setShell("CallTipsEnabled",
            self.shellCTEnabledCheckBox.isChecked())
        
        # write the Qt settings
        Preferences.setQt("QtDir", self.qtEdit.text())
        Preferences.setQt("ExportQtDir", self.exportQtDirCheckBox.isChecked())
        
        # write the Corba settings
        Preferences.setCorba("omniidl", self.idlEdit.text())
        
        # write the Refactoring settings
        Preferences.setRefactoring("Logging", 
            self.refactorLoggingCheckBox.isChecked())
            
        # write the User settings
        Preferences.setUser("MailServer",
            self.mailServerEdit.text())
        Preferences.setUser("Email",
            self.emailEdit.text())
        Preferences.setUser("Signature",
            self.signatureEdit.text())
        Preferences.setUser("MailServerAuthentication",
            self.mailAuthenticationCheckBox.isChecked())
        Preferences.setUser("MailServerUser",
            self.mailUserEdit.text())
        Preferences.setUser("MailServerPassword",
            self.mailPasswordEdit.text())
            
        # write the VCS settings
        Preferences.setVCS("AutoClose",
            self.vcsAutoCloseCheckBox.isChecked())
        Preferences.setVCS("AutoSaveFiles",
            self.vcsAutoSaveCheckBox.isChecked())
        Preferences.setVCS("AutoSaveProject",
            self.vcsAutoSaveProjectCheckBox.isChecked())
        
        # write the tasks settings
        Preferences.setTasks("TasksMarkers", self.tasksMarkerEdit.text())
        
        # write the lexer styles to disk
        for lexer in self.lexers.values():
            lexer.writeSettings(Preferences.Prefs.settings, "/eric3/Scintilla")
