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

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 LIAB\ILITY, 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 <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 <qfile.h>
#include <qtooltip.h>

#include <kapp.h>
#include <kglobal.h>
#include <klocale.h>
#include <kglobalsettings.h>
#include <kdebug.h>
#include <kconfig.h>
#include <ksimpleconfig.h>
#include <kwinmodule.h>
#include <dcopclient.h>
#include <kwin.h>
#include <kstddirs.h>
#include <kicontheme.h>

#include "panel.h"
#include "panel.moc"
#include "panelop_mnu.h"
#include "containerarea.h"
#include "containerareabox.h"
#include "hidebutton.h"
#include "pluginmgr.h"
#include "userrectsel.h"
#include "extensionmanager.h"

#include <X11/Xlib.h>
const int XFocusOut = FocusOut;
const int XFocusIn = FocusIn;
#undef FocusOut
#undef FocusIn
#undef KeyPress
#undef KeyRelease

extern void qt_set_sane_enterleave( bool b );
extern Time qt_x_time;
extern int kicker_screen_number;

const char * hide_panel = I18N_NOOP("Hide Panel");
const char * show_panel = I18N_NOOP("Show Panel");

Panel::Panel() : QWidget(0, "Panel", WStyle_Customize | WStyle_NoBorderEx)
  , DCOPObject("Panel")
  , _showHBs(true)
  , _HBwidth(14)
  , _autoHide(false)
  , _autoHidden(false)
  , _userHidden(false)
  , _hideAnim(true)
  , _autoHideAnim(true)
  , _autoHideDelay(3)
  , _hideAnimSpeed(5)
  , _autoHideAnimSpeed(50)
  , _block_user_input(false)
  , _in_autohide(false)
  , _layout(0)
  , _opMnu(0)
  ,_faked_activation(false)
{
    qt_set_sane_enterleave( true ); // enable enter/leave propagation
    setAcceptDrops( true );

    // kicker lives in the dock
    KWin::setType( winId(), NET::Dock );
    KWin::setState( winId(), NET::StaysOnTop | NET::Sticky );
    KWin::setOnAllDesktops( winId(), TRUE );

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

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

    // left/top hide button
    _ltHB = new HideButton(position(), this);
    _ltHB->installEventFilter( this );
    connect( _ltHB, SIGNAL( clicked() ), this, SLOT( hideLeft() ) );

    // right/bottom hide button
    _rbHB = new HideButton( position(), this );
    _rbHB->installEventFilter( this );
    connect( _rbHB, SIGNAL( clicked() ), this, SLOT( hideRight() ) );

    // applet area box
    _containerAreaBox = new ContainerAreaBox(this);
    _containerAreaBox->enableX11EventFilter(true);
    _containerAreaBox->setFrameStyle(QFrame::StyledPanel  | QFrame::Raised);
    _containerAreaBox->setLineWidth(2);
    _containerAreaBox->installEventFilter( this );

    // applet area
    _containerArea = new ContainerArea( orientation(), true, KGlobal::config(), _containerAreaBox );
    _containerArea->init();
    _containerArea->setFrameStyle( QFrame::NoFrame );
    _containerArea->viewport()->installEventFilter( this );
    connect(_containerArea, SIGNAL(needScrollButtons(bool)), SLOT(showScrollButtons(bool)));

    // left/up scroll button
    _luSB = new ScrollButton(this);
    _luSB->installEventFilter( this );
    _luSB->setAutoRepeat(true);
    connect(_luSB, SIGNAL(clicked()), _containerArea, SLOT(scrollLeftUp()));

    // right/ down scroll button
    _rdSB = new ScrollButton(this);
    _rdSB->installEventFilter( this );
    _rdSB->setAutoRepeat(true);
    connect(_rdSB, SIGNAL(clicked()), _containerArea, SLOT(scrollRightDown()));

    // hide scroll buttons
    showScrollButtons(false);

    // instantiate the autohide timer
    _autohideTimer = new QTimer(this);
    connect(_autohideTimer, SIGNAL(timeout()), SLOT(autoHideTimeout()));

    installEventFilter( this ); // for mouse event handling

    // this must stay at the bottom
    PGlobal::extensionManager = new ExtensionManager(this);

    // initialise
    configure();
}

