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

# Copyright (c) 2002, 2003 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 ViewManager.Config import ConfigViewManagersDispStrings, ConfigViewManagers
import Preferences
from PreferencesForm import PreferencesForm
from PreferencesLexer import PreferencesLexer

class PreferencesDialog(PreferencesForm):
    """
    Class implementing a dialog for the configuration of eric3.
    """
    def __init__(self,parent = None,name = None,modal = 0,fl = 0):
        """
        Constructor
        """
        PreferencesForm.__init__(self,parent,name,modal,fl)
        
        self.ericDir = os.path.dirname(sys.argv[0])
        if self.ericDir == '':
            self.ericDir = '.'
            
        self.tabStopWidth = Preferences.getEditor("TabWidth")
        self.indentWidth = Preferences.getEditor("IndentWidth")
        self.linenoWidth = Preferences.getEditor("LinenoWidth")
        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
        
        self.foldStyles = [
            QextScintilla.PlainFoldStyle,
            QextScintilla.CircledFoldStyle,
            QextScintilla.BoxedFoldStyle,
            QextScintilla.CircledTreeFoldStyle,
            QextScintilla.BoxedTreeFoldStyle
        ]
        
        self.initEditorTabs()
        self.initPrinterTab()
        self.initProjectTab()
        self.initInterfaceTab()
        self.initDebuggerTab()
        self.initVariousTab()
        
    def initEditorTabs(self):
        """
        Private method to initialize the editor tab.
        """
        # init source tab
        languages = [''] + self.lexers.keys()
        languages.sort()
        for lang in languages:
            self.lexerLanguageComboBox.insertItem(lang)
        self.handleLexerSelected(QString(''))
        
        # init general tab
        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"))
        
        # init style tab
        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["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["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)
        
        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)
        
        # init properties tab
        self.foldPythonCommentCheckBox.setChecked(Preferences.getEditor("PythonFoldComment"))
        self.foldPythonStringCheckBox.setChecked(Preferences.getEditor("PythonFoldString"))
        self.badIndentationCheckBox.setChecked(Preferences.getEditor("PythonBadIndentation"))
        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++'].lexer().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'].lexer().caseSensitiveTags()
            self.htmlGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.htmlGroupBox.setEnabled(0)
        self.foldHtmlPreprocessorCheckBox.setChecked(Preferences.getEditor("HtmlFoldPreprocessor"))
        self.htmlCaseSensitiveTagsCheckBox.setChecked(Preferences.getEditor("HtmlCaseSensitiveTags"))
        
        # init api tab
        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 tab
        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 initPrinterTab(self):
        """
        Private method to initialize the printer tab.
        """
        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 initProjectTab(self):
        """
        Private method to initialize the project tab.
        """
        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.xmlProjectCheckBox.setChecked(\
            Preferences.getProject("XMLProjectFile"))
        
    def initInterfaceTab(self):
        """
        Private method to initialize the interface tab.
        """
        self.initLanguageCombo()
        self.initWindowViewCombo()
        self.layoutComboBox.setCurrentItem(Preferences.getUILayout())
        
    def initDebuggerTab(self):
        """
        Private method to initialize the debugger tab.
        """
        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.customPyCheckBox.setChecked(Preferences.getDebugger("CustomPythonInterpreter"))
        self.interpreterEdit.setText(Preferences.getDebugger("PythonInterpreter"))
        self.debugClientGroup.setButton(Preferences.getDebugger("DebugClientType"))
        self.debugClientEdit.setText(Preferences.getDebugger("DebugClient"))
        self.automaticResetCheckBox.setChecked(Preferences.getDebugger("AutomaticReset"))
        
    def initVariousTab(self):
        """
        Private method to initialize the various tabs.
        """
        self.assistantCheckBox.setChecked(Preferences.getHelp("UseQtAssistant"))
        self.webbrowserEdit.setText(Preferences.getHelp("Webbrowser"))
        self.stringEncodingComboBox.setCurrentText(Preferences.getSystem("StringEncoding"))
        self.shellFont = Preferences.getShell("Font")
        self.shellFontSample.setFont(self.shellFont)
        self.qtEdit.setText(Preferences.getQt("QtDir"))
        self.exportQtDirCheckBox.setChecked(Preferences.getQt("ExportQtDir"))
        self.idlEdit.setText(Preferences.getCorba("omniidl"))
        self.refactorLoggingCheckBox.setChecked(Preferences.getRefactoring("Logging"))
        self.mailServerEdit.setText(Preferences.getUser("MailServer"))
        self.emailEdit.setText(Preferences.getUser("Email"))
        self.signatureEdit.setText(Preferences.getUser("Signature"))
        
    def initLanguageCombo(self):
        """
        Private method to initialize the language combobox of the interface tab.
        """
        self.languageComboBox.clear()
        
        fnlist = glob.glob("eric3_*.qm") + \
            glob.glob(os.path.join(self.ericDir, "eric3_*.qm"))
        self.langlist = []
        for fn in fnlist:
            lang = fn[fn.index('eric3_')+6:fn.index('.qm')]
            if not lang in self.langlist:
                self.langlist.append(lang)
        self.langlist.sort()
        self.langlist.insert(0, str(self.trUtf8('System')))
        self.langlist.insert(0, str(self.trUtf8('None')))
        
        try:
            currentIndex = self.langlist.index(self.uiLanguage)
        except:
            currentIndex = 0
        self.languageComboBox.insertStrList(self.langlist)
        self.languageComboBox.setCurrentItem(currentIndex)
        
    def initWindowViewCombo(self):
        """
        Private method to initialize the window view combobox of the interface tab.
        """
        self.windowComboBox.clear()
        
        try:
            currentIndex = ConfigViewManagers.index(self.viewManager)
        except:
            currentIndex = 0
        self.viewManagers = []
        for vm in ConfigViewManagersDispStrings:
            self.viewManagers.append(str(self.trUtf8(vm)))
        self.windowComboBox.insertStrList(self.viewManagers)
        self.windowComboBox.setCurrentItem(currentIndex)
        self.handleWorkspacePreview(\
            self.viewManagers[currentIndex])
        
    def handleWorkspacePreview(self, workspace):
        """
        Private slot to show a preview of the selected workspace view type.
        """
        workspace = ConfigViewManagers[\
            self.viewManagers.index(str(workspace))]
        workspace = str(workspace) + ".png"
        pixmap = QPixmap(os.path.join("pixmaps", workspace))
        if pixmap.isNull():
            pixmap = QPixmap(os.path.join(self.ericDir, "pixmaps", workspace))
        self.previewPixmap.setPixmap(pixmap)
    
    def handleLexerSelected(self, language):
        """
        Private slot to fill the style combo of the source tab.
        """
        self.styleElementList.clear()
        self.enableStyleList(0)
        
        if language.isEmpty():
            return
            
        try:
            self.lexer = self.lexers[str(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.
        """
        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)
        
    def handleStyleSelected(self, index):
        """
        Private method to set up the style element part of the source tab.
        """
        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 = QColorDialog.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 = QColorDialog.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 handleFont(self):
        """
        Private method used to select the font of the selected style and lexer.
        """
        font, ok = QFontDialog.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 = QFontDialog.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.
        """
        self.lexer.setEolFill(b, self.style)
        
    def selectColour(self, colourstr, button):
        """
        Private method used by the buttons selecting the marker colours.
        """
        colour = QColorDialog.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 handleNonMatchingBracesColour(self):
        """
        Private slot to set the colour for highlighting nonmatching braces.
        """
        self.selectColour("NonmatchingBrace", self.nonmatchingBracesButton)
        
    def handleCallTipsBackgroundColour(self):
        """
        Private slot to set the background colour for calltips.
        """
        self.selectColour("CallTipsBackground", self.calltipsBackgroundButton)
        
    def handleLinenumbersFont(self):
        """
        Private method used to select the font for the editor margins.
        """
        font, ok = QFontDialog.getFont(self.marginsFont)
        if ok:
            self.marginsFontSample.setFont(font)
            self.marginsFont = font
            
    def handleHeaderFont(self):
        """
        Private method used to select the font for the page header.
        """
        font, ok = QFontDialog.getFont(self.printheaderFont)
        if ok:
            self.printheaderFontSample.setFont(font)
            self.printheaderFont = font
            
    def handleShellFont(self):
        """
        Private method used to select the font for the python shell.
        """
        font, ok = QFontDialog.getFont(self.shellFont)
        if ok:
            self.shellFontSample.setFont(font)
            self.shellFont = font

            
    def handleLayoutReset(self):
        """
        Private method to reset layout to factory defaults
        """
        Preferences.resetLayout(Preferences.getUILayout())
        
    def handleInterpreterSelection(self):
        """
        Private slot to handle the Python interpreter selection.
        """
        file = QFileDialog.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 handleDebugClientSelection(self):
        """
        Private slot to handle the Debug Client selection.
        """
        file = QFileDialog.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 tab.
        """
        if self.currentApiLanguage.compare(language) == 0:
            return
            
        self.apis[str(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[str(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 = QFileDialog.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 = QFileDialog.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.
        
        Arguments
        
            dir -- the entered string (QString)
        """
        self.exportQtDirCheckBox.setEnabled(not dir.isEmpty())
        
    def handleWebbrowserSelection(self):
        """
        Private slot to handle the Web browser selection.
        """
        file = QFileDialog.getOpenFileName(self.webbrowserEdit.text(),
            None, self, None, self.trUtf8("Select Web-Browser"))
            
        if not file.isNull():
            self.webbrowserEdit.setText(QDir.convertSeparators(file))
        
    def handleIdlSelection(self):
        """
        Private slot to handle the IDL compiler selection.
        """
        file = QFileDialog.getOpenFileName(self.idlEdit.text(),
            None, self, None, self.trUtf8("Select IDL compiler"))
            
        if not file.isNull():
            self.idlEdit.setText(QDir.convertSeparators(file))
        
    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
        Preferences.setUILayout(self.layoutComboBox.currentItem())
        
        # save the debugger settings
        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("CustomPythonInterpreter", self.customPyCheckBox.isChecked())
        Preferences.setDebugger("PythonInterpreter", self.interpreterEdit.text())
        Preferences.setDebugger("DebugClientType", 
            self.debugClientGroup.id(self.debugClientGroup.selected()))
        Preferences.setDebugger("DebugClient", self.debugClientEdit.text())
        Preferences.setDebugger("AutomaticReset", self.automaticResetCheckBox.isChecked())
        
        # save the editor settings of general tab
        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())
            
        # save the editor settings of style tab
        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)
            
        # save the editor settings of properties tab
        Preferences.setEditor("PythonFoldComment",
            self.foldPythonCommentCheckBox.isChecked())
        Preferences.setEditor("PythonFoldString",
            self.foldPythonStringCheckBox.isChecked())
        Preferences.setEditor("PythonBadIndentation",
            self.badIndentationCheckBox.isChecked())
        Preferences.setEditor("CppFoldComment",
            self.foldCppCommentCheckBox.isChecked())
        Preferences.setEditor("CppFoldPreprocessor",
            self.foldCppPreprocessorCheckBox.isChecked())
        Preferences.setEditor("CppFoldAtElse",
            self.foldCppAtElseCheckBox.isChecked())
        Preferences.setEditor("HtmlFoldPreprocessor",
            self.foldHtmlPreprocessorCheckBox.isChecked())
        Preferences.setEditor("HtmlCaseSensitiveTags",
            self.htmlCaseSensitiveTagsCheckBox.isChecked())
            
        # save the editor settings of api tab
        lang = self.apiLanguageComboBox.currentText()
        self.apis[str(lang)] = self.getApisFromListBox()
        
        for lang, apis in self.apis.items():
            Preferences.setEditorAPI(lang, apis)
        
        # save the editor settings of the autocompletion/calltips tab
        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 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("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("XMLProjectFile",
            self.xmlProjectCheckBox.isChecked())
        
        # save the help settings
        Preferences.setHelp("UseQtAssistant", 
            self.assistantCheckBox.isChecked())
        Preferences.setHelp("Webbrowser",
            self.webbrowserEdit.text())
        
        # save the system settings
        Preferences.setSystem("StringEncoding",
            str(self.stringEncodingComboBox.currentText()))
            
        # write the shell settings
        Preferences.setShell("Font", self.shellFont)
        
        # 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())
        
        # write the lexer styles to disk
        for lexer in self.lexers.values():
            lexer.writeSettings(Preferences.Prefs.settings, "/eric3/Scintilla")
