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

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 <qlayout.h>
#include <qpainter.h>
#include <qstyle.h>
#include <qpixmapcache.h>
#include <qtooltip.h>

#include <kpushbutton.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>

#include "container_applet.h"

#include "applethandle.h"

static const char* const close_xpm[]={
"5 5 2 1",
"# c black",
". c None",
"#...#",
".#.#.",
"..#..",
".#.#.",
"#...#"};

static const char* const up_xpm[]={
"5 5 2 1",
"# c black",
". c None",
".....",
"..#..",
".###.",
"#####",
"....."};

static const char* const down_xpm[]={
"5 5 2 1",
"# c black",
". c None",
".....",
"#####",
".###.",
"..#..",
"....."};

static const char* const left_xpm[]={
"5 5 2 1",
"# c black",
". c None",
"...#.",
"..##.",
".###.",
"..##.",
"...#."};

static const char* const right_xpm[]={
"5 5 2 1",
"# c black",
". c None",
".#...",
".##..",
".###.",
".##..",
".#..."};

AppletHandle::AppletHandle(AppletContainer* parent, const char* name)
    : QWidget(parent, name)
    , _parent(parent)
    , _fadeout_handle(false)
    , _drawIt(false)
{
   setBackgroundOrigin( AncestorOrigin );
   _layout = new QBoxLayout( this, QBoxLayout::LeftToRight, 0, 0 );

   _drag = new AppletHandleDrag( this );
   _layout->addWidget( _drag );

   _menuButton = new AppletHandleButton( this );
   _menuButton->setPixmap( xpmPixmap( up_xpm, "up" ));
   _layout->addWidget( _menuButton );

   connect( _menuButton, SIGNAL(clicked()), this, SLOT(menuButtonClicked()) );
   _drag->installEventFilter( this );

   QToolTip::add(this, i18n("%1 applet handle").
                           arg(parent->info().name()));
   QToolTip::add(_menuButton, i18n("%1 menu").
                                  arg(parent->info().name()));
   resetLayout();
}

int AppletHandle::heightForWidth( int /* w */ ) const
{
   return style().pixelMetric( QStyle::PM_DockWindowHandleExtent, this );
}

int AppletHandle::widthForHeight( int /* h */ ) const
{
   return style().pixelMetric( QStyle::PM_DockWindowHandleExtent, this );
}

void AppletHandle::resetLayout()
{
  // Set a minimum size so that fade out handles does not cause
  // applets to move around.
  setMinimumSize( _menuButton->minimumSizeHint() );
  
  switch( popupDirection() ) {
  case ::dUp:
    _layout->setDirection( QBoxLayout::BottomToTop );
    _menuButton->setPixmap( xpmPixmap( up_xpm, "up" ));
    break;
  case ::dDown:
    _layout->setDirection( QBoxLayout::TopToBottom );
    _menuButton->setPixmap( xpmPixmap( down_xpm, "down" ));
    break;
  case ::dLeft:
    _layout->setDirection( QBoxLayout::RightToLeft );
    _menuButton->setPixmap( xpmPixmap( left_xpm, "left" ));
    break;
  case ::dRight:
    _layout->setDirection( QBoxLayout::LeftToRight );
    _menuButton->setPixmap( xpmPixmap( right_xpm, "right" ));
    break;
  }

  if( _fadeout_handle && !_drawIt ) {
    _drag->hide();
    _menuButton->hide();
  } else {
    _drag->show();
    _menuButton->show();
  }

  _layout->activate();
}

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

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

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

bool AppletHandle::eventFilter (QObject *o, QEvent *e)
{
  switch (e->type()) {
    case QEvent::MouseButtonPress:
    {
      QMouseEvent* ev = (QMouseEvent*) e;
      if ( ev->button() == RightButton ) {
        emit showAppletMenu();
        return true;
      } else if ( ev->button() == MidButton
                 || ev->button() == LeftButton ) {
        emit moveApplet( mapFromGlobal( ev->globalPos() ) );
      }
      return false;
    }
    default:
      return QWidget::eventFilter(o, e);    // standard event processing
  }
  return false;
}

void AppletHandle::menuButtonClicked()
{
  if (_menuButton->state() == QButton::On)
    emit showAppletMenu();
}

