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

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.

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

#define TEST_ME

#include <stdlib.h>
#include <unistd.h>
#include <math.h>

#include <qlayout.h>
#include <qscrollview.h>
#include <qvbox.h>
#include <qcursor.h>
#include <qevent.h>
#include <qtimer.h>

#include <kglobal.h>
#include <kglobalsettings.h>
#include <kdebug.h>
#include <kconfig.h>
#include <kwinmodule.h>
#include <dcopclient.h>
#include <kwin.h>
#include <kstddirs.h>

#include "panel.h"
#include "panel.moc"
#include "menus.h"
#include "appletarea.h"
#include "hidebutton.h"
#include "pluginmgr.h"
#include "userrectsel.h"

Panel::Panel() : QWidget(0, "Panel" )
  , DCOPObject("Panel")
  , _showHBs(true)
  , _HBwidth(10)
  , _autoHide(false)
  , _autoHidden(false)
  , _userHidden(false)
  , _hideAnim(true)
  , _autoHideAnim(true)
  , _autoHideDelay(3)
  , _hideAnimSpeed(5)
  , _autoHideAnimSpeed(50)
  , _block_user_input(false)
  , _layout(0)
  , _opMnu(0)
{
  // required for kwin to recognise kicker
  setCaption("Kicker");

  // always use the active palette
  QPalette pal(palette());
  if(pal.active().mid() != pal.inactive().mid()){
      pal.setInactive(pal.active());
      setPalette(pal);
  }

  // instantiate plugin manager and kwin module
  PGlobal::pluginmgr = new KickerPluginManager();
  PGlobal::kwin_module = new KWinModule(this, true);

  // let PGlobal know we are there
  PGlobal::panel = this;

   // left/top hide button
  _ltHB = new HideButton(position(), this);
  _ltHB->setFocusPolicy(QWidget::NoFocus);
  _ltHB->setMouseTracking(true);
  _ltHB->installEventFilter( this );
  connect( _ltHB, SIGNAL( clicked() ), this, SLOT( hideLeft() ) );

   // right/bottom hide button
  _rbHB = new HideButton( position(), this );
  _rbHB->setFocusPolicy(QWidget::NoFocus);
  _rbHB->setMouseTracking(true);
  _rbHB->installEventFilter( this );
  connect( _rbHB, SIGNAL( clicked() ), this, SLOT( hideRight() ) );

  // applet area box
  _appletAreaBox = new QVBox(this);
  _appletAreaBox->setFrameStyle(QFrame::WinPanel  | QFrame::Raised);
  _appletAreaBox->setLineWidth(1);
  _appletAreaBox->setMouseTracking(true);
  _appletAreaBox->installEventFilter( this );

  // applet area
  _appletArea = new AppletArea( orientation(), _appletAreaBox );
  _appletArea->setFrameStyle( QFrame::NoFrame );
  _appletArea->viewport()->installEventFilter( this );

  // instantiate the autohide timer
  _autohideTimer = new QTimer(this);
  
  // initialise
  configure();
}

Panel::~Panel()
{
  delete _opMnu;
  writeConfig();
}

bool Panel::process(const QCString &fun, const QByteArray &data, QCString& replyType,
					QByteArray &replyData)
{
  if ( fun == "configure()" )
	{
	  replyType = "void";
	  configure( );
	  return true;
	}
  else if ( fun == "restart()" )
  {
    replyType = "void";
    // do this on a timer to give us time to return true
    QTimer::singleShot(1000, this, SLOT(slotRestart()));
    return true;
  }
  if ( DCOPObject::process( fun, data, replyType, replyData ) )
	return true;
  return false;
}

void Panel::configure()
{
  KConfig *config = KGlobal::config();
  config->reparseConfiguration();
  config->setGroup("panel");

  _autoHide = config->readBoolEntry("AutoHidePanel", false);
  _hideAnim = config->readBoolEntry("HideAnimation", true);
  _autoHideAnim = config->readBoolEntry("AutoHideAnimation", true);
  _autoHideDelay = config->readNumEntry("AutoHideDelay", 3);
  _hideAnimSpeed = config->readNumEntry("HideAnimationSpeed", 50);
  _autoHideAnimSpeed = config->readNumEntry("AutoHideAnimationSpeed", 5);

  _size = static_cast<Size>(config->readNumEntry("Size", Normal));
  _pos = static_cast<Position>(config->readNumEntry("Position", Bottom));
  _showHBs = config->readBoolEntry("ShowHideButtons", true);
  _HBwidth = config->readNumEntry("HideButtonSize", 10);
  if (_HBwidth < 3) _HBwidth = 3;
  if (_HBwidth > 24) _HBwidth = 24;

  // force applets to change position
  emit positionChanged(_pos);
  emit orientationChanged(orientation());

  _panelsize = PGlobal::sizeValue(_size);
  resetLayout();

  _ltHB->configure();
  _rbHB->configure();
  _appletArea->configure();

  //setup auto-hide timer
  connect(_autohideTimer, SIGNAL(timeout()), SLOT(autoHideTimeout()));
  resetAutoHideTimer();

  updateWindowManager();
}

