/*
** Copyright (C) 1999,2000 Toivo Pedaste <toivo@ucs.uwa.edu.au>
**
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/

/*
** Bug reports and questions can be sent to kde-devel@kde.org
*/


#include "../config.h"

#include <tqvbox.h>

#include <tdeglobalsettings.h>
#include <kdebug.h>

#include <kpTerm.h>


//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

kpTerm::kpTerm(kpPty *pt, TQWidget * parent,  const char * name ) :
  TQTextEdit(parent,name)
{
  pty = pt;
  setFont(TDEGlobalSettings::fixedFont());
  //  setMinimumWidth(fontMetrics().maxWidth()*80 +
  //      minimumSizeHint().width());
  setWordWrap(NoWrap);
  setReadOnly(true);
}

void kpTerm::doConnect()
{
  connect(pty, TQ_SIGNAL(textIn(const TQString &, bool)), this,
	  TQ_SLOT(textIn(const TQString &, bool)));
  connect(pty,TQ_SIGNAL(result(TQStringList &, int)),
	  this,TQ_SLOT(slotResult(TQStringList &, int)));
  connect(this, TQ_SIGNAL(keyOut(char)), pty,
	  TQ_SLOT(keyOut(char)));
}

void kpTerm::doUnconnect()
{
  disconnect(pty, TQ_SIGNAL(textIn(const TQString &, bool)), this,
		   TQ_SLOT(textIn(const TQString &, bool)));
  disconnect(pty,TQ_SIGNAL(result(TQStringList &, int)),
	  this,TQ_SLOT(slotResult(TQStringList &, int)));
  disconnect(this, TQ_SIGNAL(keyOut(char)), pty,
		   TQ_SLOT(keyOut(char)));
}

bool kpTerm::run(const TQString &cmd, TQStringList &r) 
{
  setReadOnly(false);
  setFocus();
  if (pty->startSession(true)) {
    doConnect();

    r =  pty->run(cmd,false);
    return true;
  } else {
    return false;
  }
}
 
void kpTerm::cancel() {
  emit keyOut('\03');
}

void kpTerm::done()
{
   clear();
   doUnconnect();
   setReadOnly(true);
   clearFocus();
}

void kpTerm::keyPressEvent ( TQKeyEvent * e ) 
{
  //  kdDebug() << "K=" << e->ascii() << "," << e->ascii() << "\n";
  if (e->ascii()) {
    emit keyOut(e->ascii());
  } else {
      TQTextEdit::keyPressEvent (e);
  }
  setCursorPosition(9999,9999);
}

void kpTerm::textIn(const TQString &stext, bool bNewLine)
{
  TQRegExp chrs("[\\010\\012\\015]");
  TQString del = "\010";
  // kdDebug() << "Tin=[" << stext << "]\n";
  if (stext.find(chrs) < 0) {
    insert( stext );
  } else {
    int p;
    int op = 0;

    while ((p = stext.find(chrs,op)) >= 0) {
      if (p != op) {
	insert( stext.mid(op, p-op));
      }
      if (stext[p] == '\b') {
	doKeyboardAction(ActionBackspace);
      } else if (stext[p] == '\r') {
	 moveCursor(MoveLineStart, false);
      }  else if (stext[p] == '\n') {
	moveCursor(MoveEnd, false);
	doKeyboardAction(ActionReturn);
      }
      op = p + 1;
    }
    if ((signed int)stext.length() > op)
      insert( stext.right(stext.length()-op));
  }
  if (bNewLine) {
   	moveCursor(MoveEnd, false);
	doKeyboardAction(ActionReturn);
  }
  moveCursor(MoveEnd, false);
}

void kpTerm::insert ( const TQString & str, bool) {
  int x,y;
  getCursorPosition(&y,&x);

  if (str.length() > 0) {
    //    kdDebug() << "ins:"  << y << "," << x << str <<":" << str.length() << "\n";
    if (x == 0 && str != "\n") {
      doKeyboardAction(ActionKill);
      getCursorPosition(&y,&x);
      //      kdDebug() << "k="  << y << "," << x <<"\n";
    }
    TQTextEdit::insert(str,(bool)false);
  }
}

void kpTerm::slotResult(TQStringList &rlist, int ret)
{
  emit result(rlist, ret);
  doUnconnect();
}



//////////////////////////////////////////////////////////////////////////////
//
// Dialog window for password prompt
//
//////////////////////////////////////////////////////////////////////////////
kpRun::kpRun( TQWidget *parent)
  :  KDialogBase(parent, "kpRun", true, TQString(),
		Cancel, Cancel, true )
{
  TQVBox *page = makeVBoxMainWidget();
  title = new TQLabel("", page);
  TQFont f( TDEGlobalSettings::generalFont());
  f.setBold(true);
  f.setPointSize(f.pointSize()+4);
  title->setFont(f);

  term = new kpTerm(kpty,page);
  resize(600, 300);
  connect(term,TQ_SIGNAL(result(TQStringList &, int)),
	  this,TQ_SLOT(slotResult(TQStringList &, int)));
 
  hide();
}

bool kpRun::run(TQString cmd, TQString msg)
{
  TQStringList r;

  title->setText(msg);
  if (!cmd.isEmpty()) {
    return term->run(cmd, r);
  } else {
    term->doConnect();
    term->setReadOnly(false);
    term->setFocus();
    return true;
  }
}

void kpRun::addText(const TQStringList &ret)
{
  int last = ret.count()-1;
  int i = 0;
  for ( TQStringList::ConstIterator it = ret.begin(); it != ret.end(); ++it, ++i ) {
    //    kdDebug() << "ks=" << *it << "\n";
    term->textIn(*it, (i != last));
  }
}

void kpRun::slotResult(TQStringList &, int ret)
{
  if (ret == 0 || ret == 666) {
    term->clear();
    if (ret == 0) 
      accept();
    else
      reject();
  }
}

void kpRun::slotCancel()
{
  term->clear();
  term->cancel();
  accept();
}

#include "kpTerm.moc"