Panel::~Panel()
{
    kdDebug(1210) << "Panel::~Panel()" << endl;

    if(_containerArea)
        _containerArea->slotSaveContainerConfig();
    delete _opMnu;
    writeConfig();
}

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

    _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", 14);
    if (_HBwidth < 3) _HBwidth = 3;
    if (_HBwidth > 24) _HBwidth = 24;

    Direction dir;
    switch (_pos) {
    case Left:
	dir = dRight;
	break;
    case Right:
	dir = dLeft;
	break;
    case Top:
	dir = dDown;
	break;
    case Bottom:
    default:
	dir = dUp;
	break;
    }

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

    _containerArea->configure();

    // setup auto-hide timer
    if (_autoHide)
	resetAutoHideTimer();
    else {
	_autohideTimer->stop();
	autoHide(false);
    }

    updateWindowManager();
}

void Panel::setPosition(Position p)
{
    if ( p != _pos ) {
	_pos = p;

	Direction dir;
	switch (_pos) {
	case Left:
	    dir = dRight;
	    break;
	case Right:
	    dir = dLeft;
	    break;
	case Top:
	    dir = dDown;
	    break;
	case Bottom:
	default:
	    dir = dUp;
	    break;
	}

	resetLayout();
	updateWindowManager();
    }
}

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

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

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

    KSimpleConfig kdeglobals("kdeglobals", false);
    kdeglobals.setGroup("PanelIcons");
    kdeglobals.writeEntry("Size", (_size==Large) ? KIcon::SizeLarge :
	   ((_size==Normal) ? KIcon::SizeMedium : KIcon::SizeSmall));

    config->sync();
}

void Panel::strutChanged()
{
    // let's not retrigger the full size kicker after an
    // auto hide - Lotzi B.
    // ... or a user hide - Matthias E.
    if (!_autoHidden && !_userHidden ) {
	if ( initialGeometry() != geometry() )
	    resetLayout();
    }
}

void Panel::resetLayout()
{
    _containerArea->hide();
    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, height());
    }
    else {
	_ltHB->setPosition(Top);
	_ltHB->setFixedSize(width(), _HBwidth);
    }

    if (_showHBs) {
    	_ltHB->show();
	_layout->addWidget( _ltHB );
    }
    else
	_ltHB->hide();

    QToolTip::add(_ltHB, i18n(hide_panel));
    QToolTip::add(_rbHB, i18n(hide_panel));

    // applet area
    _containerArea->setOrientation(orientation());
    _containerArea->setPosition(position());
    _layout->addWidget(_containerAreaBox);

    // scroll buttons
    _layout->addWidget(_luSB);
    _layout->addWidget(_rdSB);

    if(isHorizontal()) {
        _luSB->setPosition(Left);
        _rdSB->setPosition(Right);
        _luSB->setFixedSize(10, height());
        _rdSB->setFixedSize(10, height());
        QToolTip::add(_luSB, i18n("Scroll Left"));
        QToolTip::add(_rdSB, i18n("Scroll Right"));
    }
    else {
        _luSB->setPosition(Top);
        _rdSB->setPosition(Bottom);
        _luSB->setFixedSize(width(), 10);
        _rdSB->setFixedSize(width(), 10);
        QToolTip::add(_luSB, i18n("Scroll Up"));
        QToolTip::add(_rdSB, i18n("Scroll Down"));
    }

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

    _layout->activate();
    updateGeometry();

    _autoHidden = false;
    _userHidden = false;
    _containerArea->show();
}