void Panel::setPosition(Position p)
{
  if ( p != _pos ) {
    _pos = p;
    emit positionChanged(_pos);
    emit orientationChanged(orientation());
    resetLayout();
    updateWindowManager();
  }
}

void Panel::setSize(Size s)
{
  _size = s;
  _panelsize = PGlobal::sizeValue(s);
  resetLayout();
  updateWindowManager();
}

void Panel::writeConfig()
{
  KConfig *config = KGlobal::config();
  config->setGroup("panel");

  config->writeEntry("Position", static_cast<int>(_pos));
  config->writeEntry("Size", static_cast<int>(_size));

  config->sync();
}

void Panel::resetLayout()
{
  writeConfig();

  delete _layout;

  setGeometry( initialGeometry() );

  // layout
  _layout = new QBoxLayout( this, isHorizontal()?QBoxLayout::LeftToRight
                           : QBoxLayout::TopToBottom, 0, 0);
  _layout->setResizeMode( QLayout::FreeResize );

  // left/top hide button
  if (isHorizontal())
    {
      _ltHB->setPosition(Left);
      _ltHB->setFixedSize( _HBwidth, rect().height() );
    }
  else
    {
      _ltHB->setPosition(Top);
      _ltHB->setFixedSize( rect().width(), _HBwidth );
    }
  if (_showHBs)
    {
      _ltHB->show();
      _layout->addWidget( _ltHB );
    }
  else
    _ltHB->hide();

  // applet area
  _appletArea->setOrientation(orientation());
  _layout->addWidget(_appletAreaBox);

  // right/bottom hide button
  if ( isHorizontal() )
    {
      _rbHB->setPosition(Right);
      _rbHB->setFixedSize( _HBwidth, rect().height() );
    }
  else
    {
      _rbHB->setPosition(Bottom);
      _rbHB->setFixedSize( rect().width(), _HBwidth );
    }
  if (_showHBs)
    {
      _rbHB->show();
      _layout->addWidget( _rbHB );
    }
  else
    _rbHB->hide();

  _layout->activate();
  updateGeometry();

  _autoHidden = false;
  _userHidden = false;
}

QRect Panel::initialGeometry()
{
#ifdef TEST_ME
  QRect r(KWin::edgeClientArea());
#else
  QRect r(QApplication::desktop()->geometry());
#endif
  switch( _pos ) {
  case Left:
    return QRect(  r.left(), r.top(), _panelsize, r.height() );
  case Right:
    return QRect(  r.right() - _panelsize + 1, r.top(), _panelsize, r.height() );
  case Top:
    return QRect(  r.left(), r.top(), r.width(), _panelsize );
  case Bottom:
  default:
    return QRect(  r.left(), r.bottom() - _panelsize + 1, r.width(), _panelsize );
  }
}

/* 1 is the initial speed, hide_show_animation is the top speed. */
#define PANEL_SPEED(x, c) (int)((1.0-2.0*fabs((x)-(c)/2.0)/c)*_hideAnimSpeed+1.0)
#define PANEL_AUTOSPEED(x, c) (int)((1.0-2.0*fabs((x)-(c)/2.0)/c)*_autoHideAnimSpeed+1.0)

void Panel::hideLeft()
{
  animatedHide(true);
}

void Panel::hideRight()
{
  animatedHide(false);
}

