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

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

"""
Module implementing the project management functionality.
"""

import os
import sys
import re
import time
import shutil
import glob
import fnmatch
import copy

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from KdeQt import KQFileDialog, KQMessageBox, KQInputDialog
from KdeQt.KQApplication import e4App

from Globals import recentNameProject

from ProjectBrowserModel import ProjectBrowserModel

from AddLanguageDialog import AddLanguageDialog
from AddFileDialog import AddFileDialog
from AddDirectoryDialog import AddDirectoryDialog
from PropertiesDialog import PropertiesDialog
from AddFoundFilesDialog import AddFoundFilesDialog
from DebuggerPropertiesDialog import DebuggerPropertiesDialog
from FiletypeAssociationDialog import FiletypeAssociationDialog
from UserPropertiesDialog import UserPropertiesDialog

from XML.XMLUtilities import make_parser
from XML.XMLErrorHandler import XMLErrorHandler, XMLFatalParseError
from XML.XMLEntityResolver import XMLEntityResolver

from XML.ProjectHandler import ProjectHandler
from XML.ProjectWriter import ProjectWriter
from XML.UserProjectHandler import UserProjectHandler
from XML.UserProjectWriter import UserProjectWriter
from XML.SessionHandler import SessionHandler
from XML.SessionWriter import SessionWriter
from XML.TasksHandler import TasksHandler
from XML.TasksWriter import TasksWriter
from XML.DebuggerPropertiesHandler import DebuggerPropertiesHandler
from XML.DebuggerPropertiesWriter import DebuggerPropertiesWriter

import VCS
from VCS.Config import ConfigVcsSystemIndicators, ConfigVcsSystems, \
                       ConfigVcsSystemsDisplay
from VCS.CommandOptionsDialog import vcsCommandOptionsDialog
from VCS.ProjectHelper import VcsProjectHelper

from DocumentationTools import DocumentationTools
from Packagers import Packagers
from Checks import Checkers

from Graphics.ApplicationDiagram import ApplicationDiagram

from DataViews.CodeMetricsDialog import CodeMetricsDialog
from DataViews.PyCoverageDialog import PyCoverageDialog
from DataViews.PyProfileDialog import PyProfileDialog

import UI.PixmapCache

from ThirdParty.compactpath import compactpath

from E4Gui.E4Action import E4Action, E4ActionGroup

import Preferences
import Utilities

from eric4config import getConfig

