/*****************************************************************

Copyright (c) 1996-2000 the kicker authors. See file AUTHORS.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <qxembed.h>
#include <qframe.h>
#include <qlayout.h>
#include <qhbox.h>
#include <qpainter.h>
#include <qcursor.h>

#include <kpopupmenu.h>
#include <kapp.h>
#include <kstyle.h>
#include <dcopclient.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kconfig.h>
#include <kpanelapplet.h>

#include "global.h"
#include "panel.h"
#include "menus.h"
#include "internalapplet.h"
#include "pluginmgr.h"
#include "panelbutton.h"
#include "appletcontainer.h"
#include "appletcontainer.moc"

// AppletContainer base class.
AppletContainer::AppletContainer(QWidget *parent)
  : QWidget(parent, "AppletContainter")
  , _pos(Bottom)
  , _orient(Horizontal)
  , _fspace(0)
  , _moveOffset(QPoint(0,0))
  , _aid(QString::null)
  , _opMnu(0)
  , _actions(0)
  , _flags(0)
{
  // the first one will be obsolete very soon hopefully, since the orientation
  // should be determined from the position.
  connect(PGlobal::panel, SIGNAL(orientationChanged(Orientation)),
      SLOT(setOrientation(Orientation)));
  connect(PGlobal::panel, SIGNAL(positionChanged(Position)),
      SLOT(setPosition(Position)));
}

AppletContainer::~AppletContainer()
{
  delete _opMnu;
}

QPoint AppletContainer::getPopupPosition(QPopupMenu *menu, QPoint eventpos)
{
  switch (_pos) {
  case Top: return(mapToGlobal(QPoint(eventpos.x(), height())));
  case Bottom: return(mapToGlobal(QPoint(eventpos.x(), 0 - menu->height())));
  case Right: return(mapToGlobal(QPoint(0-menu->width(), eventpos.y())));
  case Left: return(mapToGlobal(QPoint(width(), eventpos.y())));
  }
  return eventpos;
}

void AppletHandle::setFadeOutHandle(bool v)
{
  _fadeout_handle = v;
  repaint();
}

void AppletHandle::enterEvent(QEvent *)
{
  _drawIt = true;
  repaint();
}

void AppletHandle::leaveEvent(QEvent *)
{
  _drawIt = false;
  repaint();
}

void AppletHandle::paintEvent(QPaintEvent *)
{
  if (!_drawIt && _fadeout_handle)
    return;

  QPainter p;
  p.begin(this);

  if(kapp->kstyle()){
      kapp->kstyle()->drawKickerAppletHandle(&p, 0, 0, width(), height(),
                                             colorGroup(), NULL);
      p.end();
      return;
  }

  QColorGroup g = colorGroup();

  if (_orient == Horizontal)
    {
      for(int y = 2; y < height() - 2; y++)
        {
          p.setPen(g.light());
          p.drawPoint(0, y++);
          p.setPen(g.dark());
          p.drawPoint(1, y++);
          y++;
          p.setPen(g.light());
          p.drawPoint(3, y++);
          p.setPen(g.dark());
          p.drawPoint(4, y);
        }
    }
  else
    {
      for(int x = 2; x < width() - 2; x++)
        {
          p.setPen(g.light());
          p.drawPoint(x++, 0);
          p.setPen(g.dark());
          p.drawPoint(x++, 1);
          x++;
          p.setPen(g.light());
          p.drawPoint(x++, 3);
          p.setPen(g.dark());
          p.drawPoint(x, 4);
        }
    }
  p.end();

}

AppletFrame::AppletFrame( QWidget* parent )
  : AppletContainer(parent)
  , _layout(0)
{
  // setup handle
  _handle = new AppletHandle(this);
  _handle->installEventFilter(this);
  _handle->setOrientation(orientation());

  //setup appletframe
  _appletframe = new QHBox(this);
  _appletframe->setFrameStyle(QFrame::NoFrame);
  _appletframe->installEventFilter(this);

  if (orientation() == Horizontal)
    {
      _handle->setFixedWidth(7);
      _handle->setMaximumHeight(128);
      _layout = new QBoxLayout(this, QBoxLayout::LeftToRight, 0, 0);
    }
  else
    {
      _handle->setFixedHeight(7);
      _handle->setMaximumWidth(128);
      _layout = new QBoxLayout(this, QBoxLayout::TopToBottom, 0, 0);
    }

  _layout->setResizeMode( QLayout::FreeResize );

  _layout->addWidget(_handle);
  _layout->addWidget(_appletframe);
  _layout->activate();
}

void AppletFrame::configure()
{
  KConfig *config = KGlobal::config();
  config->setGroup("panel");
  _handle->setFadeOutHandle(config->readBoolEntry("FadeOutAppletHandles", false));
}

bool AppletFrame::eventFilter (QObject *o, QEvent *e)
{
  switch (e->type())
    {
    case QEvent::MouseButtonPress:
      {
	    QMouseEvent* ev = (QMouseEvent*) e;
	    if ( ev->button() == RightButton )
          {
            if (!_opMnu)
              _opMnu = new PanelAppletOpMenu(_actions);

            switch(_opMnu->exec(getPopupPosition(_opMnu, ev->pos())))
              {
              case PanelAppletOpMenu::Move:
                _moveOffset = QPoint(_handle->width()/2, _handle->height()/2);
                emit moveme(this);
                break;
              case PanelAppletOpMenu::Remove:
                emit removeme(this);
                break;
			  case PanelAppletOpMenu::Help:
				help();
				break;
			  case PanelAppletOpMenu::About:
				about();
				break;
              case PanelAppletOpMenu::Preferences:
                preferences();
                break;
              default:
                break;
              }
            return true;
          }
        else if ( ev->button() == MidButton )
          {
            _moveOffset = ev->pos();
            emit moveme(this);
          }
        return false;
      }
    default:
      return QWidget::eventFilter(o, e);    // standard event processing
    }
  return false;
}

void AppletFrame::resetLayout()
{
  _handle->setOrientation(orientation());

  if (orientation() == Horizontal)
    {
      _layout->setDirection(QBoxLayout::LeftToRight);
      _handle->setFixedWidth(7);
      _handle->setMaximumHeight(128);
    }
  else
    {
      _layout->setDirection(QBoxLayout::TopToBottom);
      _handle->setFixedHeight(7);
      _handle->setMaximumWidth(128);
    }
  _layout->activate();
}

ButtonContainer::ButtonContainer(QWidget* parent)
  : AppletContainer(parent)
  , _button(0)
  , _layout(0)
  , _oldpos(0,0){}

void ButtonContainer::configure()
{
  if(_button)
    _button->configure();
}

QString ButtonContainer::configData()
{
  if(_button)
    return _button->configData();
  else
    return QString::null;
}

void ButtonContainer::setPosition(Position p)
{
  AppletContainer::setPosition(p);

  if(_button)
    _button->setPosition(p);
}

void ButtonContainer::setOrientation(Orientation o)
{
  AppletContainer::setOrientation(o);

  if(_button)
    _button->setOrientation(o);
}

void ButtonContainer::embedButton(PanelButton* b)
{
  if (!b) return;

  delete _layout;
  _layout = new QVBoxLayout(this);
  _button = b;

  _button->installEventFilter(this);
  _layout->add(_button);
  connect(_button, SIGNAL(requestSave()), SIGNAL(requestSave()));
}

bool ButtonContainer::eventFilter (QObject *, QEvent *e)
{
  switch (e->type())
    {
    case QEvent::MouseButtonPress:
      {
	    QMouseEvent* ev = (QMouseEvent*) e;
	    if ( ev->button() == RightButton )
          {
            if (!_opMnu)
              _opMnu = new PanelAppletOpMenu(_actions);

            switch(_opMnu->exec(getPopupPosition(_opMnu, ev->pos())))
              {
              case PanelAppletOpMenu::Move:
                _moveOffset = QPoint(width()/2, height()/2);
                emit moveme(this);
                break;
              case PanelAppletOpMenu::Remove:
				emit removeme(this);
                break;
			  case PanelAppletOpMenu::Help:
				help();
				break;
			  case PanelAppletOpMenu::About:
				about();
				break;
              case PanelAppletOpMenu::Preferences:
                if (_button)
                  _button->properties();
                break;
              default:
                break;
              }
            return true;
          }
        //else if ( ev->button() == LeftButton )
        //  {
        //    _oldpos = ev->pos();
        //    return false;
        //  }
		else if ( ev->button() == MidButton )
          {
			_moveOffset = ev->pos();
            emit moveme(this);
            return true;
          }
        return false;
      }
	  /*
    case QEvent::MouseMove:
      {
        QMouseEvent* ev = (QMouseEvent*) e;
        if ((ev->state() & LeftButton) == LeftButton)
          {
            QPoint p (ev->pos() - _oldpos);

            if (p.manhattanLength() > KGlobalSettings::dndEventDelay())
              {
                _moveOffset = ev->pos();
                emit moveme(this);
              }
          return true;
          }
        return false;
      }
	  */
    default:
      return false;
    }
}

