/***************************************************************************
                          execbutton.cpp - Button that runs its text association 
                             -------------------
    copyright            : (C) 2002-2003 Marc Britton <consume@optusnet.com.au>
                           (C) 2004      Michal Rudolf <mrudolf@kdewebdev.org>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

/* KDE INCLUDES */
#include <tdeapplication.h>
#include <tdelocale.h>
#include <tdemessagebox.h>

/* QT INCLUDES */
#include <tqcursor.h>
#include <tqevent.h>
#include <tqstring.h>
#include <tqstringlist.h>
#include <tqwidget.h>
#include <tqpopupmenu.h>
#include <tqapplication.h>
#include <tqwidgetlist.h>

/* OTHER INCLUDES */
#include <kommanderwidget.h>
#include <specials.h>
#include "execbutton.h"
#include <myprocess.h>
#include <iostream>
#include <kommanderplugin.h>

using namespace std;

enum Functions {
  FirstFunction = 260, //CHANGE THIS NUMBER TO AN UNIQUE ONE!!!
  EB_isOn,
  EB_setPopup,
  EB_setButtonText,
  LastFunction
};

ExecButton::ExecButton(TQWidget* a_parent, const char* a_name)
  : KPushButton(a_parent, a_name), KommanderWidget(TQT_TQOBJECT(this))
{
  TQStringList states;
  states << "default";
  setStates(states);
  setDisplayStates(states);
  setWriteStdout(true);
  setBlockGUI(Button);
  connect(this, TQT_SIGNAL(clicked()), this, TQT_SLOT(startProcess()));
  
  KommanderPlugin::setDefaultGroup(Group::DCOP);
  KommanderPlugin::registerFunction(EB_isOn, "isOn(TQString widget)",  i18n("For use only when button is togle type."), 1);
  KommanderPlugin::registerFunction(EB_setPopup, "setPopup(TQString widget, TQString Menu)",  i18n("Associate a Kommander PopupMenu with this ExecButton."), 2);
  KommanderPlugin::registerFunction(EB_setButtonText, "setButtonText(TQString widget, TQString Text)",  i18n("Set the text on the ExecButton."), 2);
}

ExecButton::~ExecButton()
{
}

TQString ExecButton::currentState() const
{
  return TQString("default");
}

bool ExecButton::isKommanderWidget() const
{
  return true;
}

TQStringList ExecButton::associatedText() const
{
  return KommanderWidget::associatedText();
}

void ExecButton::setAssociatedText(const TQStringList& a_at)
{
  KommanderWidget::setAssociatedText(a_at);
}

void ExecButton::setPopulationText(const TQString& a_text)
{
  KommanderWidget::setPopulationText(a_text);
}

TQString ExecButton::populationText() const
{
  return KommanderWidget::populationText();
}

void ExecButton::populate()
{
  TQString txt = KommanderWidget::evalAssociatedText(populationText());
  setWidgetText(txt);
}

void ExecButton::setWidgetText(const TQString& a_text)
{
  setText(a_text);
  emit widgetTextChanged(a_text);
}

void ExecButton::startProcess()
{
  TQString at = evalAssociatedText().stripWhiteSpace();
  bool enabledStatus = isEnabled();
  if (m_blockGUI != None)
    setEnabled(false);
  if (m_blockGUI == GUI)
    TDEApplication::setOverrideCursor(TQCursor(TQt::WaitCursor));
  MyProcess* process = new MyProcess(this);
  process->setBlocking(m_blockGUI == GUI);
  connect(process, TQT_SIGNAL(processExited(MyProcess*)), TQT_SLOT(processExited(MyProcess*)));
  m_output = process->run(at);
  if (m_blockGUI == GUI)
  {
    TDEApplication::restoreOverrideCursor();
    if (writeStdout())
      cout << m_output.local8Bit() << flush;
  }
  setEnabled(enabledStatus);
}


bool ExecButton::writeStdout() const
{
  return m_writeStdout;
}

void ExecButton::setWriteStdout(bool a_enable)
{
  m_writeStdout = a_enable;
}

void ExecButton::setBlockGUI(Blocking a_enable)
{
  m_blockGUI = a_enable;
}

ExecButton::Blocking ExecButton::blockGUI() const
{
  return m_blockGUI;
}

void ExecButton::processExited(MyProcess* p)
{
  if (blockGUI() != None)
    setEnabled(true);
  if (p)
  {
    m_output = p->output();
    if (writeStdout())
      cout << m_output.local8Bit() << flush;
    delete p;
  }
}

void ExecButton::showEvent(TQShowEvent* e)
{
  KPushButton::showEvent(e);
  emit widgetOpened();
}

void ExecButton::contextMenuEvent( TQContextMenuEvent * e )
{
  e->accept();
  TQPoint p = e->globalPos();
  emit contextMenuRequested(p.x(), p.y());
}

bool ExecButton::isFunctionSupported(int f)
{
  return f == DCOP::text || f == DCOP::setText || f == DCOP::execute || f == DCOP::geometry || f == DCOP::getBackgroundColor || f == DCOP::setBackgroundColor || (f >= FirstFunction && f <= LastFunction);
}

TQString ExecButton::handleDCOP(int function, const TQStringList& args)
{
  switch (function) {
    case DCOP::text:
      return m_output;
    case DCOP::setText:
      setWidgetText(args[0]);
      break;
    case DCOP::execute:
      startProcess();
      break;
    case EB_isOn:
      return TQString::number(this->isOn() );
      break;
    case EB_setButtonText:
      ExecButton::setText(args[0]);
      break;
    case EB_setPopup:
    {
      TQWidgetList  *list = TQApplication::allWidgets();
      TQWidgetListIt it( *list );
      TQWidget * w;
      while ( (w=it.current()) != 0 ) {  // for each widget...
        ++it;
        if (w->name() == args[0] && ( strcmp(w->className(), "PopupMenu")) == 0 )
        {
          TQPopupMenu *popup = dynamic_cast<TQPopupMenu*>(w->child("unnamed", "TDEPopupMenu"));
          this->setPopup(popup);
        }
      }
      break;
    }
    case DCOP::geometry:
    {
      TQString geo = TQString::number(this->x())+" "+TQString::number(this->y())+" "+TQString::number(this->width())+" "+TQString::number(this->height());
      return geo;
      break;
    }
    case DCOP::getBackgroundColor:
      return this->paletteBackgroundColor().name();
      break;
    case DCOP::setBackgroundColor:
    {
      TQColor color;
      color.setNamedColor(args[0]);
      this->setPaletteBackgroundColor(color);
      break;
    }
    default:
      return KommanderWidget::handleDCOP(function, args);
  }
  return TQString();
}


#include "execbutton.moc"