QRect Panel::initialGeometry()
{
    QRect a;

    if (PGlobal::extensionManager)
	a = PGlobal::extensionManager->effectiveWorkArea();
    else
	a = PGlobal::kwin_module->workArea();

    a = a.unite(geometry().intersect(QApplication::desktop()->geometry()));

    switch( _pos ) {
    case Left:
        return QRect(  a.left(), a.top(), _panelsize, a.bottom()+1 - a.top() );
    case Right:
        return QRect(  a.right() - _panelsize + 1, a.top(), _panelsize, a.bottom()+1 - a.top() );
    case Top:
        return QRect(  a.left(), a.top(), a.width(), _panelsize );
    case Bottom:
        return QRect(  a.left(), a.bottom() - _panelsize + 1, a.width(), _panelsize );
    }
    return QRect(  a.left(), a.bottom() - _panelsize + 1, a.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.topLeft() - geometry().topLeft()).manhattanLength() > 7) {
        QToolTip::add(_ltHB, hide_panel);
        QToolTip::add(_rbHB, hide_panel);

	// SHOW

	if ( isVertical() ) {

	    int strut = _ltHB->height();

	    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->width();
	    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());

	_userHidden = false;
	updateWindowManager();
	raise();
    }
    else {

        QToolTip::add(_ltHB, i18n(show_panel));
        QToolTip::add(_rbHB, i18n(show_panel));

	// HIDE

	lower();
	_userHidden = true;
	// Don't bother autohiding when the user's done it already.
	_autohideTimer->stop();

	if ( isVertical() ) {
	    int strut = _ltHB->height();
	    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();
                }
	    }
	    move(geom.x(), left ? strut + geom.top() - geom.height() : geom.bottom() - strut + 1);
	}
	else {
	    int strut = _ltHB->width();
	    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();
		}
	    }
	    move(left ? strut + geom.left() - geom.width() : geom.right() - strut + 1, geom.y());
	}
        _ltHB->show();
	updateWindowManager();
    }
    blockUserInput( FALSE );
}

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

void Panel::autoHideTimeout()
{
    QRect r = rect();
    r.moveTopLeft(pos());
    if (!r.contains(QCursor::pos())) {
	autoHide(true);
    }
    if ( !_autoHidden )
	resetAutoHideTimer();
    else
	_autohideTimer->stop();
}

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

    if ( hide == _autoHidden )
	return; //nothing to do

    if (KApplication::activePopupWidget()) // Is there a popup somewhere ?
	return;

    _in_autohide = true;
    

    // Check for foreign popup menus. Only check when we want to hide it.
    // Otherwise we won't be able to unhide the panel when a drag entered.
    if ( hide ) {
	if ( XGrabPointer( qt_xdisplay(), winId(), true, ButtonPressMask,
			   GrabModeAsync, GrabModeAsync, None, None, CurrentTime )
	     != Success ) {
	    _in_autohide = false;
	    return;
	}
	XUngrabPointer( qt_xdisplay(), CurrentTime );
    }

    if(_containerArea->inMoveOperation()) // is the user currently moving a container around?
	return;

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

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

    if (hide) {
	oldpos = QPoint(geom.left(), geom.top());
	_containerAreaBox->enableX11EventFilter(false);

#ifdef __osf__
#define OFF 2
#else
#define OFF 1
#endif
	switch( _pos ) {
	case Left:
	    newpos = QPoint(geom.left() - geom.width() + OFF, geom.top());
	    break;
	case Right:
	    newpos = QPoint(geom.left() + geom.width() - OFF, geom.top());
	    break;
	case Top:
	    newpos = QPoint(geom.left(), geom.top() - geom.height() + OFF);
	    break;
	case Bottom:
	default:
	    newpos = QPoint(geom.left(), geom.top() + geom.height() - OFF);
	    break;
	}
    }
    else {
	_containerAreaBox->enableX11EventFilter(true);
	oldpos = pos();
	newpos = QPoint(geom.left(), geom.top());
    }

    if (hide)
	lower();

    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;
	}
    }

    if(!hide)
	raise();

    move(newpos);
    blockUserInput(false);
    updateWindowManager();
    _in_autohide = false;
    if ( _autoHide && !_autoHidden )
	resetAutoHideTimer();
}