void ButtonContainer::completeMoveOperation()
{
  if(_button)
    _button->setDown(false);
}

// KMenuButton container
KMenuButtonContainer::KMenuButtonContainer(QWidget* parent)
  : ButtonContainer(parent)
{
  PanelKButton *b = new PanelKButton(this);
  embedButton(b);
}

// URLButton container
URLButtonContainer::URLButtonContainer(const QString &url, QWidget* parent)
  : ButtonContainer(parent)
{
  PanelURLButton *b = new PanelURLButton(url, this);
  _actions = KPanelApplet::Preferences;
  embedButton(b);
}

// BrowserButton container
BrowserButtonContainer::BrowserButtonContainer(const QString &startDir, QWidget* parent)
  : ButtonContainer(parent)
{
  PanelBrowserButton *b = new PanelBrowserButton(startDir, this);
  embedButton(b);
}

// WindowListButton container
WindowListButtonContainer::WindowListButtonContainer(QWidget* parent)
  : ButtonContainer(parent)
{
  PanelWindowListButton *b = new PanelWindowListButton(this);
  embedButton(b);
}

// ExeButton container
ExeButtonContainer::ExeButtonContainer(const QString &filePath, const QString &icon,
                                       const QString &cmdLine, bool inTerm, QWidget *parent)
  : ButtonContainer(parent)
{
  PanelExeButton *b = new PanelExeButton(filePath, icon, cmdLine, inTerm, this);
  _actions = KPanelApplet::Preferences;
  embedButton(b);
}