class Project(QObject):
    """
    Module implementing the project management functionality.
    
    @signal dirty(int) emitted when the dirty state changes
    @signal projectSessionLoaded() emitted after a project session file was loaded
    @signal projectLanguageAdded(string) emitted after a new language was added
    @signal projectFormAdded(string) emitted after a new form was added
    @signal projectSourceAdded(string) emitted after a new source file was added
    @signal projectInterfaceAdded(string) emitted after a new IDL file was added
    @signal projectResourceAdded(string) emitted after a new resource file was added
    @signal newProject() emitted after a new project was generated
    @signal sourceFile(string) emitted after a project file was read to 
            open the main script
    @signal projectOpened() emitted after a project file was read
    @signal projectClosed() emitted after a project was closed
    @signal projectOthersAdded(string) emitted after a file or directory was added
            to the OTHERS project data area
    @signal projectFileRenamed(string, string) emitted after a file of the project
            has been renamed
    @signal projectPropertiesChanged() emitted after the project properties were changed
    @signal directoryRemoved(string) emitted after a directory has been removed from
            the project
    @signal prepareRepopulateItem(string) emitted before an item of the model is
            repopulated
    @signal completeRepopulateItem(string) emitted after an item of the model was
            repopulated
    @signal vcsStatusMonitorStatus(QString, QString) emitted to signal the status of the
        monitoring thread (ok, nok, op, off) and a status message
    @signal reinitVCS() emitted after the VCS has been reinitialized
    """
    keynames = [
        "PROGLANGUAGE", "MIXEDLANGUAGE", "UITYPE",
        "DESCRIPTION", "VERSION",
        "AUTHOR", "EMAIL",
        "SOURCES", "FORMS", "RESOURCES",
        "TRANSLATIONS", "TRANSLATIONPREFIX", "TRANSLATIONSBINPATH", 
        "TRANSLATIONEXCEPTIONS",
        "MAINSCRIPT",
        "VCS", "VCSOPTIONS", "VCSOTHERDATA",
        "ERIC4APIPARMS", "ERIC4DOCPARMS",
        "CXFREEZEPARMS",
        "PYLINTPARMS",
        "OTHERS", "INTERFACES", "FILETYPES"
    ]
    
    # the following defines patterns used to perform a security check
    securityCheckPatterns = [
        re.compile(r'os.*\.(exec|popen|spawn|startfile|system)'),
        re.compile(r'os.*\.(remove|rename|rmdir|unlink)'),
        re.compile(r'shutil.*\.rmtree'),
    ]
    
    dbgKeynames = [
        "INTERPRETER", "DEBUGCLIENT",
        "ENVIRONMENTOVERRIDE", "ENVIRONMENTSTRING",
        "REMOTEDEBUGGER", "REMOTEHOST", "REMOTECOMMAND",
        "PATHTRANSLATION", "REMOTEPATH", "LOCALPATH",
        "CONSOLEDEBUGGER", "CONSOLECOMMAND",
        "REDIRECT", "NOENCODING",
    ]
    
    userKeynames = [
        "VCSOVERRIDE", "VCSSTATUSMONITORINTERVAL",
    ]
    
    def __init__(self, parent = None, filename = None):
        """
        Constructor
        
        @param parent parent widget (usually the ui object) (QWidget)
        @param filename optional filename of a project file to open (string)
        """
        QObject.__init__(self, parent)
        
        self.ui = parent
        
        self.sourceExtensions = {\
            "Python" : ['.py', '.ptl', '.pyw'],
            "Ruby"   : ['.rb'],
            "Mixed"  : ['.py', '.ptl', '.rb']
        }
        
        self.sourceFilters = {\
            "Python" : self.trUtf8(\
                        "Python Files (*.py);;"
                        "Quixote PTL Files (*.ptl);;"
                        "Python Files win32 (*.pyw);;"),
            "Ruby"   : self.trUtf8("Ruby Files (*.rb);;"),
            "Mixed"  : self.trUtf8(\
                        "Python Files (*.py);;"
                        "Quixote PTL Files (*.ptl);;"
                        "Python Files win32 (*.pyw);;"
                        "Ruby Files (*.rb);;")
        }
        
        self.dbgFilters = {\
            "Python" : self.trUtf8(\
                        "Python Files (*.py);;"
                        "Python Files win32 (*.pyw);;"),
            "Ruby"   : self.trUtf8("Ruby Files (*.rb);;"),
        }
        
        self.vcsMenu = None
        
        self.__initUiTypes()
        
        self.__initData()
        
        self.recent = QStringList()
        self.__loadRecent()
        
        if filename is not None:
            self.openProject(filename)
        else:
            self.vcs = self.initVCS()
        self.doctools = DocumentationTools(self, self.parent())
        self.packagers = Packagers(self, self.parent())
        self.checkers = Checkers(self, self.parent())
        
        self.__model = ProjectBrowserModel(self)
        
        self.codemetrics        = None
        self.codecoverage       = None
        self.profiledata        = None
        self.applicationDiagram = None
        
    def __initUiTypes(self):
        """
        Private method to initialize the list of supported UI types.
        """
        self.uiTypes = {}
        self.uiTypes["Qt4"] = self.trUtf8("Qt4 GUI")
        self.uiTypes["Qt4C"] = self.trUtf8("Qt4 Console")
        if not Preferences.getQt("DisableQt3"):
            self.uiTypes["Qt"] = self.trUtf8("Qt3")
            if sys.platform != "win32":
                self.uiTypes["Kde"] = self.trUtf8("KDE 3")
        self.uiTypes["Console"] = self.trUtf8("Console")
        self.uiTypes["Other"] = self.trUtf8("Other")
        
    def registerUiType(self, type_, description):
        """
        Public method to register a UI type.
        
        @param type_ internal type designator to be registered (string)
        @param description more verbose type name (display string) (QString)
        """
        if self.uiTypes.has_key(type_):
            KQMessageBox.critical(None,
                self.trUtf8("Registering UI Type"),
                self.trUtf8("""<p>The UI type <b>%1</b> already exists.</p>""")\
                    .arg(type_)
            )
        else:
            self.uiTypes[type_] = description
        
    def unregisterUiType(self, type_):
        """
        Public method to unregister a UI type.
        
        @param type_ internal type designator to be unregistered (string)
        """
        if self.uiTypes.has_key(type_):
            del self.uiTypes[type_]
        
    def __initData(self):
        """
        Private method to initialize the project data part.
        """
        self.loaded = False     # flag for the loaded status
        self.dirty = False      # dirty flag
        self.pfile = ""         # name of the project file
        self.ppath = ""         # name of the project directory
        self.translationsRoot = ""  # the translations prefix
        self.name = ""
        self.opened = False
        self.subdirs = [""] # record the project dir as a relative path (i.e. empty path)
        self.otherssubdirs = []
        self.vcs = None
        self.dbgCmdline = ''
        self.dbgWd = ''
        self.dbgEnv = ''
        self.dbgReportExceptions = True
        self.dbgExcList = QStringList()
        self.dbgAutoClearShell = True
        self.dbgTracePython = False
        self.dbgAutoContinue = True
        self.dbgCovexcPattern = ''
        
        self.pdata = {}
        for key in self.__class__.keynames:
            self.pdata[key] = []
        self.pdata["AUTHOR"] = ['']
        self.pdata["EMAIL"] = ['']
        self.pdata["PROGLANGUAGE"] = ["Python"]
        self.pdata["MIXEDLANGUAGE"] = [False]
        self.pdata["UITYPE"] = ["Qt4"]
        self.pdata["FILETYPES"] = {}
        
        self.__initDebugProperties()
        
        self.pudata = {}
        for key in self.__class__.userKeynames:
            self.pudata[key] = []
        
        self.vcs = self.initVCS()
        
    def __initFileTypes(self):
        """
        Private method to initialize the filetype associations with default values.
        """
        self.pdata["FILETYPES"] = {}
        if self.pdata["MIXEDLANGUAGE"][0]:
            sourceKey = "Mixed"
        else:
            sourceKey = self.pdata["PROGLANGUAGE"][0]
        for ext in self.sourceExtensions[sourceKey]:
            self.pdata["FILETYPES"]["*%s" % ext] = "SOURCES"
        self.pdata["FILETYPES"]["*.ui"] = "FORMS"
        self.pdata["FILETYPES"]["*.ui.h"] = "FORMS"
        self.pdata["FILETYPES"]["*.idl"] = "INTERFACES"
        self.pdata["FILETYPES"]["*.qrc"] = "RESOURCES"
        self.setDirty(True)
        
    def __loadRecent(self):
        """
        Private method to load the recently opened project filenames.
        """
        self.recent.clear()
        Preferences.Prefs.rsettings.sync()
        rp = Preferences.Prefs.rsettings.value(recentNameProject)
        if rp.isValid():
            for f in rp.toStringList():
                if QFileInfo(f).exists():
                    self.recent.append(f)
    
    def __saveRecent(self):
        """
        Private method to save the list of recently opened filenames.
        """
        Preferences.Prefs.rsettings.setValue(recentNameProject, QVariant(self.recent))
        Preferences.Prefs.rsettings.sync()
        
    def getModel(self):
        """
        Public method to get a reference to the project browser model.
        
        @return reference to the project browser model (ProjectBrowserModel)
        """
        return self.__model
        
    def handlePreferencesChanged(self):
        """
        Public slot used to handle the preferencesChanged signal.
        """
        self.__initUiTypes()
        
        if self.pudata["VCSSTATUSMONITORINTERVAL"]:
            self.vcsProjectHelper.setStatusMonitorInterval(\
                self.pudata["VCSSTATUSMONITORINTERVAL"][0])
        else:
            self.vcsProjectHelper.setStatusMonitorInterval(\
                Preferences.getVCS("StatusMonitorInterval"))
        
        self.__model.preferencesChanged()
        
    def setDirty(self, b):
        """
        Public method to set the dirty state.
        
        It emits the signal dirty(int).
        
        @param b dirty state (boolean)
        """
        self.dirty = b
        self.saveAct.setEnabled(b)
        self.emit(SIGNAL("dirty"), bool(b))
        
    def isDirty(self):
        """
        Public method to return the dirty state.
        
        @return dirty state (boolean)
        """
        return self.dirty
        
    def isOpen(self):
        """
        Public method to return the opened state.
        
        @return open state (boolean)
        """
        return self.opened
        
    def __checkFilesExist(self, index):
        """
        Private method to check, if the files in a list exist. 
        
        The files in the indicated list are checked for existance in the
        filesystem. Non existant files are removed from the list and the
        dirty state of the project is changed accordingly.
        
        @param index key of the list to be checked (string)
        """
        removed = False
        removelist = []
        for file in self.pdata[index]:
            if not os.path.exists(os.path.join(self.ppath, file)):
                removelist.append(file)
                removed = True
                
        if removed:
            for file in removelist:
                self.pdata[index].remove(file)
            self.setDirty(True)
        
    def __readProject(self, fn):
        """
        Private method to read in a project (.e4p, .e4pz, .e3p, .e3pz) file.
        
        @param fn filename of the project file to be read (string or QString)
        @return flag indicating success
        """
        fn = unicode(fn)
        try:
            if fn.lower().endswith("e4pz") or fn.lower().endswith("e3pz"):
                try:
                    import gzip
                except ImportError:
                    QApplication.restoreOverrideCursor()
                    KQMessageBox.critical(None,
                        self.trUtf8("Read project file"),
                        self.trUtf8("""Compressed project files not supported."""
                                    """ The compression library is missing."""))
                    return False
                f = gzip.open(fn, "rb")
            else:
                f = open(fn, "rb")
            line = f.readline()
            dtdLine = f.readline()
            f.close()
        except:
            QApplication.restoreOverrideCursor()
            KQMessageBox.critical(None,
                self.trUtf8("Read project file"),
                self.trUtf8("<p>The project file <b>%1</b> could not be read.</p>")\
                    .arg(fn))
            return False
            
        self.pfile = os.path.abspath(fn)
        self.ppath = os.path.abspath(os.path.dirname(fn))
        
        # insert filename into list of recently opened projects
        self.__syncRecent()
        
        # now read the file
        if not line.startswith('<?xml'):
            QApplication.restoreOverrideCursor()
            KQMessageBox.critical(None,
                self.trUtf8("Read project file"),
                self.trUtf8("<p>The project file <b>%1</b> has an unsupported"
                            " format.</p>").arg(fn))
            return False
            
        res = self.__readXMLProject(fn, dtdLine.startswith("<!DOCTYPE"))
        if res:
            if len(self.pdata["TRANSLATIONPREFIX"]) == 1:
                self.translationsRoot = self.pdata["TRANSLATIONPREFIX"][0]
            elif len(self.pdata["MAINSCRIPT"]) == 1:
                self.translationsRoot = os.path.splitext(self.pdata["MAINSCRIPT"][0])[0]
            if os.path.isdir(os.path.join(self.ppath, self.translationsRoot)):
                dn = self.translationsRoot
            else:
                dn = os.path.dirname(self.translationsRoot)
            if dn not in self.subdirs:
                self.subdirs.append(dn)
                
            self.name = os.path.splitext(os.path.basename(fn))[0]
            
            # check, if the files of the project still exist in the project directory
            self.__checkFilesExist("SOURCES")
            self.__checkFilesExist("FORMS")
            self.__checkFilesExist("INTERFACES")
            self.__checkFilesExist("TRANSLATIONS")
            self.__checkFilesExist("RESOURCES")
            self.__checkFilesExist("OTHERS")
            
            # get the names of subdirectories the files are stored in
            for fn in self.pdata["SOURCES"] + \
                      self.pdata["FORMS"] + \
                      self.pdata["INTERFACES"] + \
                      self.pdata["RESOURCES"]:
                dn = os.path.dirname(fn)
                if dn not in self.subdirs:
                    self.subdirs.append(dn)
            
            # get the names of other subdirectories
            for fn in self.pdata["OTHERS"]:
                dn = os.path.dirname(fn)
                if dn not in self.otherssubdirs:
                    self.otherssubdirs.append(dn)
            
            if self.pfile.endswith('e3p') or self.pfile.endswith('e3pz'):
                # needs conversion to new format
                self.setDirty(True)
            
        return res

    def __readXMLProject(self, fn, validating):
        """
        Private method to read the project data from an XML file.
        
        @param fn filename of the project file to be read (string or QString)
        @param validating flag indicating a validation of the XML file is
            requested (boolean)
        @return flag indicating success
        """
        fn = unicode(fn)
        
        parser = make_parser(validating)
        handler = ProjectHandler(self)
        er = XMLEntityResolver()
        eh = XMLErrorHandler()
        
        parser.setContentHandler(handler)
        parser.setEntityResolver(er)
        parser.setErrorHandler(eh)
        
        try:
            if fn.lower().endswith("e4pz") or fn.lower().endswith("e3pz"):
                try:
                    import gzip
                except ImportError:
                    QApplication.restoreOverrideCursor()
                    KQMessageBox.critical(None,
                        self.trUtf8("Read project file"),
                        self.trUtf8("""Compressed project files not supported."""
                                    """ The compression library is missing."""))
                    return False
                f = gzip.open(fn, "rb")
            else:
                f = open(fn, "rb")
            try:
                parser.parse(f)
            finally:
                f.close()
        except IOError:
            QApplication.restoreOverrideCursor()
            KQMessageBox.critical(None,
                self.trUtf8("Read project file"),
                self.trUtf8("<p>The project file <b>%1</b> could not be read.</p>")\
                    .arg(fn))
            return False
            
        except XMLFatalParseError:
            QApplication.restoreOverrideCursor()
            KQMessageBox.critical(None,
                self.trUtf8("Read project file"),
                self.trUtf8("<p>The project file <b>%1</b> has invalid contents.</p>")\
                    .arg(fn))
            eh.showParseMessages()
            return False
            
        QApplication.restoreOverrideCursor()
        eh.showParseMessages()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QApplication.processEvents()
        return True
        
    def __writeProject(self, fn = None):
        """
        Private method to save the project infos to a project file.
        
        @param fn optional filename of the project file to be written.
                If fn is None, the filename stored in the project object
                is used. This is the 'save' action. If fn is given, this filename
                is used instead of the one in the project object. This is the
                'save as' action.
        @return flag indicating success
        """
        if self.vcs is not None:
            self.pdata["VCSOPTIONS"] = [copy.deepcopy(self.vcs.vcsGetOptions())]
            self.pdata["VCSOTHERDATA"] = [copy.deepcopy(self.vcs.vcsGetOtherData())]
            
        if fn is None:
            fn = self.pfile
            
        res = self.__writeXMLProject(fn)
            
        if res:
            self.pfile = os.path.abspath(fn)
            self.ppath = os.path.abspath(os.path.dirname(fn))
            self.name = os.path.splitext(os.path.basename(fn))[0]
            self.setDirty(False)
            
            # insert filename into list of recently opened projects
            self.__syncRecent()
        
        return res
        
    def __writeXMLProject(self, fn = None):
        """
        Private method to write the project data to an XML file.
        
        @param fn the filename of the project file (string)
        """
        try:
            if fn.lower().endswith("e4pz"):
                try:
                    import gzip
                except ImportError:
                    KQMessageBox.critical(None,
                        self.trUtf8("Save project file"),
                        self.trUtf8("""Compressed project files not supported."""
                                    """ The compression library is missing."""))
                    return False
                f = gzip.open(fn, "wb")
            else:
                f = open(fn, "wb")
            
            ProjectWriter(f, os.path.splitext(os.path.basename(fn))[0]).writeXML()
            
            f.close()
            
        except IOError:
            KQMessageBox.critical(None,
                self.trUtf8("Save project file"),
                self.trUtf8("<p>The project file <b>%1</b> could not be written.</p>")\
                    .arg(fn))
            return False
        
        return True
        
    def __readUserProperties(self):
        """
        Private method to read in the user specific project file (.e4q)
        """
        if self.pfile is None:
            return
        
        fn, ext = os.path.splitext(self.pfile)
        
        fn = '%s.e4q' % fn
        if os.path.exists(fn):
            try:
                f = open(fn, "rb")
                
                parser = make_parser(True)
                handler = UserProjectHandler(self)
                er = XMLEntityResolver()
                eh = XMLErrorHandler()
                
                parser.setContentHandler(handler)
                parser.setEntityResolver(er)
                parser.setErrorHandler(eh)
                
                try:
                    parser.parse(f)
                finally:
                    f.close()
            except IOError:
                KQMessageBox.critical(None,
                    self.trUtf8("Read user project properties"),
                    self.trUtf8("<p>The user specific project properties file <b>%1</b>"
                        " could not be read.</p>").arg(fn))
                return
            except XMLFatalParseError:
                pass
            
            eh.showParseMessages()
        
    def __writeUserProperties(self):
        """
        Private method to write the project data to an XML file.
        """
        if self.pfile is None or \
           self.pfile.endswith('e3p') or \
           self.pfile.endswith('e3pz'):
            return
        
        fn, ext = os.path.splitext(self.pfile)
        
        try:
            fn = '%s.e4q' % fn
            f = open(fn, "wb")
            
            UserProjectWriter(f, os.path.splitext(os.path.basename(fn))[0]).writeXML()
            
            f.close()
        except IOError:
            KQMessageBox.critical(None,
                self.trUtf8("Save user project properties"),
                self.trUtf8("<p>The user specific project properties file <b>%1</b>"
                    " could not be written.</p>").arg(fn))
        
    def __readSession(self, quiet = False):
        """
        Private method to read in the project session file (.e4s, .e3s)
        
        @param quiet flag indicating quiet operations.
                If this flag is true, no errors are reported.
        """
        if self.pfile is None:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read project session"),
                    self.trUtf8("Please save the project first."))
            return
            
        fn, ext = os.path.splitext(self.pfile)
        
        try:
            if ext.lower() in [".e4pz", ".e3pz"]:
                sessExt = ext.lower().replace("pz", "sz")
                fn += sessExt
                try:
                    import gzip
                except ImportError:
                    if not quiet:
                        KQMessageBox.critical(None,
                            self.trUtf8("Read project session"),
                            self.trUtf8("""Compressed project session files not"""
                                """ supported. The compression library is missing."""))
                    return
                f = gzip.open(fn, "rb")
            else:
                sessExt = ext.lower().replace("p", "s")
                fn += sessExt
                f = open(fn, "rb")
            line = f.readline()
            dtdLine = f.readline()
            f.close()
        except:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read project session"),
                    self.trUtf8("<p>The project session <b>%1</b>"
                                " could not be read.</p>")\
                        .arg(fn))
            return
            
        # now read the file
        if line.startswith('<?xml'):
            res = self.__readXMLSession(fn, dtdLine.startswith("<!DOCTYPE"), quiet)
        else:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read project session"),
                    self.trUtf8("<p>The project session <b>%1</b> has an unsupported"
                        " format.</p>").arg(fn))
    
    def __readXMLSession(self, fn, validating, quiet):
        """
        Private method to read the session data from an XML file.
        
        The data read is:
            <ul>
            <li>all open source filenames</li>
            <li>the active window</li>
            <li>all breakpoints</li>
            <li>the commandline</li>
            <li>the working directory</li>
            <li>the exception reporting flag</li>
            <li>the list of exception types to be highlighted</li>
            <li>all bookmarks</li>
            </ul>
            
        @param fn filename of the project session file to be read (string or QString)
        @param validating flag indicating a validation of the XML file is
            requested (boolean)
        @param quiet flag indicating quiet operations.
            If this flag is true, no errors are reported.
        """
        fn = unicode(fn)
        
        parser = make_parser(validating)
        handler = SessionHandler(self)
        er = XMLEntityResolver()
        eh = XMLErrorHandler()
        
        parser.setContentHandler(handler)
        parser.setEntityResolver(er)
        parser.setErrorHandler(eh)
        
        try:
            if fn.lower().endswith("e4sz") or fn.lower().endswith("e3sz"):
                try:
                    import gzip
                except ImportError:
                    if not quiet:
                        KQMessageBox.critical(None,
                            self.trUtf8("Read project session"),
                            self.trUtf8("<p>The project session <b>%1</b> could not"
                                " be read.</p>").arg(fn))
                    return
                f = gzip.open(fn, "rb")
            else:
                f = open(fn, "rb")
            try:
                parser.parse(f)
            finally:
                f.close()
        except IOError:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read project session"),
                    self.trUtf8("<p>The project session file <b>%1</b> could not be"
                        " read.</p>").arg(fn))
            return
        except XMLFatalParseError:
            pass
        
        if not quiet:
            eh.showParseMessages()
        
    def __writeSession(self, quiet = False):
        """
        Private method to write the session data to an XML file (.e4s).
        
        The data saved is:
            <ul>
            <li>all open source filenames belonging to the project</li>
            <li>the active window, if it belongs to the project</li>
            <li>all breakpoints</li>
            <li>the commandline</li>
            <li>the working directory</li>
            <li>the exception reporting flag</li>
            <li>the list of exception types to be highlighted</li>
            <li>all bookmarks of files belonging to the project</li>
            </ul>
        
        @param quiet flag indicating quiet operations.
                If this flag is true, no errors are reported.
        """
        if self.pfile is None or \
           self.pfile.endswith('e3p') or \
           self.pfile.endswith('e3pz'):
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Save project session"),
                    self.trUtf8("Please save the project first."))
            return
            
        fn, ext = os.path.splitext(self.pfile)
        
        try:
            if ext.lower() == ".e4pz":
                fn = '%s.e4sz' % fn
                try:
                    import gzip
                except ImportError:
                    if not quiet:
                        KQMessageBox.critical(None,
                            self.trUtf8("Save project session"),
                            self.trUtf8("""Compressed project session files not"""
                                """ supported. The compression library is missing."""))
                    return
                f = gzip.open(fn, "wb")
            else:
                fn = '%s.e4s' % fn
                f = open(fn, "wb")
            
            SessionWriter(f, os.path.splitext(os.path.basename(fn))[0]).writeXML()
            
            f.close()
            
        except IOError:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Save project session"),
                    self.trUtf8("<p>The project session file <b>%1</b> could not be"
                        " written.</p>").arg(fn))
        
    def __deleteSession(self):
        """
        Private method to delete the session file.
        """
        if self.pfile is None:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Delete project session"),
                    self.trUtf8("Please save the project first."))
            return
            
        fname, ext = os.path.splitext(self.pfile)
        
        for fn in ["%s.e4sz" % fname, "%s.e4s" % fname, 
                   "%s.e3sz" % fname, "%s.e3s" % fname]:
            if os.path.exists(fn):
                try:
                    os.remove(fn)
                except OSError:
                    KQMessageBox.critical(None,
                        self.trUtf8("Delete project session"),
                        self.trUtf8("<p>The project session file <b>%1</b> could not be"
                            " deleted.</p>").arg(fn))
        
    def __readTasks(self):
        """
        Private method to read in the project tasks file (.e4t, .e3t)
        """
        if self.pfile is None:
            KQMessageBox.critical(None,
                self.trUtf8("Read tasks"),
                self.trUtf8("Please save the project first."))
            return
            
        fn, ext = os.path.splitext(self.pfile)
        
        try:
            if ext.lower() in [".e4pz", "*.e3pz"]:
                taskExt = ext.lower().replace("pz", "tz")
                fn += taskExt
                if not os.path.exists(fn):
                    return
                try:
                    import gzip
                except ImportError:
                    KQMessageBox.critical(None,
                        self.trUtf8("Read tasks"),
                        self.trUtf8("""Compressed tasks files not supported."""
                            """ The compression library is missing."""))
                    return
                f = gzip.open(fn, "rb")
            else:
                taskExt = ext.lower().replace("p", "t")
                fn += taskExt
                if not os.path.exists(fn):
                    return
                f = open(fn, "rb")
            line = f.readline()
            dtdLine = f.readline()
            f.close()
        except:
            KQMessageBox.critical(None,
                self.trUtf8("Read tasks"),
                self.trUtf8("<p>The tasks file <b>%1</b> could not be read.</p>").arg(fn))
            return
            
        # now read the file
        if line.startswith('<?xml'):
            res = self.__readXMLTasks(fn, dtdLine.startswith("<!DOCTYPE"))
        else:
            KQMessageBox.critical(None,
                self.trUtf8("Read project session"),
                self.trUtf8("<p>The tasks file <b>%1</b> has an unsupported format.</p>")\
                    .arg(fn))
    
    def __readXMLTasks(self, fn, validating):
        """
        Private method to read the project tasks data from an XML file.
        
        @param fn filename of the project tasks file to be read (string or QString)
        @param validating flag indicating a validation of the XML file is
            requested (boolean)
        """
        fn = unicode(fn)
        
        parser = make_parser(validating)
        handler = TasksHandler(1)
        er = XMLEntityResolver()
        eh = XMLErrorHandler()
        
        parser.setContentHandler(handler)
        parser.setEntityResolver(er)
        parser.setErrorHandler(eh)
        
        try:
            if fn.lower().endswith("e4tz") or fn.lower().endswith("e3tz"):
                try:
                    import gzip
                except ImportError:
                    KQMessageBox.critical(None,
                        self.trUtf8("Read tasks"),
                        self.trUtf8("""Compressed tasks files not supported."""
                            """ The compression library is missing."""))
                    return
                f = gzip.open(fn, "rb")
            else:
                f = open(fn, "rb")
            try:
                parser.parse(f)
            finally:
                f.close()
        except IOError:
            KQMessageBox.critical(None,
                self.trUtf8("Read tasks"),
                self.trUtf8("<p>The tasks file <b>%1</b> could not be read.</p>").arg(fn))
            return
        except XMLFatalParseError:
            pass
            
        eh.showParseMessages()
        
    def __writeTasks(self):
        """
        Private method to write the tasks data to an XML file (.e4t).
        """
        if self.pfile is None:
            return
            
        fn, ext = os.path.splitext(self.pfile)
        
        try:
            if ext.lower() == ".e4pz":
                fn = '%s.e4tz' % fn
                try:
                    import gzip
                except ImportError:
                    KQMessageBox.critical(None,
                        self.trUtf8("Save tasks"),
                        self.trUtf8("""Compressed tasks files not supported."""
                            """ The compression library is missing."""))
                    return
                f = gzip.open(fn, "wb")
            else:
                fn = '%s.e4t' % fn
                f = open(fn, "wb")
            
            TasksWriter(f, True, os.path.splitext(os.path.basename(fn))[0]).writeXML()
            
            f.close()
            
        except IOError:
            KQMessageBox.critical(None,
                self.trUtf8("Save tasks"),
                self.trUtf8("<p>The tasks file <b>%1</b> could not be written.</p>")
                    .arg(fn))
        
    def __readDebugProperties(self, quiet=0):
        """
        Private method to read in the project debugger properties file (.e4d, .e3d)
        
        @param quiet flag indicating quiet operations.
                If this flag is true, no errors are reported.
        """
        if self.pfile is None:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read debugger properties"),
                    self.trUtf8("Please save the project first."))
            return
            
        fn, ext = os.path.splitext(self.pfile)
        
        try:
            if ext.lower() in [".e4pz", "*.e3pz"]:
                dbgExt = ext.lower().replace("pz", "dz")
                fn += dbgExt
                try:
                    import gzip
                except ImportError:
                    if not quiet:
                        KQMessageBox.critical(None,
                            self.trUtf8("Read debugger properties"),
                            self.trUtf8("""Compressed project session files not"""
                                        """ supported. The compression library is"""
                                        """ missing."""))
                    return
                f = gzip.open(fn, "rb")
            else:
                dbgExt = ext.lower().replace("p", "d")
                fn += dbgExt
                f = open(fn, "rb")
            line = f.readline()
            dtdLine = f.readline()
            f.close()
        except:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read debugger properties"),
                    self.trUtf8("<p>The project debugger properties file <b>%1</b> could"
                                " not be read.</p>").arg(fn))
            return
            
        # now read the file
        if line.startswith('<?xml'):
            self.__readXMLDebugProperties(fn, dtdLine.startswith("<!DOCTYPE"), quiet)
        else:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read debugger properties"),
                    self.trUtf8("<p>The project debugger properties file <b>%1</b> has an"
                                " unsupported format.</p>").arg(fn))
        
    def __readXMLDebugProperties(self, fn, validating, quiet):
        """
        Public method to read the debugger properties from an XML file.
        
        @param fn filename of the project debugger properties file to be read
            (string or QString)
        @param validating flag indicating a validation of the XML file is
            requested (boolean)
        @param quiet flag indicating quiet operations.
            If this flag is true, no errors are reported.
        """
        fn = unicode(fn)
        
        parser = make_parser(validating)
        handler = DebuggerPropertiesHandler(self)
        er = XMLEntityResolver()
        eh = XMLErrorHandler()
        
        parser.setContentHandler(handler)
        parser.setEntityResolver(er)
        parser.setErrorHandler(eh)
        
        try:
            if fn.lower().endswith("e4dz") or fn.lower().endswith("e3dz"):
                try:
                    import gzip
                except ImportError:
                    if not quiet:
                        KQMessageBox.critical(None,
                            self.trUtf8("Read debugger properties"),
                            self.trUtf8("<p>The project debugger properties file"
                                        " <b>%1</b> could not be read.</p>").arg(fn))
                    return
                f = gzip.open(fn, "rb")
            else:
                f = open(fn, "rb")
            try:
                parser.parse(f)
                if self.debugProperties["INTERPRETER"]:
                    self.debugPropertiesLoaded = True
                else:
                    self.debugPropertiesLoaded = False
            finally:
                f.close()
        except IOError:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Read debugger properties"),
                    self.trUtf8("<p>The project debugger properties file <b>%1</b> could"
                                " not be read.</p>")
                        .arg(fn))
            return
        except XMLFatalParseError:
            pass
            
        if not quiet:
            eh.showParseMessages()
        
    def __writeDebugProperties(self, quiet=0):
        """
        Private method to write the project debugger properties file (.e4d)
        
        @param quiet flag indicating quiet operations.
                If this flag is true, no errors are reported.
        """
        if self.pfile is None or \
           self.pfile.endswith('e3p') or \
           self.pfile.endswith('e3pz'):
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Save debugger properties"),
                    self.trUtf8("Please save the project first."))
            return
            
        fn, ext = os.path.splitext(self.pfile)
        
        try:
            if ext.lower() == ".e4pz":
                fn = '%s.e4dz' % fn
                try:
                    import gzip
                except ImportError:
                    if not quiet:
                        KQMessageBox.critical(None,
                            self.trUtf8("Save debugger properties"),
                            self.trUtf8("""Compressed project debugger properties files"""
                                        """ not supported. The compression library is"""
                                        """ missing."""))
                    return
                f = gzip.open(fn, "wb")
            else:
                fn = '%s.e4d' % fn
                f = open(fn, "wb")
            
            DebuggerPropertiesWriter(f, os.path.splitext(os.path.basename(fn))[0])\
                .writeXML()
            
            f.close()
            
        except IOError:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Save debugger properties"),
                    self.trUtf8("<p>The project debugger properties file <b>%1</b> could"
                                " not be written.</p>")
                        .arg(fn))
        
    def __deleteDebugProperties(self):
        """
        Private method to delete the project debugger properties file (.e3d)
        """
        if self.pfile is None:
            if not quiet:
                KQMessageBox.critical(None,
                    self.trUtf8("Delete debugger properties"),
                    self.trUtf8("Please save the project first."))
            return
            
        fname, ext = os.path.splitext(self.pfile)
        
        for fn in ["%s.e4dz" % fname, "%s.e4d" % fname,
                   "%s.e3dz" % fname, "%s.e3d" % fname]:
            if os.path.exists(fn):
                try:
                    os.remove(fn)
                except OSError:
                    KQMessageBox.critical(None,
                        self.trUtf8("Delete debugger properties"),
                        self.trUtf8("<p>The project debugger properties file <b>%1</b>"
                                    " could not be deleted.</p>")
                            .arg(fn))
        
    def __initDebugProperties(self):
        """
        Private method to initialize the debug properties.
        """
        self.debugPropertiesLoaded = 0
        self.debugProperties = {}
        for key in self.__class__.dbgKeynames:
            self.debugProperties[key] = ""
        self.debugProperties["ENVIRONMENTOVERRIDE"] = 0
        self.debugProperties["REMOTEDEBUGGER"] = 0
        self.debugProperties["PATHTRANSLATION"] = 0
        self.debugProperties["CONSOLEDEBUGGER"] = 0
        self.debugProperties["REDIRECT"] = 1
        self.debugProperties["NOENCODING"] = 0
    
    def isDebugPropertiesLoaded(self):
        """
        Public method to return the status of the debug properties.
        
        @return load status of debug properties (boolean)
        """
        return self.debugPropertiesLoaded
        
    def __showDebugProperties(self):
        """
        Private slot to display the debugger properties dialog.
        """
        dlg = DebuggerPropertiesDialog(self)
        if dlg.exec_() == QDialog.Accepted:
            dlg.storeData()
        
    def getDebugProperty(self, key):
        """
        Public method to retrieve a debugger property.
        
        @param key key of the property (string)
        @return value of the property
        """
        return self.debugProperties[key]
        
    def setDbgInfo(self, argv, wd, env, excReporting, excList, autoClearShell,
                   tracePython = None, autoContinue = None,
                   covexcPattern = None):
        """
        Public method to set the debugging information.
        
        @param argv command line arguments to be used (string or QString)
        @param wd working directory (string or QString)
        @param env environment setting (string or QString)
        @param excReporting flag indicating the highlighting of exceptions
        @param excList list of exceptions to be highlighted (QStringList)
        @param autoClearShell flag indicating, that the interpreter window
            should be cleared (boolean)
        @keyparam tracePython flag to indicate if the Python library should be
            traced as well (boolean)
        @keyparam autoContinue flag indicating, that the debugger should not stop
            at the first executable line (boolean)
        @keyparam covexcPattern regexp pattern to exclude lines from code coverage
            (string or QString)
        """
        self.dbgCmdline = str(argv)
        self.dbgWd = unicode(wd)
        self.dbgEnv = env
        self.dbgReportExceptions = excReporting
        self.dbgExcList = excList[:]    # keep a copy of the list
        self.dbgAutoClearShell = autoClearShell
        if tracePython is not None:
            self.dbgTracePython = tracePython
        if autoContinue is not None:
            self.dbgAutoContinue = autoContinue
        if covexcPattern is not None:
            self.dbgCovexcPattern = covexcPattern
    
    def addLanguage(self):
        """
        Public slot used to add a language to the project.
        """
        if self.translationsRoot == '':
            KQMessageBox.critical(None,
                self.trUtf8("Add Language"),
                self.trUtf8("You have to specify a translation prefix or"
                            " the mainscript of the project first."))
            return
        
        dlg = AddLanguageDialog(self.parent())
        if dlg.exec_() == QDialog.Accepted:
            lang = unicode(dlg.getSelectedLanguage())
            if self.translationsRoot.endswith(os.sep) or \
               self.translationsRoot.endswith("_"):
                sepChar = ""
            else:
                sepChar = "_"
            langFile = '%s%s%s.ts' % (self.translationsRoot, sepChar, lang)
            self.addLanguageFile(langFile)
            
    def addLanguageFile(self, langFile):
        """
        Public slot to add a translation file.
        
        @param langFile the translation file to be removed (string)
        """
        langFile = langFile.replace(self.ppath+os.sep, '')
        self.pdata["TRANSLATIONS"].append(langFile)
        self.__model.addNewItem("TRANSLATIONS", langFile)
        self.emit(SIGNAL('projectLanguageAdded'), langFile)
        self.setDirty(True)
        
    def checkLanguageFiles(self):
        """
        Public slot to check the language files after a release process.
        """
        tbPath = self.pdata["TRANSLATIONSBINPATH"] and \
                 self.pdata["TRANSLATIONSBINPATH"][0] or ""
        for langFile in self.pdata["TRANSLATIONS"][:]:
            if langFile.endswith('.ts'):
                qmFile = langFile.replace('.ts', '.qm')
                if qmFile not in self.pdata["TRANSLATIONS"] and \
                   os.path.exists(os.path.join(self.ppath, qmFile)):
                    self.addLanguageFile(qmFile)
                if tbPath:
                    qmFile = os.path.join(tbPath, os.path.basename(qmFile))
                    if qmFile not in self.pdata["TRANSLATIONS"] and \
                       os.path.exists(os.path.join(self.ppath, qmFile)):
                        self.addLanguageFile(qmFile)
        
    def removeLanguageFile(self, langFile):
        """
        Public slot to remove a translation from the project.
        
        The translation file is not deleted from the project directory.
        
        @param langFile the translation file to be removed (string)
        """
        langFile = langFile.replace(self.ppath+os.sep, '')
        if langFile.endswith('.ts'):
            qmFile = langFile.replace('.ts', '.qm')
        else:
            qmFile = ""
        self.pdata["TRANSLATIONS"].remove(langFile)
        self.__model.removeItem(langFile)
        if qmFile:
            try:
                if self.pdata["TRANSLATIONSBINPATH"]:
                    qmFile = os.path.join(self.pdata["TRANSLATIONSBINPATH"][0],
                        os.path.basename(qmFile)).replace(self.ppath+os.sep, '')
                self.pdata["TRANSLATIONS"].remove(qmFile)
                self.__model.removeItem(qmFile)
            except ValueError:
                pass
        self.setDirty(True)
        
    def deleteLanguageFile(self, langFile):
        """
        Public slot to delete a translation from the project directory.
        
        @param langFile the translation file to be removed (string)
        """
        langFile = langFile.replace(self.ppath+os.sep, '')
        if langFile.endswith('.ts'):
            qmFile = langFile.replace('.ts', '.qm')
        else:
            qmFile = ""
        
        try:
            fn = os.path.join(self.ppath, langFile)
            if os.path.exists(fn):
                os.remove(fn)
        except IOError:
            KQMessageBox.critical(None,
                self.trUtf8("Delete translation"),
                self.trUtf8("<p>The selected translation file <b>%1</b> could not be"
                    " deleted.</p>").arg(langFile))
            return
        
        self.removeLanguageFile(langFile)
        
        # now get rid of the .qm file
        if qmFile:
            try:
                if self.pdata["TRANSLATIONSBINPATH"]:
                    qmFile = os.path.join(self.pdata["TRANSLATIONSBINPATH"][0],
                        os.path.basename(qmFile)).replace(self.ppath+os.sep, '')
                fn = os.path.join(self.ppath, qmFile)
                if os.path.exists(fn):
                    os.remove(fn)
            except IOError:
                KQMessageBox.critical(None,
                    self.trUtf8("Delete translation"),
                    self.trUtf8("<p>The selected translation file <b>%1</b> could not be"
                        " deleted.</p>").arg(qmFile))
                return
        
    def appendFile(self, fn, isSourceFile = False, updateModel = True):
        """
        Public method to append a file to the project.
        
        @param fn filename to be added to the project (string or QString)
        @param isSourceFile flag indicating that this is a source file
                even if it doesn't have the source extension (boolean)
        @param updateModel flag indicating an update of the model is requested (boolean)
        """
        fn = unicode(fn)
        dirty = False
        
        if os.path.isabs(fn):
            # make it relative to the project root, if it starts with that path
            newfn = fn.replace(self.ppath+os.sep, '')
        else:
            # assume relative paths are relative to the project root
            newfn = fn
        newdir = os.path.dirname(newfn)
        
        if isSourceFile:
            filetype = "SOURCES"
        else:
            filetype = "OTHERS"
            bfn = os.path.basename(newfn)
            for pattern in self.pdata["FILETYPES"].keys():
                if fnmatch.fnmatch(bfn, pattern):
                    filetype = self.pdata["FILETYPES"][pattern]
                    break
        
        if filetype in ["SOURCES", "FORMS", "INTERFACES", "RESOURCES"]:
            if filetype == "SOURCES":
                if newfn not in self.pdata["SOURCES"]:
                    self.pdata["SOURCES"].append(newfn)
                    self.emit(SIGNAL('projectSourceAdded'), newfn)
                    updateModel and self.__model.addNewItem("SOURCES", newfn)
                    dirty = True
            elif filetype == "FORMS":
                if newfn not in self.pdata["FORMS"]:
                    self.pdata["FORMS"].append(newfn)
                    self.emit(SIGNAL('projectFormAdded'), newfn)
                    updateModel and self.__model.addNewItem("FORMS", newfn)
                    dirty = True
            elif filetype == "INTERFACES":
                if newfn not in self.pdata["INTERFACES"]:
                    self.pdata["INTERFACES"].append(newfn)
                    self.emit(SIGNAL('projectInterfaceAdded'), newfn)
                    updateModel and self.__model.addNewItem("INTERFACES", newfn)
                    dirty = True
            elif filetype == "RESOURCES":
                if newfn not in self.pdata["RESOURCES"]:
                    self.pdata["RESOURCES"].append(newfn)
                    self.emit(SIGNAL('projectResourceAdded'), newfn)
                    updateModel and self.__model.addNewItem("RESOURCES", newfn)
                    dirty = True
            if newdir not in self.subdirs:
                self.subdirs.append(newdir)
        else:   # filetype == "OTHERS"
            if newfn not in self.pdata["OTHERS"]:
                self.pdata['OTHERS'].append(newfn)
                self.othersAdded(newfn, updateModel)
                dirty = True
            if newdir not in self.otherssubdirs:
                self.otherssubdirs.append(newdir)
        
        if dirty:
            self.setDirty(True)
        
    def addFiles(self, filter = None, startdir = None):
        """
        Public slot used to add files to the project.
        
        @param filter filter to be used by the add file dialog
            (string out of source, form, interface, others)
        @param startdir start directory for the selection dialog
        """
        if startdir is None:
            startdir = self.ppath
        dlg = AddFileDialog(self, self.parent(), filter, startdir=startdir)
        if dlg.exec_() == QDialog.Accepted:
            fnames, target, isSource = dlg.getData()
            if target != '':
                for fn in fnames:
                    ext = os.path.splitext(fn)[1]
                    targetfile = os.path.join(target, os.path.basename(fn))
                    if not Utilities.samepath(os.path.dirname(fn), target):
                        try:
                            if not os.path.isdir(target):
                                os.makedirs(target)
                                
                            if os.path.exists(targetfile):
                                res = KQMessageBox.warning(None,
                                    self.trUtf8("Add file"),
                                    self.trUtf8("<p>The file <b>%1</b> already"
                                        " exists.</p><p>Overwrite it?</p>")
                                        .arg(targetfile),
                                    QMessageBox.StandardButtons(\
                                        QMessageBox.No | \
                                        QMessageBox.Yes),
                                    QMessageBox.No)
                                if res != QMessageBox.Yes:
                                    return  # don't overwrite
                                    
                            shutil.copy(fn, target)
                            if ext == '.ui' and os.path.isfile(fn+'.h'):
                                shutil.copy(fn+'.h', target)
                        except IOError, why:
                            KQMessageBox.critical(None,
                                self.trUtf8("Add file"),
                                self.trUtf8("<p>The selected file <b>%1</b> could not be"
                                    " added to <b>%2</b>.</p>")
                                    .arg(fn)
                                    .arg(target),
                                QMessageBox.StandardButtons(\
                                    QMessageBox.Abort))
                            return
                            
                    if fnmatch.fnmatch(targetfile, '*.ts') or \
                       fnmatch.fnmatch(targetfile, '*.qm'):
                        self.addLanguageFile(targetfile)
                    else:
                        self.appendFile(targetfile, isSource or filter == 'source')
                        if ext == '.ui' and os.path.isfile(targetfile + '.h'):
                            self.appendFile(targetfile + '.h')
            else:
                KQMessageBox.critical(None,
                    self.trUtf8("Add file"),
                    self.trUtf8("The target directory must not be empty."),
                    QMessageBox.StandardButtons(\
                        QMessageBox.Abort))
        
    def __addSingleDirectory(self, ext, source, target, quiet=0):
        """
        Private method used to add all files of a single directory to the project.
        
        @param ext extension of files to add (string)
        @param source source directory (string)
        @param target target directory (string)
        @param quiet flag indicating quiet operations (boolean)
        """
        sstring = "%s%s*%s%s" % (source, os.sep, os.extsep, ext)
        files = glob.glob(sstring)
        if len(files) == 0:
            if not quiet:
                KQMessageBox.information(None,
                    self.trUtf8("Add directory"),
                    self.trUtf8("<p>The source directory doesn't contain"
                        " any files having the extension <b>%1</b>.</p>")
                        .arg(ext))
            return
        
        if not Utilities.samepath(target, source) and not os.path.isdir(target):
            try:
                os.makedirs(target)
            except IOError, why:
                KQMessageBox.critical(None,
                    self.trUtf8("Add directory"),
                    self.trUtf8("<p>The target directory <b>%1</b> could not be"
                        " created.</p>")
                        .arg(target),
                    QMessageBox.StandardButtons(\
                        QMessageBox.Abort))
                return
                
        for file in files:
            targetfile = os.path.join(target, os.path.basename(file))
            if not Utilities.samepath(target, source):
                try:
                    if os.path.exists(targetfile):
                        res = KQMessageBox.warning(None,
                            self.trUtf8("Add directory"),
                            self.trUtf8("<p>The file <b>%1</b> already exists.</p>"
                                        "<p>Overwrite it?</p>")
                                .arg(targetfile),
                            QMessageBox.StandardButtons(\
                                QMessageBox.No | \
                                QMessageBox.Yes),
                            QMessageBox.No)
                        if res != QMessageBox.Yes:
                            continue  # don't overwrite, carry on with next file
                            
                    shutil.copy(file, target)
                    if ext == 'ui' and os.path.isfile(file+os.extsep+'h'):
                        shutil.copy(file+os.extsep+'h', target)
                except:
                    continue
            self.appendFile(targetfile)
            if ext == 'ui' and os.path.isfile(targetfile+os.extsep+'h'):
                self.appendFile(targetfile+os.extsep+'h')
        
    def __addRecursiveDirectory(self, ext, source, target):
        """
        Private method used to add all files of a directory tree.
        
        The tree is rooted at source to another one rooted at target. This
        method decents down to the lowest subdirectory.
        
        @param ext extension of files to add (string)
        @param source source directory (string)
        @param target target directory (string)
        """
        # first perform the addition of source
        self.__addSingleDirectory(ext, source, target, 1)
        
        # now recurse into subdirectories
        for name in os.listdir(source):
            ns = os.path.join(source, name)
            if os.path.isdir(ns):
                nt = os.path.join(target, name)
                self.__addRecursiveDirectory(ext, ns, nt)
        
    def addDirectory(self, filter = None, startdir = None):
        """
        Public method used to add all files of a directory to the project.
        
        @param filter filter to be used by the add directory dialog
            (string out of source, form, interface, others)
        @param startdir start directory for the selection dialog
        """
        if startdir is None:
            startdir = self.ppath
        dlg = AddDirectoryDialog(self, filter, self.parent(), startdir=startdir)
        if dlg.exec_() == QDialog.Accepted:
            ext, source, target, recursive = dlg.getData()
            if target == '':
                KQMessageBox.critical(None,
                    self.trUtf8("Add directory"),
                    self.trUtf8("The target directory must not be empty."),
                    QMessageBox.StandardButtons(\
                        QMessageBox.Abort))
                return
            
            if ext == '':
                self.__addToOthers(QString(source))
                return
            
            if source == '':
                KQMessageBox.critical(None,
                    self.trUtf8("Add directory"),
                    self.trUtf8("The source directory must not be empty."),
                    QMessageBox.StandardButtons(\
                        QMessageBox.Abort))
                return
            
            if recursive:
                self.__addRecursiveDirectory(ext, source, target)
            else:
                self.__addSingleDirectory(ext, source, target)
        
    def __addToOthers(self, fn):
        """
        Private method to add file/directory to the OTHERS project data.
        
        @param fn filename or directoryname to add
        """
        if not fn.isEmpty():
            fn = unicode(fn)
            
            # if it is below the project directory, make it relative to that
            fn = fn.replace(self.ppath+os.sep, '')
            
            # if it ends with the directory separator character, remove it
            if fn.endswith(os.sep):
                fn = fn[:-1]
            if fn not in self.pdata["OTHERS"]:
                self.pdata['OTHERS'].append(fn)
                self.othersAdded(fn)
                self.setDirty(True)
            if os.path.isdir(fn) and fn not in self.otherssubdirs:
                self.otherssubdirs.append(fn)
        
    def addSourceFiles(self):
        """
        Public slot to add source files to the current project.
        """
        self.addFiles('source')
        
    def addUiFiles(self):
        """
        Public slot to add forms to the current project.
        """
        self.addFiles('form')
        
    def addIdlFiles(self):
        """
        Public slot to add IDL interfaces to the current project.
        """
        self.addFiles('interface')
        
    def addResourceFiles(self):
        """
        Public slot to add Qt resources to the current project.
        """
        self.addFiles('resource')
        
    def addOthersFiles(self):
        """
        Private slot to add files to the OTHERS project data.
        """
        self.addFiles('others')
        
    def addSourceDir(self):
        """
        Public slot to add all source files of a directory to the current project.
        """
        self.addDirectory('source')
        
    def addUiDir(self):
        """
        Public slot to add all forms of a directory to the current project.
        """
        self.addDirectory('form')
        
    def addIdlDir(self):
        """
        Public slot to add all IDL interfaces of a directory to the current project.
        """
        self.addDirectory('interface')
        
    def addResourceDir(self):
        """
        Public slot to add all Qt resource files of a directory to the current project.
        """
        self.addDirectory('resource')
        
    def addOthersDir(self):
        """
        Private slot to add a directory to the OTHERS project data.
        """
        self.addDirectory('others')
        
    def renameMainScript(self, oldfn, newfn):
        """
        Public method to rename the main script.
        
        @param oldfn old filename (string)
        @param newfn new filename of the main script (string)
        """
        if self.pdata["MAINSCRIPT"]:
            ofn2 = unicode(oldfn)
            ofn = ofn2.replace(self.ppath+os.sep, '')
            if ofn != self.pdata["MAINSCRIPT"][0]:
                return
            
            fn2 = unicode(newfn)
            fn = fn2.replace(self.ppath+os.sep, '')
            self.pdata["MAINSCRIPT"] = [fn]
            self.setDirty(True)
        
    def renameFile(self, oldfn, newfn = None):
        """
        Public slot to rename a file of the project.
        
        @param oldfn old filename of the file (string)
        @param newfn new filename of the file (string)
        @return flag indicating success
        """
        fn2 = unicode(oldfn)
        fn = fn2.replace(self.ppath+os.sep, '')
        isSourceFile = fn in self.pdata["SOURCES"]
        
        if newfn is None:
            newfn = KQFileDialog.getSaveFileName(\
                None,
                self.trUtf8("Rename file"),
                os.path.dirname(oldfn),
                QString(),
                None,
                QFileDialog.Options(QFileDialog.DontConfirmOverwrite))
            if newfn.isEmpty():
                return False
        
        newfn = unicode(newfn)
        if os.path.exists(newfn):
            canceled = KQMessageBox.warning(None,
                self.trUtf8("Rename File"),
                self.trUtf8("""<p>The file <b>%1</b> already exists. Overwrite it?</p>""")
                    .arg(newfn),
                QMessageBox.StandardButtons(\
                    QMessageBox.No | \
                    QMessageBox.Yes),
                QMessageBox.No)
            if canceled != QMessageBox.Yes:
                return False
        
        try:
            os.rename(oldfn, newfn)
        except OSError, msg:
            KQMessageBox.critical(None,
                self.trUtf8("Rename File"),
                self.trUtf8("""<p>The file <b>%1</b> could not be renamed.<br />"""
                    """Reason: %2</p>""").arg(oldfn).arg(msg))
            return False

        if fn in self.pdata["SOURCES"] or \
           fn in self.pdata["FORMS"] or \
           fn in self.pdata["TRANSLATIONS"] or \
           fn in self.pdata["INTERFACES"] or \
           fn in self.pdata["RESOURCES"] or \
           fn in self.pdata["OTHERS"]:
            self.renameFileInPdata(oldfn, newfn, isSourceFile)
        
        return True
        
    def renameFileInPdata(self, oldname, newname, isSourceFile = False):
        """
        Public method to rename a file in the pdata structure.
        
        @param oldname old filename (string)
        @param newname new filename (string)
        @param isSourceFile flag indicating that this is a source file
                even if it doesn't have the source extension (boolean)
        """
        fn = oldname.replace(self.ppath+os.sep, '')
        if os.path.dirname(oldname) == os.path.dirname(newname):
            self.removeFile(oldname, False)
            self.appendFile(newname, isSourceFile, False)
            self.__model.renameItem(fn, newname)
        else:
            self.removeFile(oldname)
            self.appendFile(newname, isSourceFile)
        self.emit(SIGNAL('projectFileRenamed'), oldname, newname)
        
        self.renameMainScript(fn, newname)
        
    def getFiles(self, start):
        """
        Public method to get all files starting with a common prefix.
        
        @param start prefix (string or QString)
        """
        filelist = []
        start = unicode(start).replace(self.ppath+os.sep, '')
        for key in ["SOURCES", "FORMS", "INTERFACES", "RESOURCES", "OTHERS"]:
            for entry in self.pdata[key][:]:
                if entry.startswith(start):
                    filelist.append(os.path.join(self.ppath, entry))
        return filelist
        
    def copyDirectory(self, olddn, newdn):
        """
        Public slot to copy a directory.
        
        @param olddn original directory name (string or QString)
        @param newdn new directory name (string or QString)
        """
        olddn = unicode(olddn).replace(self.ppath+os.sep, '')
        newdn = unicode(newdn).replace(self.ppath+os.sep, '')
        for key in ["SOURCES", "FORMS", "INTERFACES", "RESOURCES", "OTHERS"]:
            for entry in self.pdata[key][:]:
                if entry.startswith(olddn):
                    entry = entry.replace(olddn, newdn)
                    self.appendFile(os.path.join(self.ppath, entry), key == "SOURCES")
        self.setDirty(True)
        
    def moveDirectory(self, olddn, newdn):
        """
        Public slot to move a directory.
        
        @param olddn old directory name (string or QString)
        @param newdn new directory name (string or QString)
        """
        olddn = unicode(olddn).replace(self.ppath+os.sep, '')
        newdn = unicode(newdn).replace(self.ppath+os.sep, '')
        typeStrings = []
        for key in ["SOURCES", "FORMS", "INTERFACES", "RESOURCES", "OTHERS"]:
            for entry in self.pdata[key][:]:
                if entry.startswith(olddn):
                    if key not in typeStrings:
                        typeStrings.append(key)
                    self.pdata[key].remove(entry)
                    entry = entry.replace(olddn, newdn)
                    self.pdata[key].append(entry)
            if key == "OTHERS":
                if newdn not in self.otherssubdirs:
                    self.otherssubdirs.append(newdn)
            else:
                if newdn not in self.subdirs:
                    self.subdirs.append(newdn)
        self.setDirty(True)
        typeString = typeStrings[0]
        del typeStrings[0]
        self.__model.removeItem(olddn)
        self.__model.addNewItem(typeString, newdn, typeStrings)
        self.emit(SIGNAL('directoryRemoved'), olddn)
        
    def removeFile(self, fn, updateModel = True):
        """
        Public slot to remove a file from the project.
        
        The file is not deleted from the project directory.
        
        @param fn filename to be removed from the project
        @param updateModel flag indicating an update of the model is requested (boolean)
        """
        fn2 = unicode(fn)
        fn = fn2.replace(self.ppath+os.sep, '')
        if fn in self.pdata["SOURCES"]:
            self.pdata["SOURCES"].remove(fn)
        elif fn in self.pdata["FORMS"]:
            self.pdata["FORMS"].remove(fn)
        elif fn in self.pdata["INTERFACES"]:
            self.pdata["INTERFACES"].remove(fn)
        elif fn in self.pdata["RESOURCES"]:
            self.pdata["RESOURCES"].remove(fn)
        elif fn in self.pdata["OTHERS"]:
            self.pdata["OTHERS"].remove(fn)
        updateModel and self.__model.removeItem(fn)
        self.setDirty(True)
        
    def removeDirectory(self, dn):
        """
        Public slot to remove a directory from the project.
        
        The directory is not deleted from the project directory.
        
        @param dn directory name to be removed from the project
        """
        dn2 = unicode(dn)
        dn = dn2.replace(self.ppath+os.sep, '')
        for key in ["SOURCES", "FORMS", "INTERFACES", "RESOURCES", "OTHERS"]:
            for entry in self.pdata[key][:]:
                if entry.startswith(dn):
                    self.pdata[key].remove(entry)
        self.__model.removeItem(dn)
        self.setDirty(True)
        self.emit(SIGNAL('directoryRemoved'), dn)
        
    def deleteFile(self, fn):
        """
        Public slot to delete a file from the project directory.
        
        @param fn filename to be deleted from the project
        @return flag indicating success
        """
        fn = unicode(fn)
        try:
            os.remove(os.path.join(self.ppath, fn))
            dummy, ext = os.path.splitext(fn)
            if ext == '.ui':
                fn2 = os.path.join(self.ppath, '%s.h' % fn)
                if os.path.isfile(fn2):
                    os.remove(fn2)
        except:
            KQMessageBox.critical(None,
                self.trUtf8("Delete file"),
                self.trUtf8("<p>The selected file <b>%1</b> could not be deleted.</p>")
                    .arg(fn))
            return False
        
        self.removeFile(fn)
        if ext == '.ui':
            self.removeFile(fn + '.h')
        return True
        
    def deleteDirectory(self, dn):
        """
        Public slot to delete a directory from the project directory.
        
        @param dn directory name to be removed from the project
        @return flag indicating success
        """
        dn = unicode(dn)
        if not os.path.isabs(dn):
            dn = os.path.join(self.ppath, dn)
        try:
            shutil.rmtree(dn, True)
        except:
            KQMessageBox.critical(None,
                self.trUtf8("Delete directory"),
                self.trUtf8("<p>The selected directory <b>%1</b> could not be"
                    " deleted.</p>").arg(fn))
            return False
        
        self.removeDirectory(dn)
        return True
    
    def hasEntry(self, fn):
        """
        Public method to check the project for a file.
        
        @param fn filename to be checked (string or QString)
        @return flag indicating, if the project contains the file (boolean)
        """
        fn2 = unicode(fn)
        fn = fn2.replace(self.ppath+os.sep, '')
        if fn in self.pdata["SOURCES"] or \
           fn in self.pdata["FORMS"] or \
           fn in self.pdata["INTERFACES"] or \
           fn in self.pdata["RESOURCES"] or \
           fn in self.pdata["OTHERS"]:
            return True
        else:
            return False
        
    def newProject(self):
        """
        Public slot to built a new project.
        
        This method displays the new project dialog and initializes
        the project object with the data entered.
        """
        if not self.checkDirty():
            return
            
        dlg = PropertiesDialog(self, True)
        if dlg.exec_() == QDialog.Accepted:
            self.closeProject()
            dlg.storeData()
            self.pdata["VCS"] = ['None']
            self.opened = True
            if not self.pdata["FILETYPES"]:
                self.__initFileTypes()
            self.setDirty(True)
            self.closeAct.setEnabled(True)
            self.saveasAct.setEnabled(True)
            self.actGrp2.setEnabled(True)
            self.propsAct.setEnabled(True)
            self.userPropsAct.setEnabled(True)
            self.filetypesAct.setEnabled(True)
            self.sessActGrp.setEnabled(False)
            self.dbgActGrp.setEnabled(True)
            self.menuDebuggerAct.setEnabled(True)
            self.menuSessionAct.setEnabled(False)
            self.menuCheckAct.setEnabled(True)
            self.menuShowAct.setEnabled(True)
            self.menuDiagramAct.setEnabled(True)
            self.menuApidocAct.setEnabled(True)
            self.menuPackagersAct.setEnabled(True)
        
            # create the project directory if it doesn't exist already
            if not os.path.isdir(self.ppath):
                try:
                    os.makedirs(self.ppath)
                except:
                    KQMessageBox.critical(None,
                        self.trUtf8("Create project directory"),
                        self.trUtf8("<p>The project directory <b>%1</b> could not"
                            " be created.</p>")
                            .arg(self.ppath))
                    self.vcs = self.initVCS()
                    return
                tpd = os.path.join(self.ppath, self.translationsRoot)
                if not self.translationsRoot.endswith(os.sep):
                    tpd = os.path.dirname(tpd)
                if not os.path.isdir(tpd):
                    os.makedirs(tpd)
                if self.pdata["TRANSLATIONSBINPATH"]:
                    tpd = os.path.join(self.ppath, self.pdata["TRANSLATIONSBINPATH"][0])
                    if not os.path.isdir(tpd):
                        os.makedirs(tpd)
                self.saveProject()
            else:
                try:
                    ms = os.path.join(self.ppath, self.pdata["MAINSCRIPT"][0])
                    if os.path.exists(ms):
                        self.appendFile(ms)
                except IndexError:
                    ms = ""
                
                # add existing files to the project
                res = KQMessageBox.question(None,
                    self.trUtf8("New Project"),
                    self.trUtf8("""Add existing files to the project?"""),
                    QMessageBox.StandardButtons(\
                        QMessageBox.No | \
                        QMessageBox.Yes),
                    QMessageBox.Yes)
                if res == QMessageBox.Yes:
                    # search the project directory for files with known extensions
                    filespecs = self.pdata["FILETYPES"].keys()
                    for filespec in filespecs:
                        files = Utilities.direntries(self.ppath, True, filespec)
                        for file in files:
                            self.appendFile(file)
                        
                    # special handling for translation files (*.ts and *.qm)
                    if self.translationsRoot:
                        tpd = os.path.join(self.ppath, self.translationsRoot)
                        if not self.translationsRoot.endswith(os.sep):
                            tpd = os.path.dirname(tpd)
                    else:
                        tpd = self.ppath
                    d = QDir(tpd)
                    tslist = d.entryList(QStringList() << '*.ts' << '*.qm')
                    if len(tslist) and tslist[0].contains('_'):
                        # the first entry determines the filename pattern
                        mainscriptname = os.path.splitext(ms)[0] or \
                                         tslist[0].section('_', 0, 0)
                        tr = self.translationsRoot or mainscriptname
                        for ts in tslist:
                            if ts.startsWith(tr):
                                self.pdata["TRANSLATIONS"].append(str(ts))
                                self.emit(SIGNAL('projectLanguageAdded'), ts)
                        if self.pdata["PROGLANGUAGE"][0] == "Python":
                            self.pdata["MAINSCRIPT"] = ['%s.py' % unicode(mainscriptname)]
                        elif self.pdata["PROGLANGUAGE"][0] == "Ruby":
                            self.pdata["MAINSCRIPT"] = ['%s.rb' % unicode(mainscriptname)]
                        if not self.pdata["TRANSLATIONPREFIX"]:
                            self.pdata["TRANSLATIONPREFIX"] = [tr]
                        if self.pdata["TRANSLATIONSBINPATH"]:
                            tpd = os.path.join(self.ppath, 
                                               self.pdata["TRANSLATIONSBINPATH"][0])
                            d2 = QDir(tpd)
                            qmlist = d2.entryList(QStringList() << '*.qm')
                            for qm in qmlist:
                                self.pdata["TRANSLATIONS"].append(str(qm))
                                self.emit(SIGNAL('projectLanguageAdded'), qm)
                    self.setDirty(True)
                self.saveProject()
                
                # check, if the existing project directory is already under
                # VCS control
                for vcsSystem, indicator in ConfigVcsSystemIndicators:
                    if os.path.exists(os.path.join(self.ppath, indicator)):
                        self.pdata["VCS"] = [vcsSystem]
                        self.vcs = self.initVCS()
                        self.setDirty(True)
                        if self.vcs is not None:
                            # edit VCS command options
                            vcores = KQMessageBox.question(None,
                                self.trUtf8("New Project"),
                                self.trUtf8("""Would you like to edit the VCS"""
                                    """ command options?"""),
                                QMessageBox.StandardButtons(\
                                    QMessageBox.No | \
                                    QMessageBox.Yes),
                                QMessageBox.No)
                            if vcores == QMessageBox.Yes:
                                codlg = vcsCommandOptionsDialog(self.vcs)
                                if codlg.exec_() == QDialog.Accepted:
                                    self.vcs.vcsSetOptions(codlg.getOptions())
                            # add project file to repository
                            if res == 0:
                                apres = KQMessageBox.question(None,
                                    self.trUtf8("New project"),
                                    self.trUtf8("Shall the project file be added"
                                        " to the repository?"),
                                    QMessageBox.StandardButtons(\
                                        QMessageBox.No | \
                                        QMessageBox.Yes),
                                    QMessageBox.Yes)
                                if apres == QMessageBox.Yes:
                                    self.saveProject()
                                    self.vcs.vcsAdd(self.pfile)
                        else:
                            self.pdata["VCS"] = ['None']
                        self.saveProject()
                        break
                
            # put the project under VCS control
            if self.vcs is None:
                vcsSelected, ok = KQInputDialog.getItem(\
                    None,
                    self.trUtf8("New Project"),
                    self.trUtf8("Select version control system for the project"),
                    ConfigVcsSystemsDisplay,
                    0, False)
                vcsSystem = ConfigVcsSystems[\
                            ConfigVcsSystemsDisplay.indexOf(vcsSelected)]
                if ok:
                    self.pdata["VCS"] = [vcsSystem]
                else:
                    self.pdata["VCS"] = ['None']
                self.vcs = self.initVCS()
                if self.vcs is not None:
                    vcsdlg = self.vcs.vcsOptionsDialog(self, self.name)
                    if vcsdlg.exec_() == QDialog.Accepted:
                        vcsDataDict = vcsdlg.getData()
                    else:
                        self.pdata["VCS"] = ['None']
                        self.vcs = self.initVCS()
                self.setDirty(True)
                if self.vcs is not None:
                    # edit VCS command options
                    vcores = KQMessageBox.question(None,
                        self.trUtf8("New Project"),
                        self.trUtf8("""Would you like to edit the VCS command"""
                                    """ options?"""),
                        QMessageBox.StandardButtons(\
                            QMessageBox.No | \
                            QMessageBox.Yes),
                        QMessageBox.No)
                    if vcores == QMessageBox.Yes:
                        codlg = vcsCommandOptionsDialog(self.vcs)
                        if codlg.exec_() == QDialog.Accepted:
                            self.vcs.vcsSetOptions(codlg.getOptions())
                    
                    # create the project in the VCS
                    self.vcs.vcsSetDataFromDict(vcsDataDict)
                    self.saveProject()
                    self.vcs.vcsConvertProject(vcsDataDict, self)
                else:
                    self.emit(SIGNAL('newProject'))
            
            else:
                self.emit(SIGNAL('newProject'))
    
    def __showProperties(self):
        """
        Private slot to display the properties dialog.
        """
        dlg = PropertiesDialog(self, False)
        if dlg.exec_() == QDialog.Accepted:
            dlg.storeData()
            self.setDirty(True)
            try:
                ms = os.path.join(self.ppath, self.pdata["MAINSCRIPT"][0])
                if os.path.exists(ms):
                    self.appendFile(ms)
            except IndexError:
                pass
            
            if self.translationsRoot:
                tp = os.path.join(self.ppath, self.translationsRoot)
                if not self.translationsRoot.endswith(os.sep):
                    tp = os.path.dirname(tp)
            else:
                tp = self.ppath
            if not os.path.isdir(tp):
                os.makedirs(tp)
            if tp != self.ppath and tp not in self.subdirs:
                self.subdirs.append(tp)
            
            if self.pdata["TRANSLATIONSBINPATH"]:
                tp = os.path.join(self.ppath, self.pdata["TRANSLATIONSBINPATH"][0])
                if not os.path.isdir(tp):
                    os.makedirs(tp)
                if tp != self.ppath and tp not in self.subdirs:
                    self.subdirs.append(tp)
            
            self.__model.projectPropertiesChanged()
            self.emit(SIGNAL('projectPropertiesChanged'))
        
    def __showUserProperties(self):
        """
        Private slot to display the user specific properties dialog.
        """
        vcsSystem = self.pdata["VCS"] and self.pdata["VCS"][0] or None
        vcsSystemOverride = \
            self.pudata["VCSOVERRIDE"] and self.pudata["VCSOVERRIDE"][0] or None
        
        dlg = UserPropertiesDialog(self)
        if dlg.exec_() == QDialog.Accepted:
            dlg.storeData()
            
            if (self.pdata["VCS"] and \
                self.pdata["VCS"][0] != vcsSystem) or \
               (self.pudata["VCSOVERRIDE"] and \
                self.pudata["VCSOVERRIDE"][0] != vcsSystemOverride) or \
               (vcsSystemOverride is not None and \
                len(self.pudata["VCSOVERRIDE"]) == 0):
                # stop the VCS monitor thread
                if self.vcs is not None:
                    self.vcsProjectHelper.stopStatusMonitor()
                    self.disconnect(self.vcsProjectHelper, 
                        SIGNAL("vcsStatusMonitorData(QStringList)"),
                        self.__model.changeVCSStates)
                    self.disconnect(self.vcsProjectHelper, 
                        SIGNAL("vcsStatusMonitorStatus(QString, QString)"),
                        self.__statusMonitorStatus)
                # reinit VCS
                self.vcs = self.initVCS()
                # start the VCS monitor thread
                if self.vcs is not None:
                    monitor = self.vcsProjectHelper.startStatusMonitor()
                    self.connect(self.vcsProjectHelper, 
                         SIGNAL("vcsStatusMonitorData(QStringList)"),
                         self.__model.changeVCSStates)
                    self.connect(self.vcsProjectHelper, 
                         SIGNAL("vcsStatusMonitorStatus(QString, QString)"),
                         self.__statusMonitorStatus)
                self.emit(SIGNAL("reinitVCS"))
            
            if self.pudata["VCSSTATUSMONITORINTERVAL"]:
                self.vcsProjectHelper.setStatusMonitorInterval(\
                    self.pudata["VCSSTATUSMONITORINTERVAL"][0])
            else:
                self.vcsProjectHelper.setStatusMonitorInterval(\
                    Preferences.getVCS("StatusMonitorInterval"))
        
    def __showFiletypeAssociations(self):
        """
        Public slot to display the filetype association dialog.
        """
        dlg = FiletypeAssociationDialog(self)
        if dlg.exec_() == QDialog.Accepted:
            dlg.transferData()
            self.setDirty(True)
        
    def checkSecurityString(self, stringToCheck, tag):
        """
        Public method to check a string for security problems.
        
        @param stringToCheck string that should be checked for security problems (string)
        @param tag tag that contained the string (string)
        @return flag indicating a security problem (boolean)
        """
        for r in self.__class__.securityCheckPatterns:
            if r.search(stringToCheck):
                KQMessageBox.warning(None,
                    self.trUtf8("Security Problem"),
                    self.trUtf8("""<p>The <b>%1</b> entry of the project file contains"""
                                """ a security problem.</p>""")\
                        .arg(key))
                return True
        return False
        
    def openProject(self, fn = None):
        """
        Public slot to open a project.
        
        @param fn optional filename of the project file to be read
        """
        if not self.checkDirty():
            return
        
        if fn is None:
            fn = KQFileDialog.getOpenFileName(\
                self.parent(),
                self.trUtf8("Open project"),
                QString(),
                self.trUtf8("Project Files (*.e4p *.e4pz *.e3p *.e3pz)"))
            
            if fn.isEmpty():
                fn = None
            else:
                fn = unicode(fn)
        
        QApplication.processEvents()
        
        if fn is not None:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            QApplication.processEvents()
            self.closeProject()
            if self.__readProject(fn):
                self.opened = True
                if not self.pdata["FILETYPES"]:
                    self.__initFileTypes()
                
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()
                
                # read a user specific project file
                self.__readUserProperties()
                
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                
                self.vcs = self.initVCS()
                if self.vcs is None:
                    # check, if project is version controlled
                    for vcsSystem, indicator in ConfigVcsSystemIndicators:
                        if os.path.exists(os.path.join(self.ppath, indicator)):
                            self.pdata["VCS"] = [vcsSystem]
                            self.vcs = self.initVCS()
                            self.setDirty(True)
                if self.vcs is not None and \
                   self.vcs.vcsRegisteredState(self.ppath) != self.vcs.canBeCommitted:
                    self.pdata["VCS"] = ['None']
                    self.vcs = self.initVCS()
                self.closeAct.setEnabled(True)
                self.saveasAct.setEnabled(True)
                self.actGrp2.setEnabled(True)
                self.propsAct.setEnabled(True)
                self.userPropsAct.setEnabled(True)
                self.filetypesAct.setEnabled(True)
                self.sessActGrp.setEnabled(True)
                self.dbgActGrp.setEnabled(True)
                self.menuDebuggerAct.setEnabled(True)
                self.menuSessionAct.setEnabled(True)
                self.menuCheckAct.setEnabled(True)
                self.menuShowAct.setEnabled(True)
                self.menuDiagramAct.setEnabled(True)
                self.menuApidocAct.setEnabled(True)
                self.menuPackagersAct.setEnabled(True)
                
                self.__model.projectOpened()
                self.emit(SIGNAL('projectOpened'))
                
                QApplication.restoreOverrideCursor()
                
                if Preferences.getProject("SearchNewFiles"):
                    self.__doSearchNewFiles()
                
                # read a project tasks file
                self.__readTasks()
                self.ui.taskViewer.setProjectOpen(True)
                
                # open the main script
                if len(self.pdata["MAINSCRIPT"]) == 1:
                    self.emit(SIGNAL('sourceFile'), 
                        os.path.join(self.ppath, self.pdata["MAINSCRIPT"][0]))
                
                # open a project session file being quiet about errors
                if Preferences.getProject("AutoLoadSession"):
                    self.__readSession(True)
                
                # open a project debugger properties file being quiet about errors
                if Preferences.getProject("AutoLoadDbgProperties"):
                    self.__readDebugProperties(True)
                
                # start the VCS monitor thread
                if self.vcs is not None:
                    monitor = self.vcsProjectHelper.startStatusMonitor()
                    self.connect(self.vcsProjectHelper, 
                         SIGNAL("vcsStatusMonitorData(QStringList)"),
                         self.__model.changeVCSStates)
                    self.connect(self.vcsProjectHelper, 
                         SIGNAL("vcsStatusMonitorStatus(QString, QString)"),
                         self.__statusMonitorStatus)
            else:
                QApplication.restoreOverrideCursor()
        
    def saveProject(self):
        """
        Public slot to save the current project.
        
        @return flag indicating success
        """
        if self.isDirty():
            if len(self.pfile) > 0:
                if self.pfile.endswith("e3pz") or self.pfile.endswith("e3p"):
                    ok = self.saveProjectAs()
                else:
                    ok = self.__writeProject()
            else:
                ok = self.saveProjectAs()
        else:
            ok = True
        self.sessActGrp.setEnabled(ok)
        self.menuSessionAct.setEnabled(ok)
        return ok
        
    def saveProjectAs(self):
        """
        Public slot to save the current project to a different file.
        
        @return flag indicating success
        """
        if Preferences.getProject("CompressedProjectFiles"):
            selectedFilter = self.trUtf8("Compressed Project Files (*.e4pz)")
        else:
            selectedFilter = self.trUtf8("Project Files (*.e4p)")
        fn = KQFileDialog.getSaveFileName(\
            self.parent(),
            self.trUtf8("Save project as"),
            self.ppath,
            self.trUtf8("Project Files (*.e4p);;"
                "Compressed Project Files (*.e4pz)"),
            selectedFilter,
            QFileDialog.Options(QFileDialog.DontConfirmOverwrite))
        
        if not fn.isEmpty():
            ext = QFileInfo(fn).suffix()
            if ext.isEmpty():
                ex = selectedFilter.section('(*', 1, 1).section(')', 0, 0)
                if not ex.isEmpty():
                    fn.append(ex)
            if QFileInfo(fn).exists():
                res = KQMessageBox.warning(None,
                    self.trUtf8("Save File"),
                    self.trUtf8("""<p>The file <b>%1</b> already exists.</p>""")
                        .arg(fn),
                    QMessageBox.StandardButtons(\
                        QMessageBox.Abort | \
                        QMessageBox.Save),
                    QMessageBox.Abort)
                if res != QMessageBox.Save:
                    return False
                
            self.name = unicode(QFileInfo(fn).baseName())
            ok = self.__writeProject(unicode(fn))
            
            if ok:
                # now save the tasks
                self.__writeTasks()
            
            self.sessActGrp.setEnabled(ok)
            self.menuSessionAct.setEnabled(ok)
            self.emit(SIGNAL('projectClosed'))
            self.emit(SIGNAL('projectOpened'))
            return True
        else:
            return False
    
    def checkDirty(self):
        """
        Public method to check dirty status and open a message window.
        
        @return flag indicating whether this operation was successful
        """
        if self.isDirty():
            res = KQMessageBox.warning(self.parent(), 
                self.trUtf8("Close Project"),
                self.trUtf8("The current project has unsaved changes."),
                QMessageBox.StandardButtons(\
                    QMessageBox.Abort | \
                    QMessageBox.Discard | \
                    QMessageBox.Save),
                QMessageBox.Save)
            if res == QMessageBox.Save:
                return self.saveProject()
            elif res == QMessageBox.Discard:
                self.setDirty(False)
                return True
            elif res == QMessageBox.Abort:
                return False
            
        return True
        
    def __closeAllWindows(self):
        """
        Private method to close all project related windows.
        """
        self.codemetrics        and self.codemetrics.close()
        self.codecoverage       and self.codecoverage.close()
        self.profiledata        and self.profiledata.close()
        self.checkers.closeAllWindows()
        self.applicationDiagram and self.applicationDiagram.close()
        
    def closeProject(self):
        """
        Public slot to close the current project.
        
        @return flag indicating success (boolean)
        """
        # save the list of recently opened projects
        self.__saveRecent()
        
        if not self.isOpen():
            return True
            
        if not self.checkDirty():
            return False
        
        # stop the VCS monitor thread
        if self.vcs is not None:
            self.vcsProjectHelper.stopStatusMonitor()
            self.disconnect(self.vcsProjectHelper, 
                SIGNAL("vcsStatusMonitorData(QStringList)"),
                self.__model.changeVCSStates)
            self.disconnect(self.vcsProjectHelper, 
                SIGNAL("vcsStatusMonitorStatus(QString, QString)"),
                self.__statusMonitorStatus)
        
        # save the user project properties
        self.__writeUserProperties()
        
        # save the project session file being quiet about error
        if Preferences.getProject("AutoSaveSession"):
            self.__writeSession(True)
        
        # save the project debugger properties file being quiet about error
        if Preferences.getProject("AutoSaveDbgProperties") and \
           self.isDebugPropertiesLoaded():
            self.__writeDebugProperties(True)
        
        # now save all open modified files of the project
        vm = e4App().getObject("ViewManager")
        success = True
        for fn in vm.getOpenFilenames():
            rfn = fn.replace(self.ppath+os.sep, '') # make relativ to project
            if rfn in self.pdata["SOURCES"] or \
               rfn in self.pdata["INTERFACES"] or \
               rfn in self.pdata["RESOURCES"] or \
               rfn in self.pdata["OTHERS"]:
                success &= vm.closeWindow(fn)
        
        if not success:
            return False
        
        # now save the tasks
        self.__writeTasks()
        self.ui.taskViewer.clearProjectTasks()
        self.ui.taskViewer.setProjectOpen(False)
        
        # now shutdown the vcs interface
        self.vcs and self.vcs.vcsShutdown()
        
        # now close all project related windows
        self.__closeAllWindows()
        
        self.__initData()
        self.closeAct.setEnabled(False)
        self.saveasAct.setEnabled(False)
        self.saveAct.setEnabled(False)
        self.actGrp2.setEnabled(False)
        self.propsAct.setEnabled(False)
        self.userPropsAct.setEnabled(False)
        self.filetypesAct.setEnabled(False)
        self.sessActGrp.setEnabled(False)
        self.dbgActGrp.setEnabled(False)
        self.menuDebuggerAct.setEnabled(False)
        self.menuSessionAct.setEnabled(False)
        self.menuCheckAct.setEnabled(False)
        self.menuShowAct.setEnabled(False)
        self.menuDiagramAct.setEnabled(False)
        self.menuApidocAct.setEnabled(False)
        self.menuPackagersAct.setEnabled(False)
        
        self.__model.projectClosed()
        self.emit(SIGNAL('projectClosed'))
        
        return True

    def saveAllScripts(self, reportSyntaxErrors = False):
        """
        Public method to save all scripts belonging to the project.
        
        @keyparam reportSyntaxErrors flag indicating special reporting
            for syntax errors (boolean)
        @return flag indicating success
        """
        vm = e4App().getObject("ViewManager")
        success = True
        filesWithSyntaxErrors = 0
        for fn in vm.getOpenFilenames():
            rfn = fn.replace(self.ppath+os.sep, '') # make relativ to project
            if rfn in self.pdata["SOURCES"] or rfn in self.pdata["OTHERS"]:
                editor = vm.getOpenEditor(fn)
                success &= vm.saveEditorEd(editor)
                if reportSyntaxErrors and editor.hasSyntaxErrors():
                    filesWithSyntaxErrors += 1
        
        if reportSyntaxErrors and filesWithSyntaxErrors > 0:
            KQMessageBox.critical(None,
                self.trUtf8("Syntax errors detected"),
                self.trUtf8("""The project contains %n file(s) with syntax errors.""",
                    "", filesWithSyntaxErrors)
            )
            return False
        else:
            return success
        
    def getMainScript(self, normalized = False):
        """
        Public method to return the main script filename.
        
        @param normalized flag indicating a normalized filename is wanted (boolean)
        @return filename of the projects main script (string)
        """
        if len(self.pdata["MAINSCRIPT"]):
            if normalized:
                return os.path.join(self.ppath, self.pdata["MAINSCRIPT"][0])
            else:
                return self.pdata["MAINSCRIPT"]
        else:
            return None
        
    def getSources(self, normalized = False):
        """
        Public method to return the source script files.
        
        @param normalized flag indicating a normalized filename is wanted (boolean)
        @return list of the projects scripts (list of string)
        """
        if normalized:
            return [os.path.join(self.ppath, fn) for fn in self.pdata["SOURCES"]]
        else:
            return self.pdata["SOURCES"]
        
    def getUiType(self):
        """
        Public method to get the UI type of the project.
        
        @return UI type of the project (string)
        """
        return self.pdata["UITYPE"][0]
        
    def getProjectLanguage(self):
        """
        Public method to get the project's programming language.
        
        @return programming language (string)
        """
        return self.pdata["PROGLANGUAGE"][0]
        
    def getDefaultSourceExtension(self):
        """
        Public method to get the default extension for the project's
        programming language.
        
        @return default extension (including the dot) (string)
        """
        if self.pdata["PROGLANGUAGE"]:
            return self.sourceExtensions[self.pdata["PROGLANGUAGE"][0]][0]
        else:
            return ""
        
    def getProjectPath(self):
        """
        Public method to get the project path.
        
        @return project path (string)
        """
        return self.ppath
        
    def isProjectSource(self, fn):
        """
        Public method used to check, if the passed in filename belongs to the project
        sources.
        
        @param fn filename to be checked (string or QString)
        @return flag indicating membership (boolean)
        """
        newfn = os.path.abspath(unicode(fn))
        newfn = newfn.replace(self.ppath + os.sep, '')
        return newfn in self.pdata["SOURCES"]
        
    def isProjectForm(self, fn):
        """
        Public method used to check, if the passed in filename belongs to the project
        forms.
        
        @param fn filename to be checked (string or QString)
        @return flag indicating membership (boolean)
        """
        newfn = os.path.abspath(unicode(fn))
        newfn = newfn.replace(self.ppath + os.sep, '')
        return newfn in self.pdata["FORMS"]
        
    def isProjectInterface(self, fn):
        """
        Public method used to check, if the passed in filename belongs to the project
        interfaces.
        
        @param fn filename to be checked (string or QString)
        @return flag indicating membership (boolean)
        """
        newfn = os.path.abspath(unicode(fn))
        newfn = newfn.replace(self.ppath + os.sep, '')
        return newfn in self.pdata["INTERFACES"]
        
    def isProjectResource(self, fn):
        """
        Public method used to check, if the passed in filename belongs to the project
        resources.
        
        @param fn filename to be checked (string or QString)
        @return flag indicating membership (boolean)
        """
        newfn = os.path.abspath(unicode(fn))
        newfn = newfn.replace(self.ppath + os.sep, '')
        return newfn in self.pdata["RESOURCES"]
        
    def initActions(self):
        """
        Public slot to initialize the project related actions.
        """
        self.actions = []
        
        self.actGrp1 = E4ActionGroup(self)
        
        act = E4Action(self.trUtf8('New project'),
                UI.PixmapCache.getIcon("projectNew.png"),
                self.trUtf8('&New...'), 0, 0,
                self.actGrp1,'project_new')
        act.setStatusTip(self.trUtf8('Generate a new project'))
        act.setWhatsThis(self.trUtf8(
            """<b>New...</b>"""
            """<p>This opens a dialog for entering the info for a"""
            """ new project.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.newProject)
        self.actions.append(act)

        act = E4Action(self.trUtf8('Open project'),
                UI.PixmapCache.getIcon("projectOpen.png"),
                self.trUtf8('&Open...'), 0, 0,
                self.actGrp1,'project_open')
        act.setStatusTip(self.trUtf8('Open an existing project'))
        act.setWhatsThis(self.trUtf8(
            """<b>Open...</b>"""
            """<p>This opens an existing project.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.openProject)
        self.actions.append(act)

        self.closeAct = E4Action(self.trUtf8('Close project'),
                UI.PixmapCache.getIcon("projectClose.png"),
                self.trUtf8('&Close'), 0, 0, self, 'project_close')
        self.closeAct.setStatusTip(self.trUtf8('Close the current project'))
        self.closeAct.setWhatsThis(self.trUtf8(
            """<b>Close</b>"""
            """<p>This closes the current project.</p>"""
        ))
        self.closeAct.connectIt(SIGNAL('triggered()'),self.closeProject)
        self.actions.append(self.closeAct)

        self.saveAct = E4Action(self.trUtf8('Save project'),
                UI.PixmapCache.getIcon("projectSave.png"),
                self.trUtf8('&Save'), 0, 0, self, 'project_save')
        self.saveAct.setStatusTip(self.trUtf8('Save the current project'))
        self.saveAct.setWhatsThis(self.trUtf8(
            """<b>Save</b>"""
            """<p>This saves the current project.</p>"""
        ))
        self.saveAct.connectIt(SIGNAL('triggered()'), self.saveProject)
        self.actions.append(self.saveAct)

        self.saveasAct = E4Action(self.trUtf8('Save project as'),
                UI.PixmapCache.getIcon("projectSaveAs.png"),
                self.trUtf8('Save &as...'), 0, 0, self, 'project_save_as')
        self.saveasAct.setStatusTip(self.trUtf8('Save the current project to a new file'))
        self.saveasAct.setWhatsThis(self.trUtf8(
            """<b>Save as</b>"""
            """<p>This saves the current project to a new file.</p>"""
        ))
        self.saveasAct.connectIt(SIGNAL('triggered()'), self.saveProjectAs)
        self.actions.append(self.saveasAct)

        self.actGrp2 = E4ActionGroup(self)
        
        act = E4Action(self.trUtf8('Add files to project'),
                UI.PixmapCache.getIcon("fileMisc.png"),
                self.trUtf8('Add &files...'), 0, 0,
                self.actGrp2,'project_add_file')
        act.setStatusTip(self.trUtf8('Add files to the current project'))
        act.setWhatsThis(self.trUtf8(
            """<b>Add files...</b>"""
            """<p>This opens a dialog for adding files"""
            """ to the current project. The place to add is"""
            """ determined by the file extension.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.addFiles)
        self.actions.append(act)

        act = E4Action(self.trUtf8('Add directory to project'),
                UI.PixmapCache.getIcon("dirOpen.png"),
                self.trUtf8('Add directory...'), 0, 0,
                self.actGrp2,'project_add_directory')
        act.setStatusTip(self.trUtf8('Add a directory to the current project'))
        act.setWhatsThis(self.trUtf8(
            """<b>Add directory...</b>"""
            """<p>This opens a dialog for adding a directory"""
            """ to the current project.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.addDirectory)
        self.actions.append(act)

        act = E4Action(self.trUtf8('Add translation to project'),
                UI.PixmapCache.getIcon("linguist.png"),
                self.trUtf8('Add &translation...'), 0, 0,
                self.actGrp2,'project_add_translation')
        act.setStatusTip(self.trUtf8('Add a translation to the current project'))
        act.setWhatsThis(self.trUtf8(
            """<b>Add translation...</b>"""
            """<p>This opens a dialog for add a translation"""
            """ to the current project.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.addLanguage)
        self.actions.append(act)

        act = E4Action(self.trUtf8('Search new files'),
                self.trUtf8('Searc&h new files...'), 0, 0,
                self.actGrp2,'project_search_new_files')
        act.setStatusTip(self.trUtf8('Search new files in the project directory.'))
        act.setWhatsThis(self.trUtf8(
            """<b>Search new files...</b>"""
            """<p>This searches for new files (sources, *.ui, *.idl) in the project"""
            """ directory and registered subdirectories.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__searchNewFiles)
        self.actions.append(act)

        self.propsAct = E4Action(self.trUtf8('Project properties'),
                UI.PixmapCache.getIcon("projectProps.png"),
                self.trUtf8('&Properties...'), 0, 0, self, 'project_properties')
        self.propsAct.setStatusTip(self.trUtf8('Show the project properties'))
        self.propsAct.setWhatsThis(self.trUtf8(
            """<b>Properties...</b>"""
            """<p>This shows a dialog to edit the project properties.</p>"""
        ))
        self.propsAct.connectIt(SIGNAL('triggered()'), self.__showProperties)
        self.actions.append(self.propsAct)

        self.userPropsAct = E4Action(self.trUtf8('User project properties'),
                UI.PixmapCache.getIcon("projectUserProps.png"),
                self.trUtf8('&User Properties...'), 0, 0, self, 'project_user_properties')
        self.userPropsAct.setStatusTip(self.trUtf8(
            'Show the user specific project properties'))
        self.userPropsAct.setWhatsThis(self.trUtf8(
            """<b>User Properties...</b>"""
            """<p>This shows a dialog to edit the user specific project properties.</p>"""
        ))
        self.userPropsAct.connectIt(SIGNAL('triggered()'), self.__showUserProperties)
        self.actions.append(self.userPropsAct)

        self.filetypesAct = E4Action(self.trUtf8('Filetype Associations'),
                self.trUtf8('Filetype Associations...'), 0, 0,
                self, 'project_filetype_associatios')
        self.filetypesAct.setStatusTip(\
            self.trUtf8('Show the project filetype associations'))
        self.filetypesAct.setWhatsThis(self.trUtf8(
            """<b>Filetype Associations...</b>"""
            """<p>This shows a dialog to edit the filetype associations of the project."""
            """ These associations determine the type (source, form, interface"""
            """ or others) with a filename pattern. They are used when adding a file"""
            """ to the project and when performing a search for new files.</p>"""
        ))
        self.filetypesAct.connectIt(SIGNAL('triggered()'), 
                                    self.__showFiletypeAssociations)
        self.actions.append(self.filetypesAct)

        self.dbgActGrp = E4ActionGroup(self)
        
        act = E4Action(self.trUtf8('Debugger Properties'),
                self.trUtf8('Debugger &Properties...'), 0, 0,
                self.dbgActGrp, 'project_debugger_properties')
        act.setStatusTip(self.trUtf8('Show the debugger properties'))
        act.setWhatsThis(self.trUtf8(
            """<b>Debugger Properties...</b>"""
            """<p>This shows a dialog to edit project specific debugger settings.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__showDebugProperties)
        self.actions.append(act)
        
        act = E4Action(self.trUtf8('Load'),
                self.trUtf8('&Load'), 0, 0,
                self.dbgActGrp, 'project_debugger_properties_load')
        act.setStatusTip(self.trUtf8('Load the debugger properties'))
        act.setWhatsThis(self.trUtf8(
            """<b>Load Debugger Properties</b>"""
            """<p>This loads the project specific debugger settings.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__readDebugProperties)
        self.actions.append(act)
        
        act = E4Action(self.trUtf8('Save'),
                self.trUtf8('&Save'), 0, 0,
                self.dbgActGrp, 'project_debugger_properties_save')
        act.setStatusTip(self.trUtf8('Save the debugger properties'))
        act.setWhatsThis(self.trUtf8(
            """<b>Save Debugger Properties</b>"""
            """<p>This saves the project specific debugger settings.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__writeDebugProperties)
        self.actions.append(act)
        
        act = E4Action(self.trUtf8('Delete'),
                self.trUtf8('&Delete'), 0, 0,
                self.dbgActGrp, 'project_debugger_properties_delete')
        act.setStatusTip(self.trUtf8('Delete the debugger properties'))
        act.setWhatsThis(self.trUtf8(
            """<b>Delete Debugger Properties</b>"""
            """<p>This deletes the file containing the project specific"""
            """ debugger settings.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__deleteDebugProperties)
        self.actions.append(act)
        
        act = E4Action(self.trUtf8('Reset'),
                self.trUtf8('&Reset'), 0, 0,
                self.dbgActGrp, 'project_debugger_properties_resets')
        act.setStatusTip(self.trUtf8('Reset the debugger properties'))
        act.setWhatsThis(self.trUtf8(
            """<b>Reset Debugger Properties</b>"""
            """<p>This resets the project specific debugger settings.</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__initDebugProperties)
        self.actions.append(act)
        
        self.sessActGrp = E4ActionGroup(self)

        act = E4Action(self.trUtf8('Load session'),
                self.trUtf8('Load session'), 0, 0,
                self.sessActGrp, 'project_load_session')
        act.setStatusTip(self.trUtf8('Load the projects session file.'))
        act.setWhatsThis(self.trUtf8(
            """<b>Load session</b>"""
            """<p>This loads the projects session file. The session consists"""
            """ of the following data.<br>"""
            """- all open source files<br>"""
            """- all breakpoint<br>"""
            """- the commandline arguments<br>"""
            """- the working directory<br>"""
            """- the exception reporting flag</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__readSession)
        self.actions.append(act)

        act = E4Action(self.trUtf8('Save session'),
                self.trUtf8('Save session'), 0, 0,
                self.sessActGrp, 'project_save_session')
        act.setStatusTip(self.trUtf8('Save the projects session file.'))
        act.setWhatsThis(self.trUtf8(
            """<b>Save session</b>"""
            """<p>This saves the projects session file. The session consists"""
            """ of the following data.<br>"""
            """- all open source files<br>"""
            """- all breakpoint<br>"""
            """- the commandline arguments<br>"""
            """- the working directory<br>"""
            """- the exception reporting flag</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__writeSession)
        self.actions.append(act)
        
        act = E4Action(self.trUtf8('Delete session'),
                self.trUtf8('Delete session'), 0, 0,
                self.sessActGrp, 'project_delete_session')
        act.setStatusTip(self.trUtf8('Delete the projects session file.'))
        act.setWhatsThis(self.trUtf8(
            """<b>Delete session</b>"""
            """<p>This deletes the projects session file</p>"""
        ))
        act.connectIt(SIGNAL('triggered()'), self.__deleteSession)
        self.actions.append(act)
        
        self.chkGrp = E4ActionGroup(self)

        self.codeMetricsAct = E4Action(self.trUtf8('Code Metrics'),
                self.trUtf8('&Code Metrics...'), 0, 0,
                self.chkGrp,'project_code_metrics')
        self.codeMetricsAct.setStatusTip(\
            self.trUtf8('Show some code metrics for the project.'))
        self.codeMetricsAct.setWhatsThis(self.trUtf8(
            """<b>Code Metrics...</b>"""
            """<p>This shows some code metrics for all Python files in the project.</p>"""
        ))
        self.codeMetricsAct.connectIt(SIGNAL('triggered()'), self.__showCodeMetrics)
        self.actions.append(self.codeMetricsAct)

        self.codeCoverageAct = E4Action(self.trUtf8('Python Code Coverage'),
                self.trUtf8('Code Co&verage...'), 0, 0,
                self.chkGrp,'project_code_coverage')
        self.codeCoverageAct.setStatusTip(\
            self.trUtf8('Show code coverage information for the project.'))
        self.codeCoverageAct.setWhatsThis(self.trUtf8(
            """<b>Code Coverage...</b>"""
            """<p>This shows the code coverage information for all Python files"""
            """ in the project.</p>"""
        ))
        self.codeCoverageAct.connectIt(SIGNAL('triggered()'), self.__showCodeCoverage)
        self.actions.append(self.codeCoverageAct)

        self.codeProfileAct = E4Action(self.trUtf8('Profile Data'),
                self.trUtf8('&Profile Data...'), 0, 0,
                self.chkGrp,'project_profile_data')
        self.codeProfileAct.setStatusTip(\
            self.trUtf8('Show profiling data for the project.'))
        self.codeProfileAct.setWhatsThis(self.trUtf8(
            """<b>Profile Data...</b>"""
            """<p>This shows the profiling data for the project.</p>"""
        ))
        self.codeProfileAct.connectIt(SIGNAL('triggered()'), self.__showProfileData)
        self.actions.append(self.codeProfileAct)

        self.codeCyclopsAct = E4Action(self.trUtf8('Cyclops Report'),
                self.trUtf8('Cyclops &Report...'), 0, 0,
                self.chkGrp,'project_cyclops_report')
        self.codeCyclopsAct.setStatusTip(\
            self.trUtf8('Show cyclops report for the project.'))
        self.codeCyclopsAct.setWhatsThis(self.trUtf8(
            """<b>Cyclops Report...</b>"""
            """<p>This shows the cyclops report for the project.</p>"""
        ))
        self.codeCyclopsAct.connectIt(SIGNAL('triggered()'), self.__showCyclopsReport)
        self.actions.append(self.codeCyclopsAct)

        self.removeCyclopsAct = E4Action(self.trUtf8('Remove Cyclops Report'),
                self.trUtf8('R&emove Cyclops Report'), 0, 0,
                self.chkGrp,'project_remove_cyclops_report')
        self.removeCyclopsAct.setStatusTip(\
            self.trUtf8('Remove cyclops report for the project.'))
        self.removeCyclopsAct.setWhatsThis(self.trUtf8(
            """<b>Remove Cyclops Report</b>"""
            """<p>This removes the cyclops report for the project.</p>"""
        ))
        self.removeCyclopsAct.connectIt(SIGNAL('triggered()'),
                                        self.__removeCyclopsReport)
        self.actions.append(self.removeCyclopsAct)

        self.applicationDiagramAct = E4Action(self.trUtf8('Application Diagram'),
                self.trUtf8('&Application Diagram...'), 0, 0,
                self.chkGrp,'project_application_diagram')
        self.applicationDiagramAct.setStatusTip(\
            self.trUtf8('Show a diagram of the project.'))
        self.applicationDiagramAct.setWhatsThis(self.trUtf8(
            """<b>Application Diagram...</b>"""
            """<p>This shows a diagram of the project.</p>"""
        ))
        self.applicationDiagramAct.connectIt(SIGNAL('triggered()'),
                                             self.handleApplicationDiagram)
        self.actions.append(self.applicationDiagramAct)

        self.closeAct.setEnabled(False)
        self.saveAct.setEnabled(False)
        self.saveasAct.setEnabled(False)
        self.actGrp2.setEnabled(False)
        self.propsAct.setEnabled(False)
        self.userPropsAct.setEnabled(False)
        self.filetypesAct.setEnabled(False)
        self.sessActGrp.setEnabled(False)
        self.dbgActGrp.setEnabled(False)
        
        self.doctools.initActions()
        self.packagers.initActions()
        self.checkers.initActions()
        
    def initMenu(self):
        """
        Public slot to initialize the project menu.
        
        @return the menu generated (QMenu)
        """
        menu = QMenu(self.trUtf8('&Project'), self.parent())
        self.recentMenu = QMenu(self.trUtf8('Open &Recent Projects'), menu)
        self.vcsMenu = QMenu(self.trUtf8('&Version Control'), menu)
        self.vcsMenu.setTearOffEnabled(True)
        self.vcsProjectHelper.initMenu(self.vcsMenu)
        self.checksMenu = self.checkers.initMenu()
        self.checksMenu.setTitle(self.trUtf8('Chec&k'))
        self.showMenu = QMenu(self.trUtf8('Sho&w'), menu)
        self.graphicsMenu = QMenu(self.trUtf8('&Diagrams'), menu)
        self.sessionMenu = QMenu(self.trUtf8('Session'), menu)
        self.apidocMenu = self.doctools.initMenu()
        self.apidocMenu.setTitle(self.trUtf8('Source &Documentation'))
        self.debuggerMenu = QMenu(self.trUtf8('Debugger'), menu)
        self.packagersMenu = self.packagers.initMenu()
        self.packagersMenu.setTitle(self.trUtf8('Pac&kagers'))
        
        # connect the aboutToShow signals
        self.connect(self.recentMenu, SIGNAL('aboutToShow()'), self.__showRecentMenu)
        self.connect(self.recentMenu, SIGNAL('triggered(QAction *)'),
                     self.__openRecent)
        self.connect(self.vcsMenu, SIGNAL('aboutToShow()'), self.__showVCSMenu)
        self.connect(self.showMenu, SIGNAL('aboutToShow()'), self.__showShowMenu)
        self.connect(menu, SIGNAL('aboutToShow()'), self.__showMenu)
        
        # build the show menu
        self.showMenu.setTearOffEnabled(True)
        self.codeMetricsAct.addTo(self.showMenu)
        self.codeCoverageAct.addTo(self.showMenu)
        self.codeProfileAct.addTo(self.showMenu)
        self.codeCyclopsAct.addTo(self.showMenu)
        self.removeCyclopsAct.addTo(self.showMenu)
        
        # build the diagrams menu
        self.graphicsMenu.setTearOffEnabled(True)
        self.applicationDiagramAct.addTo(self.graphicsMenu)
        
        # build the session menu
        self.sessionMenu.setTearOffEnabled(True)
        self.sessActGrp.addTo(self.sessionMenu)
        
        # build the debugger menu
        self.debuggerMenu.setTearOffEnabled(True)
        self.dbgActGrp.addTo(self.debuggerMenu)
        
        # build the main menu
        menu.setTearOffEnabled(True)
        self.actGrp1.addTo(menu)
        self.menuRecentAct = menu.addMenu(self.recentMenu)
        menu.addSeparator()
        self.closeAct.addTo(menu)
        menu.addSeparator()
        self.saveAct.addTo(menu)
        self.saveasAct.addTo(menu)
        menu.addSeparator()
        self.menuDebuggerAct = menu.addMenu(self.debuggerMenu)
        self.menuSessionAct = menu.addMenu(self.sessionMenu)
        menu.addSeparator()
        self.actGrp2.addTo(menu)
        menu.addSeparator()
        self.menuDiagramAct = menu.addMenu(self.graphicsMenu)
        menu.addSeparator()
        self.menuCheckAct = menu.addMenu(self.checksMenu)
        menu.addSeparator()
        menu.addMenu(self.vcsMenu)
        menu.addSeparator()
        self.menuShowAct = menu.addMenu(self.showMenu)
        menu.addSeparator()
        self.menuApidocAct = menu.addMenu(self.apidocMenu)
        menu.addSeparator()
        self.menuPackagersAct = menu.addMenu(self.packagersMenu)
        menu.addSeparator()
        self.propsAct.addTo(menu)
        self.userPropsAct.addTo(menu)
        self.filetypesAct.addTo(menu)
        
        self.menuCheckAct.setEnabled(False)
        self.menuShowAct.setEnabled(False)
        self.menuDiagramAct.setEnabled(False)
        self.menuSessionAct.setEnabled(False)
        self.menuDebuggerAct.setEnabled(False)
        self.menuApidocAct.setEnabled(False)
        self.menuPackagersAct.setEnabled(False)
        
        self.menu = menu
        return menu
        
    def initToolbar(self):
        """
        Public slot to initialize the project toolbar.
        
        @return the toolbar generated (QToolBar)
        """
        tb = QToolBar(self.trUtf8("Project"), self.parent())
        tb.setIconSize(UI.Config.ToolBarIconSize)
        tb.setObjectName("ProjectToolbar")
        tb.setToolTip(self.trUtf8('Project'))
        
        self.actGrp1.addTo(tb)
        self.closeAct.addTo(tb)
        tb.addSeparator()
        self.saveAct.addTo(tb)
        self.saveasAct.addTo(tb)
        tb.addSeparator()
        self.propsAct.addTo(tb)
        self.userPropsAct.addTo(tb)
        
        return tb
        
    def __showMenu(self):
        """
        Private method to set up the project menu.
        """
        self.menuRecentAct.setEnabled(len(self.recent) > 0)
        
    def __syncRecent(self):
        """
        Private method to synchronize the list of recently opened projects
        with the central store.
        """
        self.recent.removeAll(self.pfile)
        self.recent.prepend(self.pfile)
        if len(self.recent) > 9:
            self.recent = self.recent[:9]
        self.__saveRecent()
        
    def __showRecentMenu(self):
        """
        Private method to set up the recent projects menu.
        """
        self.__loadRecent()
        
        self.recentMenu.clear()
        
        idx = 1
        for rp in self.recent:
            act = self.recentMenu.addAction(\
                '&%d. %s' % (idx, 
                    compactpath.compactPath(unicode(rp), self.ui.maxMenuFilePathLen)))
            act.setData(QVariant(rp))
            act.setEnabled(QFileInfo(rp).exists())
            idx += 1
        
        self.recentMenu.addSeparator()
        self.recentMenu.addAction(self.trUtf8('&Clear'), self.__clearRecent)
        
    def __openRecent(self, act):
        """
        Private method to open a project from the list of rencently opened projects.
        
        @param act reference to the action that triggered (QAction)
        """
        file = unicode(act.data().toString())
        if file:
            self.openProject(file)
        
    def __clearRecent(self):
        """
        Private method to clear the recent projects menu.
        """
        self.recent.clear()
        
    def __searchNewFiles(self):
        """
        Private slot used to handle the search new files action.
        """
        self.__doSearchNewFiles(False, True)
        
    def __doSearchNewFiles(self, AI = True, onUserDemand = False):
        """
        Private method to search for new files in the project directory.
        
        If new files were found it shows a dialog listing these files and
        gives the user the oportunity to select the ones he wants to
        include. If 'Automatic Inclusion' is enabled, the new files are
        automatically added to the project.
        
        @param AI flag indicating whether the automatic inclusion should
                be honoured
        @param onUserDemand flag indicating whether this method was 
                requested by the user via a menu action
        """
        autoInclude = Preferences.getProject("AutoIncludeNewFiles")
        newFiles = QStringList()
        
        for dir in self.subdirs:
            curpath = os.path.join(self.ppath, dir)
            try:
                newSources = os.listdir(curpath)
            except OSError:
                newSources = []
            for ns in newSources:
                # set fn to project relative name
                # then reset ns to fully qualified name for insertion, possibly.
                if dir == "":
                    fn = ns
                else:
                    fn = os.path.join(dir, ns)
                ns = os.path.abspath(os.path.join(curpath, ns))
                
                # do not bother with dirs here...
                if os.path.isdir(ns):
                    continue
                
                filetype = ""
                bfn = os.path.basename(fn)
                for pattern in self.pdata["FILETYPES"].keys():
                    if fnmatch.fnmatch(bfn, pattern):
                        filetype = self.pdata["FILETYPES"][pattern]
                        break
                else:
                    if fnmatch.fnmatch(bfn, '*.ts') or fnmatch.fnmatch(bfn, '*.qm'):
                        filetype = "TRANSLATIONS"
                
                if (filetype == "SOURCES" and fn not in self.pdata["SOURCES"]) or \
                   (filetype == "FORMS" and fn not in self.pdata["FORMS"]) or \
                   (filetype == "INTERFACES" and fn not in self.pdata["INTERFACES"]) or \
                   (filetype == "RESOURCES" and fn not in self.pdata["RESOURCES"]) or \
                   (filetype == "OTHERS" and fn not in self.pdata["OTHERS"]):
                    if autoInclude and AI:
                        self.appendFile(ns)
                    else:
                        newFiles.append(ns)
                elif filetype == "TRANSLATIONS" and fn not in self.pdata["TRANSLATIONS"]:
                    if fn.startswith(self.translationsRoot):
                        if autoInclude and AI:
                            self.addLanguageFile(ns)
                        else:
                            newFiles.append(ns)
        
        # if autoInclude is set there is no more work left
        if (autoInclude and AI):
            return
        
        # if newfiles is empty, put up message box informing user nothing found
        if newFiles.isEmpty():
            if onUserDemand:
                KQMessageBox.information(None,
                    self.trUtf8("Search New Files"),
                    self.trUtf8("There were no new files found to be added."))
            return
            
        # autoInclude is not set, show a dialog
        dlg = AddFoundFilesDialog(newFiles, self.parent(), None)
        res = dlg.exec_()
        
        # the 'Add All' button was pressed
        if res == 1:
            for file in newFiles:
                file = unicode(file)
                if fnmatch.fnmatch(file, '*.ts') or fnmatch.fnmatch(file, '*.qm'):
                    self.addLanguageFile(file)
                else:
                    self.appendFile(file)
            
        # the 'Add Selected' button was pressed
        elif res == 2:
            files = dlg.getSelection()
            for file in files:
                file = unicode(file)
                if fnmatch.fnmatch(file, '*.ts') or fnmatch.fnmatch(file, '*.qm'):
                    self.addLanguageFile(file)
                else:
                    self.appendFile(file)
        
    def othersAdded(self, fn, updateModel = True):
        """
        Public slot to be called, if something was added to the OTHERS project data area.
        
        @param fn filename or directory name added (string or QString)
        @param updateModel flag indicating an update of the model is requested (boolean)
        """
        f = unicode(fn)
        self.emit(SIGNAL('projectOthersAdded'), f)
        updateModel and self.__model.addNewItem("OTHERS", fn)
        
    def getActions(self):
        """
        Public method to get a list of all actions.
        
        @return list of all actions (list of E4Action)
        """
        return self.actions[:] + \
               self.doctools.getActions() + \
               self.packagers.getActions() + \
               self.checkers.getActions()
        
    def repopulateItem(self, fullname):
        """
        Public slot to repopulate a named item.
        
        @param fullname full name of the item to repopulate (string or QString)
        """
        if not self.isOpen():
            return
        
        fullname = unicode(fullname)
        name = fullname.replace(self.ppath+os.sep, "")
        self.emit(SIGNAL("prepareRepopulateItem"), name)
        self.__model.repopulateItem(name)
        self.emit(SIGNAL("completeRepopulateItem"), name)
    
    ##############################################################
    ## Below is the VCS interface
    ##############################################################
    
    def initVCS(self, vcsSystem = None):
        """
        Public method used to instantiate a vcs system.
        
        @param vcsSystem type of VCS to be used
        @return a reference to the vcs object
        """
        vcs = None
        forProject = True
        
        if vcsSystem is None:
            if len(self.pdata["VCS"]):
                if self.pdata["VCS"][0] != 'None':
                    vcsSystem = self.pdata["VCS"][0]
        else:
            vcsSystem = str(vcsSystem)
            forProject = False
        
        if self.pdata["VCS"] and self.pdata["VCS"][0] != 'None':
            if self.pudata["VCSOVERRIDE"] and self.pudata["VCSOVERRIDE"][0] is not None:
                vcsSystem = self.pudata["VCSOVERRIDE"][0]
            
            svnOverride = Preferences.getVCS("SvnInterfaceGlobalOverride")
            if svnOverride == 1:
                vcsSystem = "Subversion"
            elif svnOverride == 2:
                vcsSystem = "PySvn"
        
        if vcsSystem is not None:
            try:
                vcs = VCS.factory(vcsSystem)
            except ImportError:
                pass
            
        if vcs and not vcs.vcsExists():
            QApplication.restoreOverrideCursor()
            KQMessageBox.critical(None,
                self.trUtf8("Version Control System"),
                self.trUtf8("<p>The selected VCS <b>%1</b> could not be found.<br>"
                    "Disabling version control.</p>").arg(self.pdata["VCS"][0]))
            vcs = None
            if forProject:
                self.pdata["VCS"][0] = 'None'
                self.setDirty(True)
            
        if vcs and forProject:
            # set the vcs options
            try:
                vcsopt = copy.deepcopy(self.pdata["VCSOPTIONS"][0])
                vcs.vcsSetOptions(vcsopt)
            except:
                pass
            # set vcs specific data
            try:
                vcsother = copy.deepcopy(self.pdata["VCSOTHERDATA"][0])
                vcs.vcsSetOtherData(vcsother)
            except:
                pass
            
        if vcs is None:
            self.vcsProjectHelper = VcsProjectHelper(None, self)
        else:
            self.vcsProjectHelper = vcs.vcsGetProjectHelper(self)
        if self.vcsMenu is not None:
            self.vcsProjectHelper.initMenu(self.vcsMenu)
        return vcs
        
    def __showVCSMenu(self):
        """
        Private slot called before the vcs menu is shown.
        """
        self.vcsProjectHelper.showMenu()
    
    #########################################################################
    ## Below is the interface to the checker tools
    #########################################################################
    
    def handleTabnanny(self):
        """
        Public slot used to check the project files for bad indentations.
        """
        self.saveAllScripts()
        files = [os.path.join(self.ppath, file) \
            for file in self.pdata["SOURCES"] \
                if file.endswith(".py") or \
                   file.endswith(".pyw") or \
                   file.endswith(".ptl")]
        self.checkers.tabnanny(files)
    
    def handleSyntaxCheck(self):
        """
        Public slot used to check the project files for bad syntax.
        """
        self.saveAllScripts()
        files = [os.path.join(self.ppath, file) \
            for file in self.pdata["SOURCES"] \
                if file.endswith(".py") or \
                   file.endswith(".pyw") or \
                   file.endswith(".ptl")]
        self.checkers.syntaxCheck(files)

    def handlePyLint(self):
        """
        Public slot used to check the project with pylint.
        """
        self.saveAllScripts()
        self.checkers.pyLint(self, self.ppath)

    #########################################################################
    ## Below is the interface to the show tools
    #########################################################################
    
    def __showCodeMetrics(self):
        """
        Private slot used to calculate some code metrics for the project files.
        """
        files = [os.path.join(self.ppath, file) \
            for file in self.pdata["SOURCES"] if file.endswith(".py")]
        self.codemetrics = CodeMetricsDialog()
        self.codemetrics.show()
        self.codemetrics.start(files)

    def __showCodeCoverage(self):
        """
        Private slot used to show the code coverage information for the project files.
        """
        fn = self.getMainScript(True)
        if fn is None:
            KQMessageBox.critical(self.ui,
                self.trUtf8("Coverage Data"),
                self.trUtf8("There is no main script defined for the"
                    " current project. Aborting"))
            return
        
        tfn = Utilities.getTestFileName(fn)
        basename = os.path.splitext(fn)[0]
        tbasename = os.path.splitext(tfn)[0]
        
        # determine name of coverage file to be used
        files = []
        f = "%s.coverage" % basename
        tf = "%s.coverage" % tbasename
        if os.path.isfile(f):
            files.append(f)
        if os.path.isfile(tf):
            files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    None,
                    self.trUtf8("Code Coverage"),
                    self.trUtf8("Please select a coverage file"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            return
        
        files = [os.path.join(self.ppath, file) \
            for file in self.pdata["SOURCES"] if file.endswith(".py")]
        self.codecoverage = PyCoverageDialog()
        self.codecoverage.show()
        self.codecoverage.start(fn, files)

    def __showProfileData(self):
        """
        Private slot used to show the profiling information for the project.
        """
        fn = self.getMainScript(True)
        if fn is None:
            KQMessageBox.critical(self.ui,
                self.trUtf8("Profile Data"),
                self.trUtf8("There is no main script defined for the"
                    " current project. Aborting"))
            return
        
        tfn = Utilities.getTestFileName(fn)
        basename = os.path.splitext(fn)[0]
        tbasename = os.path.splitext(tfn)[0]
        
        # determine name of profile file to be used
        files = []
        f = "%s.profile" % basename
        tf = "%s.profile" % tbasename
        if os.path.isfile(f):
            files.append(f)
        if os.path.isfile(tf):
            files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    None,
                    self.trUtf8("Profile Data"),
                    self.trUtf8("Please select a profile file"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            return
        
        self.profiledata = PyProfileDialog()
        self.profiledata.show()
        self.profiledata.start(fn)
        
    def __showCyclopsReport(self):
        """
        Private slot used to show the Cyclops report for the project.
        """
        fn = self.getMainScript(True)
        if fn is None:
            KQMessageBox.critical(self.ui,
                self.trUtf8("Cyclops Report"),
                self.trUtf8("There is no main script defined for the"
                    " current project. Aborting"))
            return
        
        files = []
        tfn = Utilities.getTestFileName(fn)
        basename = os.path.splitext(fn)[0]
        tbasename = os.path.splitext(tfn)[0]
        
        f = "%s.cycles.html" % basename
        tf = "%s.cycles.html" % tbasename
        if os.path.isfile(f):
            files.append(f)
        if os.path.isfile(tf):
            files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    None,
                    self.trUtf8("Cyclops Report"),
                    self.trUtf8("Please select a Cyclops report file"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            return
        
        self.parent().launchHelpViewer(fn)
        
    def __removeCyclopsReport(self):
        """
        Private slot used to remove the Cyclops report for the project.
        """
        fn = self.getMainScript(True)
        if fn is None:
            KQMessageBox.critical(self.ui,
                self.trUtf8("Remove Cyclops Report"),
                self.trUtf8("There is no main script defined for the"
                    " current project. Aborting"))
            return
        
        files = []
        tfn = Utilities.getTestFileName(fn)
        basename = os.path.splitext(fn)[0]
        tbasename = os.path.splitext(tfn)[0]
        
        f = "%s.cycles.html" % basename
        tf = "%s.cycles.html" % tbasename
        if os.path.isfile(f):
            files.append(f)
        if os.path.isfile(tf):
            files.append(tf)
        
        if files:
            if len(files) > 1:
                filelist = QStringList()
                for f in files:
                    filelist.append(f)
                fn, ok = KQInputDialog.getItem(\
                    None,
                    self.trUtf8("Remove Cyclops Report"),
                    self.trUtf8("Please select a Cyclops report file to be removed"),
                    filelist,
                    0, False)
                if not ok:
                    return
                fn = unicode(fn)
            else:
                fn = files[0]
        else:
            return
            
        if os.path.exists(fn):
            os.remove(fn)
        
    def __showShowMenu(self):
        """
        Private slot called before the show menu is shown.
        """
        fn = self.getMainScript(True)
        if fn is not None:
            tfn = Utilities.getTestFileName(fn)
            basename = os.path.splitext(fn)[0]
            tbasename = os.path.splitext(tfn)[0]
            self.codeProfileAct.setEnabled(\
                os.path.isfile("%s.profile" % basename) or \
                os.path.isfile("%s.profile" % tbasename))
            self.codeCoverageAct.setEnabled(\
                os.path.isfile("%s.coverage" % basename) or \
                os.path.isfile("%s.coverage" % tbasename))
            self.codeCyclopsAct.setEnabled(\
                os.path.isfile("%s.cycles.html" % basename) or \
                os.path.isfile("%s.cycles.html" % tbasename))
            self.removeCyclopsAct.setEnabled(\
                os.path.isfile("%s.cycles.html" % basename) or \
                os.path.isfile("%s.cycles.html" % tbasename))
        else:
            self.codeProfileAct.setEnabled(False)
            self.codeCoverageAct.setEnabled(False)
            self.codeCyclopsAct.setEnabled(False)
            self.removeCyclopsAct.setEnabled(False)
    
    #########################################################################
    ## Below is the interface to the diagrams
    #########################################################################
    
    def handleApplicationDiagram(self):
        """
        Private method to handle the application diagram context menu action.
        """
        res = KQMessageBox.question(None,
            self.trUtf8("Application Diagram"),
            self.trUtf8("""Include module names?"""),
            QMessageBox.StandardButtons(\
                QMessageBox.No | \
                QMessageBox.Yes),
            QMessageBox.Yes)

        self.applicationDiagram = ApplicationDiagram(self, self.parent(), 
            noModules = (res != QMessageBox.Yes))
        self.applicationDiagram.show()
    
    #########################################################################
    ## Below is the interface to the VCS monitor thread
    #########################################################################
    
    def __statusMonitorStatus(self, status, statusMsg):
        """
        Private method to receive the status monitor status.
        
        It simply reemits the received status.
        
        @param status status of the monitoring thread (QString, ok, nok or off)
        @param statusMsg explanotory text for the signaled status (QString)
        """
        self.emit(SIGNAL("vcsStatusMonitorStatus(QString, QString)"), status, statusMsg)
        
    def setStatusMonitorInterval(self, interval):
        """
        Public method to se the interval of the VCS status monitor thread.
        
        @param interval status monitor interval in seconds (integer)
        """
        self.vcsProjectHelper.setStatusMonitorInterval(interval)
        
    def getStatusMonitorInterval(self):
        """
        Public method to get the monitor interval.
        
        @return interval in seconds (integer)
        """
        return self.vcsProjectHelper.getStatusMonitorInterval()
        
    def checkVCSStatus(self):
        """
        Public method to wake up the VCS status monitor thread.
        """
        self.vcsProjectHelper.checkVCSStatus()
        
    def startStatusMonitor(self):
        """
        Public method to start the VCS status monitor thread.
        """
        self.vcsProjectHelper.startStatusMonitor()
        
    def stopStatusMonitor(self):
        """
        Public method to stop the VCS status monitor thread.
        """
        self.vcsProjectHelper.stopStatusMonitor()