bool Panel::eventFilter( QObject* o, QEvent * e)
{
    if (_autoHidden) {
	switch ( e->type() ) {
	case QEvent::MouseButtonPress:
	case QEvent::MouseButtonRelease:
	case QEvent::MouseButtonDblClick:
	case QEvent::MouseMove:
	case QEvent::KeyPress:
	case QEvent::KeyRelease:
	    return true; // ignore;
	case QEvent::Enter:
	case QEvent::DragEnter:
	    autoHide(false);
	    break;
	default:
	    break;
	}
	return false;
    }

    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:
	case QEvent::Enter:
	case QEvent::Leave:
	    return true; // ignore;
	default:
	    break;
	}
	return false;
    }

    switch ( e->type() ) {
    case QEvent::Enter:
	if  ( o == this && !isActiveWindow() ) {
	    XEvent ev;
	    memset(&ev, 0, sizeof(ev));
	    ev.xfocus.display = qt_xdisplay();
	    ev.xfocus.type = XFocusIn;
	    ev.xfocus.window = winId();
	    ev.xfocus.mode = NotifyNormal;
	    ev.xfocus.detail = NotifyAncestor;
	    Time time = qt_x_time;
	    qt_x_time = 1;
	    qApp->x11ProcessEvent( &ev );
	    qt_x_time = time;
	    _faked_activation = true;
	    setFocus(); // to avoid having a blinking cursor or a focus rectangle somewhere else
	}
	break;
    case QEvent::Leave:
	if ( o == this && _faked_activation && isActiveWindow() ) {
	    XEvent ev;
	    memset(&ev, 0, sizeof(ev));
	    ev.xfocus.display = qt_xdisplay();
	    ev.xfocus.type = XFocusIn;
	    ev.xfocus.window = winId();
	    ev.xfocus.mode = NotifyNormal;
	    ev.xfocus.detail = NotifyAncestor;
	    Time time = qt_x_time;
	    qt_x_time = 1;
	    qApp->x11ProcessEvent( &ev );
	    qt_x_time = time;
	    _faked_activation = false;
	}
    case QEvent::WindowDeactivate:
	_faked_activation = false;
	break;
    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(true);
		    _opMnu->exec(getPopupPosition(_opMnu));
		}
	    resetAutoHideTimer();
	}
	break;
    case QEvent::MouseMove:
	{
	    QMouseEvent* me = (QMouseEvent*) e;
	    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;
}

void Panel::blockUserInput( bool block )
{
    if ( block == _block_user_input )
	return;

    // If we don't want any user input to be possible we should catch mouse
    // events and such. Therefore we install an eventfilter and let the
    // eventfilter discard those events.
    if ( block )
	qApp->installEventFilter( this );
    else
	qApp->removeEventFilter( this );

    _block_user_input = block;
}

void Panel::moveMe()
{
    _autohideTimer->stop();

    QApplication::syncX();
    QValueList<QRect> rects;

    QRect a = PGlobal::extensionManager->effectiveWorkArea();
    a = a.unite(geometry());

    rects.append( QRect(  a.left(), a.top(), _panelsize, a.height() ) );
    rects.append( QRect(  a.right() - _panelsize + 1, a.top(), _panelsize, a.height() ) );
    rects.append( QRect(  a.left(), a.top(), a.width(), _panelsize ) );
    rects.append( QRect(  a.left(), a.bottom() - _panelsize + 1, a.width(), _panelsize ) );
    Position newpos = (Position) UserRectSel::select(rects, _pos);
    setPosition(newpos);

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

    resetAutoHideTimer();

    updateWindowManager();
}