void Panel::animatedHide(bool left)
{
  blockUserInput( TRUE );
  QRect geom( initialGeometry() );

  if ( geom != geometry() ) {

    // SHOW

    if ( isVertical() ) {

      int strut = _ltHB->geometry().bottom();

      if (_hideAnim) {

        for (int i = geom.height()-strut; i>0;i-=PANEL_SPEED(i,geom.height()) )
        {
          move(geom.x(), left ? geom.y() + i : geom.y() - i);

          qApp->syncX();
          qApp->processEvents();
        }
      }
    }
    else {
      int strut = _ltHB->geometry().right();
      if(_hideAnim)
      {
        for (int i = geom.width()-strut; i>0;i-=PANEL_SPEED(i,geom.width()) )
        {
          move(left ? geom.x() + i : geom.x() - i, geom.y());

          qApp->syncX();
          qApp->processEvents();
        }
      }
    }
    move(geom.x(), geom.y());

    // Do this late, because it doesn't need doing early and it's better
    // that kwin updates kdesktop late so we don't see the grey area.
    _userHidden = false;
    updateWindowManager();
  }
  else
  {
    // HIDE

    // Do this early, because we want the grey area to disappear as
    // quickly as possible (kwin asks kdesktop to update).
    _userHidden = true;
    updateWindowManager();
    // Don't bother autohiding when the user's done it already.
    _autohideTimer->stop();

    if ( isVertical() ) {
      int strut = _ltHB->geometry().bottom();
      if(_hideAnim)
      {
        for (int i = 0;
          i < geom.height() - strut;
          i += PANEL_SPEED(i,geom.height()))
        {
          move(geom.x(), left ? geom.y() - i : geom.y() + i);

          qApp->syncX();
          qApp->processEvents();
        }
      }
      else
        move(geom.x(), left ? strut - geom.height() : geom.height() - strut);
    }
    else {
      int strut = _ltHB->geometry().right();
      if(_hideAnim)
      {
        for (int i = 0;
          i < geom.width() - strut;
          i += PANEL_SPEED(i,geom.width()))
        {
          move(left ? geom.x() - i : geom.x() + i, geom.y());

          qApp->syncX();
          qApp->processEvents();
        }
      }
      else
        move(left ? strut - geom.width() : geom.width() - strut, geom.y());
    }
  }
  blockUserInput( FALSE );
}

void Panel::resetAutoHideTimer()
{
  _autohideTimer->start(_autoHideDelay * 1000, true);
}

void Panel::autoHideTimeout()
{
  if (_autoHide)
	{
	  QRect r = rect();
	  r.moveTopLeft(pos());
	  if (!r.contains(QCursor::pos()))
		autoHide(true);
	}
  resetAutoHideTimer();
}

void Panel::autoHide(bool hide)
{
  if (_userHidden) // Don't autohide when the user has hidden us already.
    return;

  if (hide && !_autoHidden) //HIDE
	  _autoHidden = true;
  else if  (!hide && _autoHidden) // SHOW
	  _autoHidden = false;
  else
	return;

  blockUserInput(true);
  QRect geom(initialGeometry());
  QPoint oldpos;
  QPoint newpos;

  if (hide) // HIDE
	{
	  oldpos = QPoint(geom.left(), geom.top());
	  
	  switch( _pos ) {
	  case Left:
		newpos = QPoint(geom.left() - geom.width() + 1, geom.top());
		break;
	  case Right:
		newpos = QPoint(geom.left() + geom.width() - 1, geom.top());
		break;
	  case Top:
		newpos = QPoint(geom.left(), geom.top() - geom.height() + 1);
		break;
	  case Bottom:
	  default:
		newpos = QPoint(geom.left(), geom.top() + geom.height() - 1);
		break;
	  }
	}
  else
	{
	  oldpos = pos();
	  newpos = QPoint(geom.left(), geom.top());
	}

  if(_autoHideAnim)
	{
	  switch( _pos ) {
	  case Left:
	  case Right:
		for (int i = 0; i < abs(newpos.x() - oldpos.x());
			 i += PANEL_AUTOSPEED(i,abs(newpos.x() - oldpos.x())))
		  {
			if (newpos.x() > oldpos.x())
			  move(oldpos.x() + i, newpos.y());
			else
			  move(oldpos.x() - i, newpos.y());
			qApp->syncX();
			qApp->processEvents();
		  }
		break;
	  case Top:
	  case Bottom:
	  default:
		for (int i = 0; i < abs(newpos.y() - oldpos.y());
			 i += PANEL_AUTOSPEED(i,abs(newpos.y() - oldpos.y())))
		  {
			if (newpos.y() > oldpos.y())
			  move(newpos.x(), oldpos.y() + i);
			else
			  move(newpos.x(), oldpos.y() - i);
			qApp->syncX();
			qApp->processEvents();
		  }
		break;
	  }
	}
  move(newpos);
  
  blockUserInput(false);

  updateWindowManager();
}