ExeButtonContainer::ExeButtonContainer(const QString &configData, QWidget *parent)
  : ButtonContainer(parent)
{
  PanelExeButton *b = new PanelExeButton(configData, this);
  embedButton(b);
}

// AppletContainer for external applets.
ExternalFrame::ExternalFrame( QCString application, QCString objId, QWidget* parent )
  : AppletFrame(parent)
  , _app(application)
  , _obj(objId)
  , _win(0)
{
  // get some information about the applet.
  DCOPClient* dcop = kapp->dcopClient();

  QByteArray data;
  QCString replyType;
  QByteArray replyData;
  if ( dcop->call ( _app, _obj, "winId()", data, replyType, replyData ) )
    {
      QDataStream reply( replyData, IO_ReadOnly );
      reply >> _win;
    }
  if ( dcop->call ( _app, _obj, "restartCommand()", data, replyType, replyData ) )
    {
      QDataStream reply( replyData, IO_ReadOnly );
      reply >> _com;
      if(_com.isEmpty())
        _com = _app;
    }
  if ( dcop->call ( _app, _obj, "actions()", data, replyType, replyData ) )
    {
      QDataStream reply( replyData, IO_ReadOnly );
      reply >> _actions;
    }

  if ( dcop->call ( _app, _obj, "flags()", data, replyType, replyData ) )
    {
      QDataStream reply( replyData, IO_ReadOnly );
      reply >> _flags;
    }

  {
    QByteArray data;
    QDataStream dataStream( data, IO_WriteOnly );
    dataStream << static_cast<int>(_pos);

    kapp->dcopClient()->send( _app, _obj, "setPosition(int)", data);
  }
  {
    QByteArray data;
    QDataStream dataStream( data, IO_WriteOnly );
    dataStream << static_cast<int>(_orient);

    kapp->dcopClient()->send( _app, _obj, "setOrientation(int)", data );
  }

  _embed = new QXEmbed( _appletframe );

  if (_win)
    {
      _embed->embed( _win );
      connect ( _embed, SIGNAL( embeddedWindowDestroyed() ),
				this, SIGNAL( embeddedWindowDestroyed() ) );
	}
}

ExternalFrame::~ExternalFrame()
{
  QByteArray data;
  kapp->dcopClient()->send( _app, _obj, "removedFromPanel()", data);
}

