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

# Copyright (c) 2002 - 2006 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
from QScintilla.QextScintillaCompat import QSCINTILLA_VERSION
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, fromEric = 1):
        """
        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.fromEric = fromEric
        
        self.configList.header().hide()
        self.configList.setColumnWidthMode(1,QListView.Manual)
        self.configList.setColumnWidth(1,0)
        
        # modify some what's this help texts
        t = QWhatsThis.textFor(self.execLineEdit)
        if not t.isEmpty():
            t = t.append(Utilities.getPercentReplacementHelp())
            QWhatsThis.add(self.execLineEdit, t)
            
        t = QWhatsThis.textFor(self.consoleDbgEdit)
        if not t.isEmpty():
            t = t.append(Utilities.getPercentReplacementHelp())
            QWhatsThis.add(self.consoleDbgEdit, t)
            
        # 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"), "shellPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-shell.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Python"), "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"), "tasksPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("task.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Templates"), "templatesPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-template.png"))
        itm = QListViewItem(self.configList, self.trUtf8("Programs"), "programsPage")
        itm.setPixmap(0, UI.PixmapCache.getPixmap("preferences-programs.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
        # the following lexers are only supported for QScintilla > 1.5
        try:
            self.lexers['CSS'] = PreferencesLexer('CSS', self)
        except ImportError:
            pass
        try:
            self.lexers['Diff'] = PreferencesLexer('Diff', self)
        except ImportError:
            pass
        try:
            self.lexers['Makefile'] = PreferencesLexer('Makefile', self)
        except ImportError:
            pass
        try:
            self.lexers['Properties'] = PreferencesLexer('Properties', self)
        except ImportError:
            pass
        try:
            self.lexers['TeX'] = PreferencesLexer('TeX', self)
        except ImportError:
            pass
        try:
            self.lexers['Batch'] = PreferencesLexer('Batch', self)
        except ImportError:
            pass
        
        self.foldStyles = [
            QextScintilla.PlainFoldStyle,
            QextScintilla.CircledFoldStyle,
            QextScintilla.BoxedFoldStyle,
            QextScintilla.CircledTreeFoldStyle,
            QextScintilla.BoxedTreeFoldStyle
        ]
        
        self.tasksColours = {}
        
        self.initEditorPages()
        self.initPrinterPage()
        self.initProjectPage()
        self.initInterfacePage()
        self.initApplicationPage()
        self.initIconsPage()
        self.initDebuggerPages()
        self.initVariousPages()
        self.initHelpPage()
        self.initTasksPage()
        self.initTemplatesPage()
        
    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"))
        self.defaultEncodingComboBox.setCurrentText(Preferences.getEditor("DefaultEncoding"))
        self.wrapLongLinesCheckBox.setChecked(Preferences.getEditor("WrapLongLines"))
        
        # 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.allFoldCompactCheckBox.setChecked(Preferences.getEditor("AllFoldCompact"))
        
        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 SQL properties only for recent QScintilla versions
        try:
            self.lexers['SQL'].getLexer().foldComments()
            self.sqlGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.sqlGroupBox.setEnabled(0)
        self.foldSqlCommentCheckBox.setChecked(Preferences.getEditor("SqlFoldComment"))
        self.sqlBackslashEscapesCheckBox.setChecked(Preferences.getEditor("SqlBackslashEscapes"))
        
        # enable the CSS properties only for recent QScintilla versions
        try:
            self.lexers['CSS'].getLexer().foldComments()
            self.cssGroupBox.setEnabled(1)
        except (KeyError, AttributeError):
            self.cssGroupBox.setEnabled(0)
        self.foldCssCommentCheckBox.setChecked(Preferences.getEditor("CssFoldComment"))
        
        # 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.acFillupsCheckBox.setChecked(Preferences.getEditor("AutoCompletionFillups"))
        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)
        # the following was added for QScintilla > 1.6
        elif QSCINTILLA_VERSION() > 0x010600 and acSource == QextScintilla.AcsAll:
            self.acSourceAllRadioButton.setChecked(1)
        if QSCINTILLA_VERSION() < 0x010700:
            self.acSourceAllRadioButton.setEnabled(0)
        
        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.projectLoadDebugPropertiesCheckBox.setChecked(\
            Preferences.getProject("AutoLoadDbgProperties"))
        self.projectSaveDebugPropertiesCheckBox.setChecked(\
            Preferences.getProject("AutoSaveDbgProperties"))
        self.projectAutoCompileFormsCheckBox.setChecked(\
            Preferences.getProject("AutoCompileForms"))
        self.projectTimestampCheckBox.setChecked(\
            Preferences.getProject("XMLTimestamp"))
        
    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"))
        self.ResetLayout.setEnabled(self.fromEric)
        
        # 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"))
        self.dbgPathTranslationGroup.setChecked(Preferences.getDebugger("PathTranslation"))
        self.dbgTranslationRemoteEdit.setText(\
            Preferences.getDebugger("PathTranslationRemote"))
        self.dbgTranslationLocalEdit.setText(\
            Preferences.getDebugger("PathTranslationLocal"))

        # 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"))
        self.pyNoEncodingCheckBox.setChecked(Preferences.getDebugger("PythonNoEncoding"))
        
        # 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"))
        self.qt4DocDirEdit.setText(Preferences.getHelp("Qt4DocDir"))
        
    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.shellCTEnabledCheckBox.setChecked(\
            Preferences.getShell("CallTipsEnabled"))
        self.shellHistorySpinBox.setValue(\
            Preferences.getShell("MaxHistoryEntries"))
        
        # init the Qt settings
        self.qtEdit.setText(Preferences.getQt("QtDir"))
        self.exportQtDirCheckBox.setChecked(Preferences.getQt("ExportQtDir"))
        self.qt4Edit.setText(Preferences.getQt("Qt4Dir"))
        self.exportQt4DirCheckBox.setChecked(Preferences.getQt("ExportQt4Dir"))
        
        # 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"))
        
    def initTasksPage(self):
        """
        Private method to initialize the tasks page.
        """
        # init the tasks settings
        self.tasksMarkerEdit.setText(Preferences.getTasks("TasksMarkers"))
        self.tasksMarkerBugfixEdit.setText(Preferences.getTasks("TasksMarkersBugfix"))
        
        self.tasksColours["TasksColour"] = \
            Preferences.getTasks("TasksColour")
        size = self.tasksColourButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.tasksColours["TasksColour"])
        self.tasksColourButton.setPixmap(pm)
        
        self.tasksColours["TasksBugfixColour"] = \
            Preferences.getTasks("TasksBugfixColour")
        size = self.tasksBugfixColourButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.tasksColours["TasksBugfixColour"])
        self.tasksBugfixColourButton.setPixmap(pm)
        
        self.tasksColours["TasksBgColour"] = \
            Preferences.getTasks("TasksBgColour")
        size = self.tasksBgColourButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.tasksColours["TasksBgColour"])
        self.tasksBgColourButton.setPixmap(pm)
        
        self.tasksColours["TasksProjectBgColour"] = \
            Preferences.getTasks("TasksProjectBgColour")
        size = self.tasksProjectBgColourButton.size()
        pm = QPixmap(size.width()/2, size.height()/2)
        pm.fill(self.tasksColours["TasksProjectBgColour"])
        self.tasksProjectBgColourButton.setPixmap(pm)
        
    def initTemplatesPage(self):
        """
        Private method to initialize the templates page.
        """
        # init the templates settings
        self.templatesAutoOpenGroupsCheckBox.setChecked(\
            Preferences.getTemplates("AutoOpenGroups"))
        self.templatesSeparatorCharEdit.setText(\
            Preferences.getTemplates("SeparatorChar"))
        self.templatesInputDialogGroup.setButton(\
            int(Preferences.getTemplates("SingleDialog")))
        self.templatesToolTipCheckBox.setChecked(\
            Preferences.getTemplates("ShowTooltip"))
    
    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(),
            QString.null, 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(),
            QString.null, 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 handleQt4DirSelection(self):
        """
        Private slot to handle the Qt directory selection.
        """
        dir = KQFileDialog.getExistingDirectory(\
            self.qt4Edit.text(),
            None, None,
            self.trUtf8("Select Qt4 Directory"),
            1, 1)
            
        if not dir.isNull():
            self.qt4Edit.setText(QDir.convertSeparators(dir))
            
    def handleQt4DirEntered(self, dir):
        """
        Private slot to handle a change in the entered Qt directory.
        
        @param dir the entered string (QString)
        """
        self.exportQt4DirCheckBox.setEnabled(not dir.isEmpty())
        
    def handleCustomViewerSelection(self):
        """
        Private slot to handle the custom viewer selection.
        """
        file = KQFileDialog.getOpenFileName(self.customViewerEdit.text(),
            QString.null, 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(),
            QString.null, 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(),
            QString.null, 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 handleQt4DocDirSelection(self):
        """
        Private slot to select the Qt documentation directory.
        """
        dir = KQFileDialog.getExistingDirectory(\
            self.qt4DocDirEdit.text(),
            None, None,
            self.trUtf8("Select Qt4 documentation directory"),
            1, 1)
            
        if not dir.isEmpty():
            self.qt4DocDirEdit.setText(QDir.convertSeparators(dir))
    
    def handleIdlSelection(self):
        """
        Private slot to handle the IDL compiler selection.
        """
        file = KQFileDialog.getOpenFileName(self.idlEdit.text(),
            QString.null, 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(\
            QString.null,
            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 currently 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 selectTasksColour(self, colourstr, button):
        """
        Private method used by the buttons selecting the tasks colours.
        
        @param colourstr Colour to be set. (string)
        @param button Reference to a QButton to show the colour on.
        """
        colour = KQColorDialog.getColor(self.tasksColours[colourstr])
        if colour.isValid():
            button.pixmap().fill(colour)
            self.tasksColours[colourstr] = colour
            button.repaint(1)
            
    def handleTasksFgColour(self):
        """
        Private slot to set the colour for standard tasks.
        """
        self.selectTasksColour("TasksColour", 
            self.tasksColourButton)
        
    def handleTasksBugfixFgColour(self):
        """
        Private slot to set the colour for bugfix tasks.
        """
        self.selectTasksColour("TasksBugfixColour", 
            self.tasksBugfixColourButton)
        
    def handleTasksBgColour(self):
        """
        Private slot to set the background colour for global tasks.
        """
        self.selectTasksColour("TasksBgColour", 
            self.tasksBgColourButton)
        
    def handleTasksProjectBgColour(self):
        """
        Private slot to set the backgroundcolour for project tasks.
        """
        self.selectTasksColour("TasksProjectBgColour", 
            self.tasksProjectBgColourButton)
        
    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())
        Preferences.setDebugger("PathTranslation", self.dbgPathTranslationGroup.isChecked())
        Preferences.setDebugger("PathTranslationRemote",
            unicode(self.dbgTranslationRemoteEdit.text()))
        Preferences.setDebugger("PathTranslationLocal",
            unicode(self.dbgTranslationLocalEdit.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())
        Preferences.setDebugger("PythonNoEncoding", self.pyNoEncodingCheckBox.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())
        Preferences.setEditor("DefaultEncoding",
            unicode(self.defaultEncodingComboBox.currentText()))
        Preferences.setEditor("WrapLongLines",
            self.wrapLongLinesCheckBox.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("AllFoldCompact",
            self.allFoldCompactCheckBox.isChecked())
        
        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():
            if QSCINTILLA_VERSION() > 0x010600:
                self.lexers['Python'].setAutoIndentStyle(QextScintilla.AiOpening)
            else:
                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("SqlFoldComment",
            self.foldSqlCommentCheckBox.isChecked())
        Preferences.setEditor("SqlBackslashEscapes",
            self.sqlBackslashEscapesCheckBox.isChecked())
            
        Preferences.setEditor("CssFoldComment",
            self.foldCssCommentCheckBox.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("AutoCompletionFillups",
            self.acFillupsCheckBox.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)
        # the following was added for QScintilla > 1.6
        elif QSCINTILLA_VERSION() > 0x010600 and self.acSourceAllRadioButton.isChecked():
            Preferences.setEditor("AutoCompletionSource", QextScintilla.AcsAll)
            
        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("AutoLoadDbgProperties",
            self.projectLoadDebugPropertiesCheckBox.isChecked())
        Preferences.setProject("AutoSaveDbgProperties",
            self.projectSaveDebugPropertiesCheckBox.isChecked())
        Preferences.setProject("AutoCompileForms",
            self.projectAutoCompileFormsCheckBox.isChecked())
        Preferences.setProject("XMLTimestamp",
            self.projectTimestampCheckBox.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())
        Preferences.setHelp("Qt4DocDir",
            self.qt4DocDirEdit.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("CallTipsEnabled",
            self.shellCTEnabledCheckBox.isChecked())
        Preferences.setShell("MaxHistoryEntries",
            self.shellHistorySpinBox.value())
        
        # write the Qt settings
        Preferences.setQt("QtDir", self.qtEdit.text())
        Preferences.setQt("ExportQtDir", self.exportQtDirCheckBox.isChecked())
        Preferences.setQt("Qt4Dir", self.qt4Edit.text())
        Preferences.setQt("ExportQt4Dir", self.exportQt4DirCheckBox.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())
        Preferences.setTasks("TasksMarkersBugfix", self.tasksMarkerBugfixEdit.text())
        for key in self.tasksColours.keys():
            Preferences.setTasks(key, self.tasksColours[key])
        
        # write the templates settings
        Preferences.setTemplates("AutoOpenGroups",
            self.templatesAutoOpenGroupsCheckBox.isChecked())
        sepChar = self.templatesSeparatorCharEdit.text()
        if not sepChar.isEmpty():
            Preferences.setTemplates("SeparatorChar", unicode(sepChar))
        Preferences.setTemplates("SingleDialog",
            self.templatesInputDialogGroup.selectedId())
        Preferences.setTemplates("ShowTooltip",
            self.templatesToolTipCheckBox.isChecked())
        
        # write the lexer styles to disk
        for lexer in self.lexers.values():
            lexer.writeSettings(Preferences.Prefs.settings, "/eric3/Scintilla")
        
    def accept(self):
        """
        Protected slot called by the Ok button. 
        """
        if not self.fromEric:
            self.setPreferences()
            Preferences.syncPreferences()
        ConfigurationForm.accept(self)
    
    def handleSearchPrograms(self):
        """
        Private slot to search for all supported/required programs.
        """
        qApp.setOverrideCursor(Qt.waitCursor)
        qApp.processEvents()
        
        self.programsList.clear()
        self.programsList.setAllColumnsShowFocus(True)
        
        # 1. do the Qt programs
        if self.qtEdit.text().isEmpty():
            qtdir = os.getenv("QTDIR", "")
        else:
            qtdir = unicode(self.qtEdit.text())
        # 1a. Translation Converter
        exe = sys.platform == "win32" and "lrelease.exe" or "lrelease"
        if qtdir:
            exe = os.path.join(qtdir, 'bin', exe)
        version = self.__createProgramEntry("Translation Converter (Qt3)", exe,
                    '-version', 'lrelease', -1)
        # 1b. Qt Designer
        exe = sys.platform == "win32" and "designer.exe" or "designer"
        if qtdir:
            exe = os.path.join(qtdir, 'bin', exe)
        self.__createProgramEntry("Qt3 Designer", exe, version = version)
        # 1c. Qt Linguist
        exe = sys.platform == "win32" and "linguist.exe" or "linguist"
        if qtdir:
            exe = os.path.join(qtdir, 'bin', exe)
        self.__createProgramEntry("Qt3 Linguist", exe, version = version)
        # 1d. Qt Assistant
        exe = sys.platform == "win32" and "assistant.exe" or "assistant"
        if qtdir:
            exe = os.path.join(qtdir, 'bin', exe)
        self.__createProgramEntry("Qt3 Assistant", exe, version = version)
        
        # do the Qt4 programs
        if self.qt4Edit.text().isEmpty():
            qt4dir = os.getenv("QT4DIR", "")
        else:
            qt4dir = unicode(self.qt4Edit.text())
        # 1e. Translation Converter
        exe = sys.platform == "win32" and "lrelease.exe" or "lrelease"
        if qt4dir:
            exe = os.path.join(qt4dir, 'bin', exe)
        version = self.__createProgramEntry("Translation Converter (Qt4)", exe,
                    '-version', 'lrelease', -1)
        # 1f. Qt4 Designer
        exe = sys.platform == "win32" and "designer.exe" or "designer"
        if qt4dir:
            exe = os.path.join(qt4dir, 'bin', exe)
        self.__createProgramEntry("Qt4 Designer", exe, version = version)
        # 1g. Qt4 Linguist
        exe = sys.platform == "win32" and "linguist.exe" or "linguist"
        if qt4dir:
            exe = os.path.join(qt4dir, 'bin', exe)
        self.__createProgramEntry("Qt4 Linguist", exe, version = version)
        # 1h. Qt4 Assistant
        exe = sys.platform == "win32" and "assistant.exe" or "assistant"
        if qt4dir:
            exe = os.path.join(qt4dir, 'bin', exe)
        self.__createProgramEntry("Qt4 Assistant", exe, version = version)
        
        # 2. do the PyQt programs
        # 2a. Translation Extractor
        self.__createProgramEntry("Translation Extractor (Python, Qt3)", 
            sys.platform == "win32" and "pylupdate.exe" or "pylupdate", 
            '-version', 'pylupdate', -1)
        # 2b. Forms Compiler
        self.__createProgramEntry("Forms Compiler (Python, Qt3)", 
            sys.platform == "win32" and "pyuic.exe" or "pyuic", 
            '-version', 'Python User', 4)
        # 2c. Translation Extractor PyQt4
        self.__createProgramEntry("Translation Extractor (Python, Qt4)", 
            sys.platform == "win32" and "pylupdate4.exe" or "pylupdate4", 
            '-version', 'pylupdate', -1)
        # 2d. Forms Compiler PyQt4
        self.__createProgramEntry("Forms Compiler (Python, Qt4)", 
            sys.platform == "win32" and "pyuic4.bat" or "pyuic4", 
            '--version', 'Python User', 4)
        # 2e. Resource Compiler PyQt4
        self.__createProgramEntry("Resource Compiler (Python, Qt4)", 
            sys.platform == "win32" and "pyrcc4.exe" or "pyrcc4", 
            '-version', 'Resource Compiler', -1)
        
        # 3. do the Ruby programs
        # 3a. Forms Compiler
        self.__createProgramEntry("Forms Compiler (Ruby)", 
            sys.platform == "win32" and "rbuic.exe" or "rbuic", 
            '-version', 'QtRuby User', 4)
        
        # 4. do the Eric3 programs
        # 4a. API File Generator
        self.__createProgramEntry("Eric3 API File Generator", 
            sys.platform == "win32" and "eric3-api.bat" or "eric3-api", 
            '--version', 'eric3-', -1)
        # 4b. Documentation Generator
        self.__createProgramEntry("Eric3 Documentation Generator", 
            sys.platform == "win32" and "eric3-doc.bat" or "eric3-doc", 
            '--version', 'eric3-', -1)
        # 4c. Translation Previewer
        self.__createProgramEntry("Eric3 Translation Previewer", 
            sys.platform == "win32" and "eric3-trpreviewer.bat" or "eric3-trpreviewer", 
            '--version', 'Eric3', -1)
        # 4d. Forms Previewer
        self.__createProgramEntry("Eric3 Forms Previewer", 
            sys.platform == "win32" and "eric3-uipreviewer.bat" or "eric3-uipreviewer", 
            '--version', 'Eric3', -1)
        
        # 5. do the CORBA programs
        # 5a. omniORB
        exe = unicode(self.idlEdit.text())
        if not exe:
            exe = sys.platform == "win32" and "omniidl.exe" or "omniidl"
        self.__createProgramEntry("CORBA IDL Compiler", exe,
            '-V', 'omniidl', -1)
        if not os.path.isabs(exe):
            exe = Utilities.getExecutablePath(exe)
        
        # 6. do the Version Control programs
        # 6a. CVS
        self.__createProgramEntry("Version Control - CVS", 
            sys.platform == "win32" and "cvs.exe" or "cvs", 
            '--version', 'Concurrent Versions', 4)
        # 6b. Subversion
        self.__createProgramEntry("Version Control - Subversion", 
            sys.platform == "win32" and "svn.exe" or "svn", 
            '--version', 'svn', 2)
        
        # 7. do the Checker programs
        # 7a. Pylint
        self.__createProgramEntry("Checkers - Pylint", 
            sys.platform == "win32" and "pylint.bat" or "pylint", 
            '--version', 'pylint', -1)
        
        # 8. do the Packagers programs
        # 8a. cx_freeze
        self.__createProgramEntry("Packagers - cx_freeze", 
            sys.platform == "win32" and "FreezePython.exe" or "FreezePython", 
            '--version', 'FreezePython', -1)
        
        # 9. do other programs
        # 9a. web browser
        self.__createProgramEntry("Web Browser", unicode(self.webbrowserEdit.text()))
        # 9b. PDF viewer
        self.__createProgramEntry("PDF Viewer", unicode(self.pdfviewerEdit.text()))
        
        qApp.restoreOverrideCursor()

    def __createProgramEntry(self, description, exe,
                             versionCommand = "", versionStartsWith = "", 
                             versionPosition = 0, version = ""):
        """
        Private method to generate a program entry.
        
        @param description descriptive text (string or QString)
        @param exe name of the executable program (string)
        @param versionCommand command line switch to get the version info (string).
            if this is empty, the given version will be shown.
        @param versionStartsWith start of line identifying version info (string)
        @param versionPosition index of part containing the version info (integer)
        @keyparam version version string to show (string).
        @return version string of detected or given version (string)
        """
        itm = ProgramsItem(self.programsList, description)
        if not exe:
            itm.setText(1, self.trUtf8("(not configured)"))
        else:
            if os.path.isabs(exe):
                if not Utilities.isExecutable(exe):
                    exe = ""
            else:
                exe = Utilities.getExecutablePath(exe)
            if exe:
                if versionCommand and versionStartsWith and versionPosition:
                    p = os.popen4("%s %s" % (exe, versionCommand))[1]
                    lines = p.readlines()
                    p.close()
                    for line in lines:
                        if line.startswith(versionStartsWith):
                            version = line.split()[versionPosition]
                            break
                itm2 = QListViewItem(itm, exe, version)
                itm.setOpen(True)
            else:
                itm.setText(1, self.trUtf8("(not found)"))
        qApp.processEvents()
        return version

class ProgramsItem(QListViewItem):
    """
    Class implementing a thin wrapper around QListViewItem to show entries in bold. 
    """
    def __init__(self, parent, *args):
        """
        Constructor
        
        @param parent parent Browser or BrowserNode
        @param *args arguments for the QListViewItem constructor
        """
        QListViewItem.__init__(self, parent, *args)

    def paintCell(self, p, cg, column, width, alignment):
        """
        Overwritten method to set text to bold.
        
        @param p the painter (QPainter)
        @param cg the color group (QColorGroup)
        @param column the column (int)
        @param width width of the cell (int)
        @param alignment alignment of the cell (int)
        """
        font = p.font()
        font.setBold(True)
        p.setFont(font)
        
        QListViewItem.paintCell(self, p, cg, column, width, alignment)
    
    def setOpen(self, o):
        """
        Overwritten public slot to set/reset the open state.
        It keeps the open state always at True.
        
        @param o flag indicating the open state (boolean)
        """
        QListViewItem.setOpen(self, True)