bool Panel::eventFilter( QObject* , QEvent * e)
{
  if ( _block_user_input ) {
    switch ( e->type() ) {
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
    case QEvent::MouseMove:
    case QEvent::KeyPress:
    case QEvent::KeyRelease:
      return true; // ignore;
    default:
      break;
    }
    return false;
  }
  
  switch ( e->type() ) {
  case QEvent::MouseButtonPress:
    {
      _autohideTimer->stop();
      QMouseEvent* me = (QMouseEvent*) e;
      if ( me->button() == LeftButton )
        {
          _last_lmb_press = me->pos();
        }
      else if ( me->button() == RightButton )
        {
          if(!_opMnu)
            _opMnu = new PanelOpMenu();
          _opMnu->exec(getPopupPosition(_opMnu));
        }
      resetAutoHideTimer();
    }
    break;
  case QEvent::MouseMove:
    {
      QMouseEvent* me = (QMouseEvent*) e;
	  if (_autoHidden)
		autoHide(false);

      if ( (me->state() & LeftButton) == LeftButton ) {
        QPoint p( me->pos() - _last_lmb_press );
        if ( !geometry().contains(me->globalPos()) &&
            p.manhattanLength() > KGlobalSettings::dndEventDelay() ) {
          moveMe();
          return true;
        }
      }
    }
    break;
  default:
    break;
  }
  return false;
}

QCString Panel::functions()
{
  return DCOPObject::functions() + "configure();";
}

void Panel::blockUserInput( bool block )
{
  if ( block == _block_user_input )
    return;
  if ( block )
    qApp->installEventFilter( this );
  else
    qApp->removeEventFilter( this );

  _block_user_input = block;
}

void Panel::moveMe()
{
  _autohideTimer->stop();
  hide();
  QApplication::syncX();
  QValueList<QRect> rects;
#ifdef TEST_ME
  QRect r(KWin::edgeClientArea());
#else
  QRect r(QApplication::desktop()->geometry());
#endif
  rects.append( QRect(  r.left(), r.top(), _panelsize, r.height() ) );
  rects.append( QRect(  r.right() - _panelsize + 1, r.top(), _panelsize, r.height() ) );
  rects.append( QRect(  r.left(), r.top(), r.width(), _panelsize ) );
  rects.append( QRect(  r.left(), r.bottom() - _panelsize + 1, r.width(), _panelsize ) );
  Position newpos = (Position) UserRectSel::select(rects, _pos);
  setPosition(newpos);
  show();

  // sometimes the HB's are not reset correctly
  _ltHB->setDown(false);
  _rbHB->setDown(false);

  resetAutoHideTimer();

  // TODO: find out if this call is necessary since it is already called 
  // by setPosition()
  updateWindowManager(); 
}

void Panel::updateWindowManager()
{
#ifdef TEST_ME
  // Set the relevant properties on the window.

  if (_userHidden || _autoHidden)
    KWin::stopAvoiding(winId());

  else {
    
    switch (_pos) {
      case Top:     KWin::avoid(winId(), KWin::Top);    break;
      case Bottom:  KWin::avoid(winId(), KWin::Bottom); break;
      case Right:   KWin::avoid(winId(), KWin::Right);  break;
      case Left:    KWin::avoid(winId(), KWin::Left);   break;
    }

  }

  // Tell kwin that it needs to update its client area.

  KWin::updateClientArea();
#endif
}

void Panel::closeEvent( QCloseEvent *e )
{
  e->ignore();
}

QPoint Panel::getPopupPosition(QPopupMenu *menu)
{
  QPoint p(0,0);
  
  switch (_pos) {
  case Top:
    p = mapToGlobal(QPoint(0, height()));
    p.setX(QCursor::pos().x());
    break;
  case Bottom:
    p = mapToGlobal(QPoint(0, 0 - menu->height()));
    p.setX(QCursor::pos().x());
    break;
  case Right:
    p = mapToGlobal(QPoint(0-menu->width(), 0));
    p.setY(QCursor::pos().y());
    break;
  case Left:
    p = mapToGlobal(QPoint(width(), 0));
    p.setY(QCursor::pos().y());
    break;
  }

  return p;
}

void Panel::slotRestart()
{
  char ** o_argv = new char*[2];
  o_argv[0] = strdup("kicker");
  o_argv[1] = 0L;

  PGlobal::panel->writeConfig();
  QApplication::exit();
  execv(locate("exe", "kicker"), o_argv);
  exit(1);
}