bool AppletHandle::onMenuButton(const QPoint& point) const
{
  return (childAt(mapFromGlobal(point)) == _menuButton);
}

void AppletHandle::toggleMenuButtonOff()
{
  _menuButton->setOn(false);
}

QPixmap AppletHandle::xpmPixmap( const char* const xpm[], const char* _key )
{
   QString key = QString( "$kde_kicker_applethandle_" ) + _key;
   if( QPixmap* pm = QPixmapCache::find( key ))
       return *pm;
   QPixmap pm( const_cast< const char** >( xpm ));
   QPixmapCache::insert( key, pm );
   return pm;
}

AppletHandleDrag::AppletHandleDrag( AppletHandle* parent, const char* name)
    : QWidget( parent, name )
    , _parent( parent )
{
   setBackgroundOrigin( AncestorOrigin );
}

QSize AppletHandleDrag::minimumSizeHint() const
{
    int wh = style().pixelMetric( QStyle::PM_DockWindowHandleExtent, this );
    if ( orientation() == Horizontal )
	return QSize( wh, 0 );
    return QSize( 0, wh );
}

QSizePolicy AppletHandleDrag::sizePolicy() const
{
    if ( orientation() == Horizontal )
        return QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Preferred );
    return QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );
}

void AppletHandleDrag::paintEvent(QPaintEvent *)
{
  QPainter p(this);

  QStyle::SFlags flags = QStyle::Style_Default;
  flags |= QStyle::Style_Enabled;
  if( orientation() == Horizontal )
     flags |= QStyle::Style_Horizontal;

  QRect r = rect();
  switch( popupDirection() ) {
  case ::dUp:    r.rBottom() -= 3; break;
  case ::dDown:  r.rTop()    += 3; break;
  case ::dLeft:  r.rRight()  -= 3; break;
  case ::dRight: r.rLeft()   += 3; break;
  }

  style().drawPrimitive( QStyle::PE_DockWindowHandle, &p,
            r,
            colorGroup(), flags );

}

AppletHandleButton::AppletHandleButton( AppletHandle *parent, const char * name )
  : QPushButton( parent, name )
  , _parent( parent )
{
  setBackgroundOrigin( AncestorOrigin );
  moveMouse = false;
  setFocusPolicy( NoFocus );
  setToggleButton( true );
  setToggleType(QButton::Toggle);
}

AppletHandleButton::~AppletHandleButton()
{
}

void AppletHandleButton::mousePressEvent(QMouseEvent * e)
{
  if (state() == QButton::On)
  {
    setOn(false);
    return;
  }

  QPushButton::mousePressEvent(e);
}

QSize AppletHandleButton::minimumSizeHint() const
{
    int wh = style().pixelMetric( QStyle::PM_DockWindowHandleExtent, this );
    return QSize( wh, wh );
}

QSizePolicy AppletHandleButton::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
}

void AppletHandleButton::drawButton( QPainter* p )
{
  QPoint origin = backgroundOffset();
  QPixmap* bgPixmap = colorGroup().brush(QColorGroup::Background).pixmap();
  if (bgPixmap)
  {
    p->drawTiledPixmap( 0, 0, width(), height(), *bgPixmap, origin.x(), origin.y());
  }

  p->drawPixmap( (width() - pixmap()->width()) / 2, (height() - pixmap()->height()) / 2, *pixmap() );
  if ( moveMouse && !isDown() ){
    p->setPen( white );
    p->moveTo( 0, height() - 1 );
    p->lineTo( 0, 0 );
    p->lineTo( width() - 1, 0 );

    p->setPen( colorGroup().dark() );
    p->lineTo( width() - 1, height() - 1 );
    p->lineTo( 0, height() - 1 );
  }
  if ( isOn() || isDown() ){
    p->setPen( colorGroup().dark() );
    p->moveTo( 0, height() - 1 );
    p->lineTo( 0, 0 );
    p->lineTo( width() - 1, 0 );

    p->setPen( white );
    p->lineTo( width() - 1, height() - 1 );
    p->lineTo( 0, height() - 1 );
  }
}

void AppletHandleButton::enterEvent( QEvent * )
{
  moveMouse = true;
  repaint();
}

void AppletHandleButton::leaveEvent( QEvent * )
{
  moveMouse = false;
  repaint();
}

#include "applethandle.moc"
