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

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

"""
Module implementing the version control systems interface to CVS.
"""

import os
import shutil
import types

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

from KdeQt import KQMessageBox
from KdeQt.KQApplication import e4App

from VCS.VersionControl import VersionControl

from CvsDialog import CvsDialog
from CvsCommitDialog import CvsCommitDialog
from CvsLogDialog import CvsLogDialog
from CvsDiffDialog import CvsDiffDialog
from CvsHistoryDialog import CvsHistoryDialog
from CvsStatusDialog import CvsStatusDialog
from CvsTagDialog import CvsTagDialog
from CvsCommandDialog import CvsCommandDialog
from CvsSwitchDialog import CvsSwitchDialog
from CvsMergeDialog import CvsMergeDialog
from CvsOptionsDialog import CvsOptionsDialog
from CvsNewProjectOptionsDialog import CvsNewProjectOptionsDialog
from CvsLoginDialog import CvsLoginDialog
from CvsLogoutDialog import CvsLogoutDialog
from ProjectBrowserHelper import CvsProjectBrowserHelper
from ProjectHelper import CvsProjectHelper

import Preferences
import Utilities

class Cvs(VersionControl):
    """
    Class implementing the version control systems interface to CVS.
    """
    def __init__(self, parent = None, name = None):
        """
        Constructor
        
        @param parent parent widget (QWidget)
        @param name name of this object (string or QString)
        """
        VersionControl.__init__(self, parent, name)
        self.defaultOptions = {
            'global' : ['-f'],
            'commit' : [''],
            'checkout' : ['-z3'],
            'update' : ['-dP'],
            'add' : [''],
            'remove' : ['-f'],
            'diff' : ['-u3', '-p'],
            'log' : [''],
            'history' : ['-e', '-a'],
            'status' : ['-v'],
            'tag' : ['-c'],
            'export' : ['']
        }
        self.interestingDataKeys = [
        ]
        self.canDetectBinaries = False
        
        self.options = self.defaultOptions
        self.tagList = QStringList()
        
        self.commandHistory = QStringList()
        self.wdHistory = QStringList()
        
        self.log = None
        self.diff = None
        self.status = None
        self.history = None
        
        self.__commitData = {}
        self.__commitDialog = None
        
    def vcsShutdown(self):
        """
        Public method used to shutdown the CVS interface.
        """
        self.log and self.log.close()
        self.diff and self.diff.close()
        self.status and self.status.close()
        self.history and self.history.close()
        
    def vcsExists(self):
        """
        Public method used to test for the presence of the cvs executable.
        
        @return flag indicating the existance (boolean)
        """
        self.versionStr = QString()
        ioEncoding = str(Preferences.getSystem("IOEncoding"))
        
        process = QProcess()
        process.start('cvs', QStringList('-v'))
        procStarted = process.waitForStarted()
        if procStarted:
            finished = process.waitForFinished(30000)
            if finished and process.exitCode() == 0:
                output = \
                    unicode(process.readAllStandardOutput(), ioEncoding, 'replace')
                self.versionStr = output.strip().split()[4]
                return True
        
        return False
        
    def vcsInit(self, vcsDir, noDialog = False):
        """
        Public method used to initialize the cvs repository.
        
        @param vcsDir name of the VCS directory (string)
        @param noDialog flag indicating quiet operations (boolean)
        @return flag indicating an execution without errors (boolean)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('-d')
        args.append(vcsDir)
        args.append('init')
        
        if noDialog:
            return self.startSynchronizedProcess(QProcess(), "cvs", args)
        else:
            dia = CvsDialog(self.trUtf8('Initializing cvs repository'))
            res = dia.startProcess(args)
            if res:
                dia.exec_()
            return dia.normalExit()
        
    def vcsConvertProject(self, vcsDataDict, project):
        """
        Public method to convert an uncontrolled project to a version controlled project.
        
        @param vcsDataDict dictionary of data required for the conversion
        @param project reference to the project object
        """
        success = self.vcsImport(vcsDataDict, project.ppath)[0]
        if not success:
            KQMessageBox.critical(None,
                self.trUtf8("Create project in repository"),
                self.trUtf8("""The project could not be created in the repository."""
                            """ Maybe the given repository doesn't exist or the"""
                            """ repository server is down."""))
        else:
            cwdIsPpath = False
            if os.getcwd() == project.ppath:
                os.chdir(os.path.dirname(project.ppath))
                cwdIsPpath = True
            tmpProjectDir = "%s_tmp" % project.ppath
            os.rename(project.ppath, tmpProjectDir)
            os.makedirs(project.ppath)
            self.vcsCheckout(vcsDataDict, project.ppath)
            if cwdIsPpath:
                os.chdir(project.ppath)
            self.vcsCommit(os.path.join(project.ppath, vcsDataDict["archive"]), 
                           vcsDataDict["message"], True)
            pfn = os.path.join(project.ppath, vcsDataDict["archive"], 
                               os.path.basename(project.pfile))
            if not os.path.isfile(pfn):
                pfn += "z"
            if not os.path.isfile(pfn):
                KQMessageBox.critical(None,
                    self.trUtf8("New project"),
                    self.trUtf8("""The project could not be checked out of the"""
                                """ repository.<br />Restoring the original contents."""))
                if os.getcwd() == project.ppath:
                    os.chdir(os.path.dirname(project.ppath))
                    cwdIsPpath = True
                else:
                    cwdIsPpath = False
                shutil.rmtree(project.ppath, 1)
                os.rename(tmpProjectDir, project.ppath)
                project.pdata["VCS"] = ['None']
                project.vcs = None
                project.setDirty(True)
                project.saveProject()
                return
            shutil.rmtree(tmpProjectDir, True)
            project.openProject(pfn)
        
    def vcsImport(self, vcsDataDict, projectDir, noDialog=0):
        """
        Public method used to import the project into the cvs repository.
        
        @param vcsDataDict dictionary of data required for the import
        @param projectDir project directory to create (string)
        @param noDialog flag indicating quiet operations
        @return flag indicating an execution without errors (boolean)
            and a flag indicating the version controll status (boolean)
        """
        self.vcsInit(vcsDataDict["repository"], True)
        msg = QString(vcsDataDict["message"])
        if msg.isEmpty():
            msg = QString('***')
            
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('-d')
        args.append(vcsDataDict["repository"])
        args.append('import')
        args.append('-m')
        args.append(vcsDataDict["message"])
        args.append(vcsDataDict["archive"])
        args.append(vcsDataDict["vendor"])
        args.append(vcsDataDict["release"])
        proc.setWorkingDirectory(QDir(projectDir))
        
        if noDialog:
            status = self.startSynchronizedProcess(QProcess(), "cvs", args,
                projectDir)
        else:
            dia = CvsDialog(self.trUtf8('Importing project into cvs repository'))
            res = dia.startProcess(args)
            if res:
                dia.exec_()
            status = dia.normalExit()
        
        return status, False
        
    def vcsCheckout(self, vcsDataDict, projectDir, noDialog=0):
        """
        Public method used to check the project out of the cvs repository.
        
        @param vcsDataDict dictionary of data required for the checkout
        @param projectDir project directory to create (string)
        @param noDialog flag indicating quiet operations
        @return flag indicating an execution without errors (boolean)
        """
        try:
            tag = vcsDataDict["tag"]
        except KeyError:
            tag = None
        
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('-d')
        args.append(vcsDataDict["repository"])
        args.append('checkout')
        self.addArguments(args, self.options['checkout'])
        if tag is not None and tag != "":
            args.append('-r')
            args.append(tag)
        args.append('-d')
        args.append(projectDir)
        args.append(vcsDataDict["archive"])
        
        if noDialog:
            return self.startSynchronizedProcess(QProcess(), "cvs", args,
                projectDir)
        else:
            dia = CvsDialog(self.trUtf8('Checking project out of cvs repository'))
            res = dia.startProcess(args)
            if res:
                dia.exec_()
            return dia.normalExit()
        
    def vcsExport(self, vcsDataDict, projectDir):
        """
        Public method used to export a directory from the cvs repository.
        
        @param vcsDataDict dictionary of data required for the checkout
        @param project name of the archive (string)
        @param projectDir project directory to create (string)
        @return flag indicating an execution without errors (boolean)
        """
        try:
            tag = vcsDataDict["tag"]
        except KeyError:
            tag = None
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('-d')
        args.append(vcsDataDict["repository"])
        args.append('export')
        if tag is not None and tag != "":
            args.append('-r')
            args.append(tag)
        args.append('-d')
        args.append(projectDir)
        args.append(vcsDataDict["archive"])
        
        dia = CvsDialog(self.trUtf8('Exporting project from cvs repository'))
        res = dia.startProcess(args, projectDir)
        if res:
            dia.exec_()
        return dia.normalExit()
        
    def vcsCommit(self, name, message, noDialog = False):
        """
        Public method used to make the change of a file/directory permanent in the 
        cvs repository.
        
        @param name file/directory name to be committed (string)
        @param message message for this operation (string)
        @param noDialog flag indicating quiet operations
        """
        msg = QString(message)
        
        if not noDialog and msg.isEmpty():
            # call CommitDialog and get message from there
            if self.__commitDialog is None:
                self.__commitDialog = CvsCommitDialog()
                self.connect(self.__commitDialog, SIGNAL("accepted()"), 
                             self.__vcsCommit_Step2)
            self.__commitDialog.show()
            self.__commitDialog.raise_()
            self.__commitDialog.activateWindow()
        
        self.__commitData["name"] = name
        self.__commitData["msg"] = msg
        self.__commitData["noDialog"] = noDialog
        
        if noDialog:
            self.__vcsCommit_Step2()
        
    def __vcsCommit_Step2(self):
        """
        Private slot performing the second step of the commit action.
        """
        name = self.__commitData["name"]
        msg = self.__commitData["msg"]
        noDialog = self.__commitData["noDialog"]
        
        if self.__commitDialog is not None:
            msg = self.__commitDialog.logMessage()
            self.disconnect(self.__commitDialog, SIGNAL("accepted()"), 
                            self.__vcsCommit_Step2)
            self.__commitDialog = None
        
        if msg.isEmpty():
            msg = QString('***')
        
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('commit')
        self.addArguments(args, self.options['commit'])
        args.append('-m')
        args.append(msg)
        if type(name) is types.ListType:
            dname, fnames = self.splitPathList(name)
            self.addArguments(args, fnames)
        else:
            dname, fname = self.splitPath(name)
            args.append(fname)
        
        if noDialog:
            return self.startSynchronizedProcess(QProcess(), "cvs", procs, dname)
        else:
            dia = CvsDialog(self.trUtf8('Commiting changes to cvs repository'))
            res = dia.startProcess(args, dname)
            if res:
                dia.exec_()
            return dia.normalExit()
        
    def vcsUpdate(self, name):
        """
        Public method used to update a file/directory with the cvs repository.
        
        @param name file/directory name to be updated (string)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('update')
        self.addArguments(args, self.options['update'])
        if type(name) is types.ListType:
            dname, fnames = self.splitPathList(name)
            self.addArguments(args, fnames)
        else:
            dname, fname = self.splitPath(name)
            args.append(fname)
        
        dia = CvsDialog(self.trUtf8('Synchronizing with the cvs repository'))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()
        
    def __stripped(self, item, wdir):
        """
        Private method to give item without the common prefix.
        
        @param item the path to make relative (string)
        @param wdir the working directory (string)
        @return a path relative to wdir (string)
        """
        item = item[len(wdir):]
        while item.startswith(os.path.sep) or \
              (os.path.altsep and item.startswith(os.path.altsep)):
            item = item[1:]
        return item
        
    def vcsAdd(self, name, isDir = False, binary = False):
        """
        Public method used to add a file/directory to the cvs repository.
        
        @param name file/directory name to be added (string)
        @param isDir flag indicating name is a directory (boolean)
        @param binary flag indicating a binary add (boolean)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('add')
        self.addArguments(args, self.options['add'])
        if binary:
            args.append('-kb')
        
        if type(name) is types.ListType:
            if isDir:
                dname, fname = os.path.split(unicode(name[0]))
            else:
                dname, fnames = self.splitPathList(name)
        else:
            if isDir:
                dname, fname = os.path.split(unicode(name))
            else:
                dname, fname = self.splitPath(name)
        tree = []
        wdir = dname
        while not os.path.exists(os.path.join(dname, 'CVS')):
            # add directories recursively, if they aren't in the repository already
            tree.insert(-1, dname)
            dname = os.path.split(dname)[0]
            wdir = dname
        # have to split off the working directory so we get relative paths
        tree = [self.__stripped(item, wdir) for item in tree]
        self.addArguments(args, tree)
        
        if type(name) is types.ListType:
            tree2 = []
            for n in name:
                d = os.path.split(n)[0]
                while not os.path.exists(os.path.join(d, 'CVS')):
                    if d in tree2 + tree:
                        break
                    tree2.append(d)
                    d = os.path.split(d)[0]
            tree2.reverse()
            # have to split off the working directory so we get relative paths
            tree2 = [self.__stripped(item, wdir) for item in tree2]
            name = [self.__stripped(item, wdir) for item in name]
            self.addArguments(args, tree2)
            self.addArguments(args, name)
        else:
            args.append(self.__stripped(name, wdir))
        
        if binary:
            msg = self.trUtf8('Adding to the cvs repository in binary mode')
        else:
            msg = self.trUtf8('Adding to the cvs repository')
        dia = CvsDialog(msg)
        res = dia.startProcess(args, wdir)
        if res:
            dia.exec_()
        
    def vcsAddBinary(self, name, isDir = False):
        """
        Public method used to add a file/directory in binary mode to the cvs repository.
        
        @param name file/directory name to be added (string)
        @param isDir flag indicating name is a directory (boolean)
        """
        self.vcsAdd(name, isDir = isDir, binary = True)
        
    def vcsAddTree(self, path):
        """
        Public method to add a directory tree rooted at path to the cvs repository.
        
        @param path root directory of the tree to be added (string)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('add')
        self.addArguments(args, self.options['add'])
        
        if type(path) is types.ListType:
            dname, fnames = self.splitPathList(path)
        else:
            dname, fname = self.splitPath(path)
        tree = []
        wdir = dname
        while not os.path.exists(os.path.join(dname, 'CVS')):
            # add directories recursively, if they aren't in the repository already
            tree.insert(-1, dname)
            dname = os.path.split(dname)[0]
            wdir = dname
        # have to split off the working directory so we get relative paths
        tree = [self.__stripped(item, wdir) for item in tree]
        self.addArguments(args, tree)
        
        if type(path) is types.ListType:
            tree2 = []
            for n in path:
                d = os.path.split(n)[0]
                while not os.path.exists(os.path.join(d, 'CVS')):
                    if d in tree2 + tree:
                        break
                    tree2.append(d)
                    d = os.path.split(d)[0]
            tree2.reverse()
            # have to split off the working directory so we get relative paths
            tree2 = [self.__stripped(item, wdir) for item in tree2]
            self.addArguments(args, tree2)
            
            for n in path:
                entries = Utilities.direntries(n)
                entries = [self.__stripped(item, wdir) for item in entries]
                self.addArguments(args, entries)
        else:
            entries = Utilities.direntries(path)
            entries = [self.__stripped(item, wdir) for item in entries]
            self.addArguments(args, entries)
        
        dia = CvsDialog(self.trUtf8('Adding to the cvs repository'))
        res = dia.startProcess(args, wdir)
        if res:
            dia.exec_()
        
    def vcsRemove(self, name, project=0):
        """
        Public method used to remove a file/directory from the cvs repository.
        
        The default operation is to remove the local copy as well.
        
        @param name file/directory name to be removed (string)
        @param project flag indicating deletion of a project tree (boolean)
        @return flag indicating successfull operation (boolean)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('remove')
        self.addArguments(args, self.options['remove'])
        if type(name) is types.ListType:
            dname = self.splitPathList(name)[0]
            for n in name:
                if os.path.isdir(n):
                    entries = Utilities.direntries(n, True)
                    self.addArguments(args, entries)
                else:
                    args.append(n)
        else:
            if (not project) and os.path.isdir(name):
                dname, fname = os.path.split(name)
                entries = Utilities.direntries(name, True)
                self.addArguments(args, entries)
            else:
                dname, fname = self.splitPath(name)
                args.append(fname)
        
        dia = CvsDialog(self.trUtf8('Removing from the cvs repository'))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()
            res = dia.normalExit()
            
        return res
        
    def vcsLog(self, name):
        """
        Public method used to view the log of a file/directory from the cvs repository.
        
        @param name file/directory name to show the log for (string)
        """
        self.log = CvsLogDialog(self)
        self.log.show()
        self.log.start(name)
        
    def vcsDiff(self, name):
        """
        Public method used to view the difference of a file/directory to the cvs
        repository.
        
        If name is a directory and is the project directory, all project files
        are save first. If name is a file, which is being edited and has unsaved
        modification, they can be saved or the operation may be aborted.
        
        @param name file/directory name to be diffed (string)
        """
        if type(name) is types.ListType:
            names = name[:]
        else:
            names = [name]
        for nam in names:
            if os.path.isfile(nam):
                editor = e4App().getObject("ViewManager").getOpenEditor(nam)
                if editor and not editor.checkDirty() :
                    return
            else:
                project = e4App().getObject("Project")
                if name == project.ppath and not project.saveAllScripts():
                    return
        self.diff = CvsDiffDialog(self)
        self.diff.show()
        self.diff.start(name)
        
    def vcsHistory(self, name):
        """
        Public method used to view the history of a file/directory in the cvs repository.
        
        @param name file/directory name to show the history for (string)
        """
        self.history = CvsHistoryDialog(self)
        self.history.show()
        self.history.start(name)
        
    def vcsStatus(self, name):
        """
        Public method used to view the status of a file in the cvs repository.
        
        @param name file/directory name to show the status for (string)
        """
        self.status = CvsStatusDialog(self)
        self.status.show()
        self.status.start(name)
        
    def vcsTag(self, name):
        """
        Public method used to set the tag of a file/directory in the cvs repository.
        
        @param name file/directory name to be tagged (string)
        """
        dname, fname = self.splitPath(name)
        
        dlg = CvsTagDialog(self.tagList)
        if dlg.exec_() == QDialog.Accepted:
            tag, tagOp = dlg.getParameters()
            self.tagList.removeAll(tag)
            self.tagList.prepend(tag)
        else:
            return
        
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('tag')
        self.addArguments(args, self.options['tag'])
        if tagOp == 2:
            args.append('-b')
        elif tagOp == 4:
            args.append('-d')
        args.append(tag)
        args.append(fname)
        
        dia = CvsDialog(self.trUtf8('Tagging %1 in the cvs repository')
            .arg(name))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()
        
    def vcsRevert(self, name):
        """
        Public method used to revert changes made to a file/directory.
        
        @param name file/directory name to be reverted (string)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('update')
        self.addArguments(args, self.options['update'])
        args.append('-C')
        if type(name) is types.ListType:
            dname = self.splitPathList(name)[0]
            self.addArguments(args, name)
        else:
            dname = self.splitPath(name)[0]
            args.append(name)
        
        dia = CvsDialog(self.trUtf8('Reverting changes'))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()
        
    def vcsSwitch(self, name):
        """
        Public method used to switch a directory to a different tag/branch.
        
        @param name directory name to be switched (string)
        """
        dname, fname = self.splitPath(name)
        
        dlg = CvsSwitchDialog(self.tagList)
        if dlg.exec_() == QDialog.Accepted:
            tag = dlg.getParameters()
            self.tagList.removeAll(tag)
            self.tagList.prepend(tag)
        else:
            return
        
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('update')
        self.addArguments(args, self.options['update'])
        if tag.isEmpty():
            args.append('-A')
            tn = QString('head revision')
        else:
            args.append('-r')
            args.append(tag)
            tn = tag
        
        dia = CvsDialog(self.trUtf8('Switching to %1')
            .arg(tn))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()
        
    def vcsMerge(self, name):
        """
        Public method used to merge a tag/branch into the local project.
        
        @param name file/directory name to be merged (string)
        """
        dname, fname = self.splitPath(name)
        
        dlg = CvsMergeDialog(self.tagList)
        if dlg.exec_() == QDialog.Accepted:
            tag1, tag2 = dlg.getParameters()
        else:
            return
        
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('update')
        self.addArguments(args, self.options['update'])
        args.append('-j')
        args.append(tag1)
        if not tag2.isEmpty():
            args.append('-j')
            args.append(tag2)
        args.append(fname)
        
        dia = CvsDialog(self.trUtf8('Merging %1')
            .arg(fname))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()
        
    def vcsRegisteredState(self, name):
        """
        Public method used to get the registered state of a file in the vcs.
        
        @param name filename to check (string)
        @return a combination of canBeCommited and canBeAdded or
            0 in order to signal an error
        """
        dname, fname = self.splitPath(name)
        
        ename = os.path.join(dname, 'CVS', 'Entries')
        if fname == '.' and os.path.exists(ename):
            return self.canBeCommitted
        
        try:
            f = open(ename, 'rb')
            lines = f.readlines()
            f.close()
        except:
            return 0
        
        state = self.canBeAdded
        for line in lines:
            fields = line.split('/')
            if fields[0] == '' and fields[1] == fname:
                state = self.canBeCommitted
                if fields[2] == '-':
                    state |= self.canBeAdded
                break
            elif fields[0] == 'D' and fields[1] == fname:
                state = self.canBeCommitted
                break
        
        return state
        
    def vcsAllRegisteredStates(self, names, dname):
        """
        Public method used to get the registered states of a number of files in the vcs.
        
        @param names dictionary with all filenames to be checked as keys
        @param dname directory to check in (string)
        @return the received dictionary completed with a combination of 
            canBeCommited and canBeAdded or None in order to signal an error
        """
        dname = unicode(dname)
        ename = os.path.join(dname, 'CVS', 'Entries')
        try:
            f = open(ename, 'rb')
            lines = f.readlines()
            f.close()
        except:
            return names
        
        for line in lines:
            fields = line.split('/')
            if fields[0] == '' or fields[0] == 'D':
                if fields[2] == '-':
                    state = self.canBeCommitted | self.canBeAdded
                else:
                    state = self.canBeCommitted
                name = os.path.normcase(os.path.join(dname, fields[1]))
                if names.has_key(name):
                    names[name] = state
        
        return names
        
    def vcsName(self):
        """
        Public method returning the name of the vcs.
        
        @return always 'CVS' (string)
        """
        return "CVS"
        
    def vcsCleanup(self, name):
        """
        Public method used to cleanup the local copy.
        
        @param name directory name to be cleaned up (string)
        """
        entries = Utilities.direntries(name, True, '.#*')
        for entry in entries:
            try:
                os.remove(entry)
            except OSError:
                pass
        
    def vcsCommandLine(self, name):
        """
        Public method used to execute arbitrary cvs commands.
        
        @param name directory name of the working directory (string)
        """
        dlg = CvsCommandDialog(self.commandHistory, self.wdHistory, name)
        if dlg.exec_() == QDialog.Accepted:
            command, wd = dlg.getData()
            commandList = Utilities.parseOptionString(command)
            
            # This moves any previous occurence of these arguments to the head
            # of the list.
            self.commandHistory.removeAll(command)
            self.commandHistory.prepend(command)
            self.wdHistory.removeAll(wd)
            self.wdHistory.prepend(wd)
            
            args = QStringList()
            self.addArguments(args, commandList)
            
            dia = CvsDialog(self.trUtf8('CVS command'))
            res = dia.startProcess(args, wd)
            if res:
                dia.exec_()
        
    def vcsOptionsDialog(self, project, archive, editable = False, parent = None):
        """
        Public method to get a dialog to enter repository info.
        
        @param project reference to the project object
        @param archive name of the project in the repository (string)
        @param editable flag indicating that the project name is editable (boolean)
        @param parent parent widget (QWidget)
        """
        return CvsOptionsDialog(project, archive, editable, parent)
        
    def vcsNewProjectOptionsDialog(self, parent = None):
        """
        Public method to get a dialog to enter repository info for getting a new project.
        
        @param parent parent widget (QWidget)
        """
        return CvsNewProjectOptionsDialog(parent)
        
    def vcsRepositoryInfos(self, ppath):
        """
        Public method to retrieve information about the repository.
        
        @param ppath local path to get the repository infos (string)
        @return string with ready formated info for display (QString)
        """
        info = {\
            'cvsroot' : ''
        }
        
        rname = os.path.join(ppath, 'CVS', 'Root')
        try:
            f = open(rname, 'rb')
            lines = f.readlines()
            f.close()
        except:
            return QString(QApplication.translate('cvs',
                'Could not read the Root file.'))
        
        if len(lines) != 1:
            return QString(QApplication.translate('cvs',
                'The Root file has an unknown format.'))
        else:
            info['cvsroot'] = lines[0]
        
        return QString(QApplication.translate('cvs',
            """<h3>Repository information</h3>"""
            """<table>"""
            """<tr><td><b>CVS V.</b></td><td>%1</td></tr>"""
            """<tr><td><b>CVS Root</b></td><td>%2</td></tr>"""
            """</table>"""
            ))\
            .arg(self.versionStr)\
            .arg(info['cvsroot'])\
    
    #################################################################
    ## Below are CVS specific methods
    #################################################################
    
    def cvsEdit(self, name):
        """
        Public method used to edit a file under cvs control.
        
        A list of filenames can be passed in as well. In this case
        it is assumed, that all files are located in the same directory.
        
        @param name file name(s) to be edited (string or list of strings)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('edit')
        args.append('-a')
        args.append('none')
        if type(name) is types.ListType:
            dname, fnames = self.splitPathList(name)
            self.addArguments(args, fnames)
        else:
            dname, fname = self.splitPath(name)
            args.append(fname)
        
        dia = CvsDialog(self.trUtf8('CVS Edit'))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()
            
    def cvsUnedit(self, name):
        """
        Public method used to unedit a file under cvs control.
        
        A list of filenames can be passed in as well. In this case
        it is assumed, that all files are located in the same directory.
        
        @param name file name(s) to be unedited (string or list of strings)
        """
        args = QStringList()
        self.addArguments(args, self.options['global'])
        args.append('unedit')
        if type(name) is types.ListType:
            dname, fnames = self.splitPathList(name)
            self.addArguments(args, fnames)
        else:
            dname, fname = self.splitPath(name)
            args.append(fname)
        
        dia = CvsDialog(self.trUtf8('CVS Unedit'))
        res = dia.startProcess(args, dname)
        if res:
            dia.exec_()

    def cvsLogin(self):
        """
        Public method used to login to the CVS repository.
        """
        dlg = CvsLoginDialog()
        if dlg.exec_() == QDialog.Accepted:
            protocol, user, passwd, host, port, repository = dlg.getData()
            
            if passwd:
                passwd = ":%s" % passwd
            if protocol in ['ext', 'server']:
                repdir = ':%s:%s@%s:%s' % (protocol, user, host, repository)
            else:
                repdir = ':%s:%s%s@%s:%s%s' % \
                    (protocol, user, passwd, host, port, repository)
            
            args = QStringList()
            self.addArguments(args, self.options['global'])
            args.append('-d')
            args.append(repdir)
            args.append('login')
            
            dia = CvsDialog(self.trUtf8('Logging in to the CVS repository'))
            res = dia.startProcess(args)
            if res:
                dia.exec_()
        
    def cvsLogout(self):
        """
        Public method used to logout from the remote repository.
        """
        dlg = CvsLogoutDialog()
        if dlg.exec_() == QDialog.Accepted:
            protocol, user, host, port, repository = dlg.getData()
            repdir = ':%s:%s@%s:%s%s' % (protocol, user, host, port, repository)
            
            args = QStringList()
            self.addArguments(args, self.options['global'])
            args.append('-d')
            args.append(repdir)
            args.append('logout')
            
            dia = CvsDialog(self.trUtf8('Logging out from the CVS repository'))
            res = dia.startProcess(args)
            if res:
                dia.exec_()
        
    ############################################################################
    ## Methods to get the helper objects are below.
    ############################################################################
    
    def vcsGetProjectBrowserHelper(self, browser, project, isTranslationsBrowser = False):
        """
        Public method to instanciate a helper object for the different project browsers.
        
        @param browser reference to the project browser object
        @param project reference to the project object
        @param isTranslationsBrowser flag indicating, the helper is requested for the
            translations browser (this needs some special treatment)
        @return the project browser helper object
        """
        return CvsProjectBrowserHelper(self, browser, project, isTranslationsBrowser)
        
    def vcsGetProjectHelper(self, project):
        """
        Public method to instanciate a helper object for the project.
        
        @param project reference to the project object
        @return the project helper object
        """
        return CvsProjectHelper(self, project)
