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

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

"""
Module implementing a dialog starting a process and showing its output.
"""

import os

from qt import *

from KdeQt import KQMessageBox

from SvnForm import SvnForm
import Preferences

class SvnDialog(SvnForm):
    """
    Module implementing a dialog starting a process and showing its output.
    
    It starts a QProcess and display a dialog that
    shows the output of the process. The dialog is modal,
    which causes a synchronized execution of the process.
    """
    def __init__(self, text, parent = None):
        """
        Constructor
        
        @param text text to be shown by the label (string or QString)
        @param parent parent widget (QWidget)
        """
        SvnForm.__init__(self, parent, None, 1)
        
        self.proc = None
        self.username = ''
        self.password = ''
        
        self.outputGroup.setTitle(text)
        
    def finish(self):
        """
        Private slot called when the process finished or the user pressed the button.
        """
        if self.proc is not None:
            self.proc.tryTerminate()
            QTimer.singleShot(2000, self.proc, SLOT('kill()'))
            
        self.button.setText(self.trUtf8('&OK'))
        self.button.setDefault(1)
        self.button.setFocus()
        
        self.inputGroup.setEnabled(0)
        
        self.proc = None
        
        if Preferences.getVCS("AutoClose") and \
           self.normal and \
           not self.errors.length() > 0:
            self.accept()
        
    def buttonPressed(self):
        """
        Private slot connected to the button clicked signal.
        """
        if self.proc is None:
            self.accept()
        else:
            self.finish()
            
    def procExited(self):
        """
        Private slot connected to the processExited signal.
        """
        if self.proc is not None:
            self.normal = self.proc.normalExit()
        self.finish()
        
    def startProcess(self, proc):
        """
        Public slot used to start the process.
        
        @param proc process object (QProcess)
        """
        self.normal = 0
        self.intercept = 0
        if proc is None:
            return
            
        self.proc = proc
        args = proc.arguments()
        nargs = QStringList()
        lastWasPwd = 0
        for arg in args:
            if lastWasPwd:
                lastWasPwd = 0
                continue
            nargs.append(arg)
            if str(arg) == '--password':
                lastWasPwd = 1
                nargs.append('*****')
            
        self.resultbox.append(nargs.join(' '))
        self.resultbox.append('')
        
        self.connect(proc, SIGNAL('processExited()'), self.procExited)
        self.connect(proc, SIGNAL('readyReadStdout()'), self.handleReadStdout)
        self.connect(proc, SIGNAL('readyReadStderr()'), self.handleReadStderr)
        
        procStarted = proc.start()
        if not procStarted:
            self.button.setFocus()
            self.inputGroup.setEnabled(0)
            arg0 = proc.arguments()[0]
            KQMessageBox.critical(None,
                self.trUtf8('Process Generation Error'),
                self.trUtf8(
                    'The process %1 could not be started.'
                    'Ensure, that it is in the search path.'
                ).arg(arg0),
                self.trUtf8('OK'))
        else:
            self.inputGroup.setEnabled(1)
        return procStarted
        
    def normalExit(self):
        """
        Public method to check for a normal process termination.
        
        @return flag indicating normal process termination (boolean)
        """
        return self.normal
    
    def handleReadStdout(self):
        """
        Private slot to handle the readyReadStdout signal. 
        
        It reads the output of the process, formats it and inserts it into
        the contents pane.
        """
        if self.proc is not None:
            s = unicode(self.proc.readStdout())
            self.resultbox.moveCursor(QTextEdit.MoveEnd, 0)
            self.resultbox.insert(s)
        
    def handleReadStderr(self):
        """
        Private slot to handle the readyReadStderr signal.
        
        It reads the error output of the process and inserts it into the
        error pane.
        """
        if self.proc is not None:
            s = unicode(self.proc.readStderr())
            self.errors.moveCursor(QTextEdit.MoveEnd, 0)
            self.errors.insert(s)
        
    def passwordMode(self, isOn):
        """
        Private slot to handle the password checkbox toggled.
        
        @param isOn flag indicating the status of the check box (boolean)
        """
        if isOn:
            self.input.setEchoMode(QLineEdit.Password)
        else:
            self.input.setEchoMode(QLineEdit.Normal)
        
    def sendInput(self):
        """
        Private slot to send the input to the subversion process.
        """
        input = self.input.text()
        input.append(os.linesep)
        
        self.errors.moveCursor(QTextEdit.MoveEnd, 0)
        if self.passwordCheckBox.isChecked():
            self.errors.insert(os.linesep)
        else:
            self.errors.insert(input)
        
        self.proc.writeToStdin(input)
        
        self.passwordCheckBox.setChecked(0)
        self.input.clear()
        
    def returnPressed(self):
        """
        Private slot to handle the press of the return key in the input field.
        """
        self.intercept = 1
        self.sendInput()
        
    def keyPressEvent(self, evt):
        """
        Protected slot to handle a key press event.
        
        @param evt the key press event (QKeyEvent)
        """
        if self.intercept:
            self.intercept = 0
            evt.accept()
            return
        SvnForm.keyPressEvent(self, evt)