void Panel::updateWindowManager()
{
    // Set the relevant properties on the window.
    int w = width();
    int h = height();

    QRect r(QApplication::desktop()->geometry());

    QRect geom = initialGeometry();

    if ( _userHidden )
        w = h = 0;
    else if ( _autoHide ) // use _autoHidden for auto adjustment, maybe configurable in the future
        w = h = 1;

    // only call KWin::setStrut when the strut is really changed
    NETStrut strut;
    switch (_pos) {
    case Top:     strut.top = geom.y() + h; break;
    case Bottom:  strut.bottom = (r.bottom() - geom.y() - height()) + h; break;
    case Right:   strut.right = (r.right() - geom.x() - width()) + w; break;
    case Left:    strut.left = geom.x() + w; break;
    }

    if (!PGlobal::areEqual(PGlobal::strutMap[winId()], strut)) {
	PGlobal::strutMap.replace(winId(), strut);
	kdDebug(1210) << "Panel sets new strut." << endl;
    	switch (_pos) {
	case Top:     KWin::setStrut( winId(), 0, 0,  strut.top, 0 ); break;
	case Bottom:  KWin::setStrut( winId(), 0, 0, 0, strut.bottom); break;
	case Right:   KWin::setStrut( winId(), 0, strut.right, 0, 0 ); break;
	case Left:    KWin::setStrut( winId(), strut.left, 0, 0, 0 ); break;
	}
    }
    raise();
}

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;

    writeConfig();
    delete PGlobal::panel;
    execv(QFile::encodeName(locate("exe", "kdeinit_wrapper")), o_argv);
    exit(1);
}

void Panel::restart()
{
    // do this on a timer to give us time to return true
    QTimer::singleShot(1000, this, SLOT(slotRestart()));
}

void Panel::addKMenuButton()
{
    _containerArea->addKMenuButton();
}

void Panel::addDesktopButton()
{
    _containerArea->addDesktopButton();
}

void Panel::addWindowListButton()
{
    _containerArea->addWindowListButton();
}

void Panel::addURLButton(const QString &url)
{
    _containerArea->addURLButton(url);
}

void Panel::addBrowserButton(const QString &startDir)
{
    _containerArea->addBrowserButton(startDir);
}

void Panel::addServiceMenuButton(const QString &name, const QString& relPath)
{
    _containerArea->addServiceMenuButton(name, relPath);
}

void Panel::addExeButton(const QString &filePath, const QString &icon, const QString &cmdLine, bool inTerm)
{
    _containerArea->addExeButton(filePath, icon, cmdLine, inTerm);
}

void Panel::addApplet( const QString &desktopFile )
{
    _containerArea->addApplet( desktopFile );
}

void Panel::addExtension( const QString &desktopFile )
{
    PGlobal::extensionManager->addExtension( desktopFile );
}

void Panel::showScrollButtons(bool show)
{
    if(show) {
        _luSB->show();
        _rdSB->show();
    }
    else {
        _luSB->hide();
        _rdSB->hide();
    }
}

const int arrow = 8;

ScrollButton::ScrollButton(QWidget *parent, const char *name)
  : QButton(parent, name)
, _pos(Left) {}


void ScrollButton::setPosition(Position pos)
{
    _pos = pos;
    repaint();
}

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

    style().drawPanel(&p, 0, 0, width(), height(), colorGroup(),
                      isDown(), 2, &colorGroup().brush(QColorGroup::Background));

    if(width() < 10 || height() < 10)
        return; // don't draw arrows if we are to small

    int d = 0;
    if (isDown()) d = 1;

    if(_pos == Bottom)
        style().drawArrow(&p, Qt::DownArrow, isDown(), (width()-arrow)/2 +d, (height()-arrow)/2 +d,
                          arrow, arrow, colorGroup(), true);
    else if (_pos == Top)
        style().drawArrow(&p, Qt::UpArrow, isDown(), (width()-arrow)/2 +d, (height()-arrow)/2 +d,
                          arrow, arrow, colorGroup(), true);
    else if (_pos == Left)
        style().drawArrow(&p, Qt::LeftArrow, isDown(), (width()-arrow)/2 +d, (height()-arrow)/2 +d,
                          arrow, arrow, colorGroup(), true);
    else
        style().drawArrow(&p, Qt::RightArrow, isDown(), (width()-arrow)/2 +d, (height()-arrow)/2 +d,
                          arrow, arrow, colorGroup(), true);
}