void ExternalFrame::about()
{
  QByteArray data;
  kapp->dcopClient()->send( _app, _obj, "about()", data );
}

void ExternalFrame::help()
{
  QByteArray data;
  kapp->dcopClient()->send( _app, _obj, "help()", data );
}

void ExternalFrame::preferences()
{
  QByteArray data;
  kapp->dcopClient()->send( _app, _obj, "preferences()", data );
}

void ExternalFrame::setPosition(Position p)
{
  if (_pos == p) return;

  AppletContainer::setPosition(p);

  QByteArray data;
  QDataStream dataStream( data, IO_WriteOnly );
  dataStream << static_cast<int>(p);

  kapp->dcopClient()->send( _app, _obj, "setPosition(int)", data);
}

void ExternalFrame::setOrientation(Orientation o)
{
  if (_orient == o) return;

  AppletContainer::setOrientation(o);

  QByteArray data;
  QDataStream dataStream( data, IO_WriteOnly );
  dataStream << static_cast<int>(o);

  kapp->dcopClient()->send( _app, _obj, "setOrientation(int)", data );

  resetLayout();
}

int ExternalFrame::widthForHeight(int h)
{
  DCOPClient* dcop = kapp->dcopClient();

  QByteArray data;
  QCString replyType;
  QByteArray replyData;
  QDataStream dataStream( data, IO_WriteOnly );
  dataStream << h;

  int w = h + _handle->width();

  if (dcop->call( _app, _obj, "widthForHeight(int)", data, replyType, replyData ) )
    {
      QDataStream reply( replyData, IO_ReadOnly );
      reply >> w;
    }
  return w + _handle->width();
}

int ExternalFrame::heightForWidth(int w)
{
  DCOPClient* dcop = kapp->dcopClient();

  QByteArray data;
  QCString replyType;
  QByteArray replyData;
  QDataStream dataStream( data, IO_WriteOnly );
  dataStream << w;

  int h = w + _handle->height();

  if (dcop->call( _app, _obj, "heightForWidth(int)", data, replyType, replyData ) )
    {
      QDataStream reply( replyData, IO_ReadOnly );
      reply >> h;
    }
  return h + _handle->height();
}

QString ExternalFrame::configData()
{
  return QString(_com) + "::seperator::" + QString("%1").arg(width());
}

// AppletContainer for internal applets.
InternalFrame::InternalFrame( const QString &aname, const QString &desktopFile, QWidget *parent )
  : AppletFrame(parent)
{
  _applet = PGlobal::pluginmgr->loadPlugin(desktopFile, _appletframe);

  if (_applet)
    {
      _applet->setOrientation(_orient);
      _applet->setPosition((InternalApplet::Position) (_pos));
      _actions = _applet->actions();
      _flags = _applet->flags();

      connect(_applet, SIGNAL(sigUpdateLayout()), SIGNAL(sigUpdateLayout()));
      connect(_applet, SIGNAL(sigActionsChanged()), SLOT(slotActionsChanged()));
      connect(_applet, SIGNAL(sigFlagsChanged()), SLOT(slotFlagsChanged()));
    }

  _id = aname; // good as anything else ;-)
  _deskFile = desktopFile;
}

void InternalFrame::slotActionsChanged()
{
  if (_applet)
    _actions = _applet->actions();
}

void InternalFrame::slotFlagsChanged()
{
  if (_applet)
    _flags = _applet->flags();
}

void InternalFrame::setPosition(Position p)
{
  if (_pos == p) return;

  AppletContainer::setPosition(p);

  if (!_applet) return;
  _applet->setPosition( (InternalApplet::Position) (p));

  resetLayout();
}

void InternalFrame::setOrientation(Orientation o)
{
  if (_orient == o) return;

  AppletContainer::setOrientation(o);

  if (!_applet) return;
  _applet->setOrientation(o);

  resetLayout();
}

int InternalFrame::widthForHeight(int h)
{
  if (!_applet) return h;
  return _applet->widthForHeight(h) + _handle->width();
}

int InternalFrame::heightForWidth(int w)
{
  if (!_applet) return w;
  return _applet->heightForWidth(w) + _handle->height();
}

void InternalFrame::about()
{
  if (!_applet) return;
  _applet->about();
}

void InternalFrame::help()
{
  if (!_applet) return;
  _applet->help();
}

void InternalFrame::preferences()
{
  if (!_applet) return;
  _applet->preferences();
}
