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

Copyright (c) 2001 Carsten Pfeiffer <pfeiffer@kde.org>
              2001 Matthias Elter   <elter@kde.org>
              2001 Martijn Klingens <klingens@kde.org>

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 <qpixmap.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qstyle.h>
#include <qtooltip.h>

#include <dcopclient.h>

#include <kapplication.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <krun.h>
#include <kdebug.h>

#include <stdlib.h>
#include "lockout.h"

extern "C"
{
    KPanelApplet* init(QWidget *parent, const QString& configFile)
    {
	KGlobal::locale()->insertCatalogue("lockout");
	return new Lockout(configFile, parent, "lockout");
    }
}

Lockout::Lockout( const QString& configFile, QWidget *parent, const char *name)
    : KPanelApplet( configFile, KPanelApplet::Normal, 0, parent, name )
{
    setFrameStyle(Panel | Sunken);
    setBackgroundMode(X11ParentRelative);

    if ( orientation() == Horizontal )
	layout = new QBoxLayout( this, QBoxLayout::TopToBottom );
    else
	layout = new QBoxLayout( this, QBoxLayout::LeftToRight );

    layout->setAutoAdd( true );
    layout->setMargin( 0 );
    layout->setSpacing( 0 );

    lockButton = new TrayButton( this, "lock");
    logoutButton = new TrayButton( this, "logout");

    lockButton->setBackgroundMode(X11ParentRelative);
    logoutButton->setBackgroundMode(X11ParentRelative);

    QToolTip::add( lockButton, i18n("Lock the desktop") );
    QToolTip::add( logoutButton, i18n("Logout") );

    lockButton->setPixmap( SmallIcon( "lock" ));
    logoutButton->setPixmap( SmallIcon( "exit" ));

    lockButton->setMinimumSize( lockButton->pixmap()->size() );
    logoutButton->setMinimumSize( logoutButton->pixmap()->size() );

    connect( lockButton, SIGNAL( clicked() ), SLOT( lock() ));
    connect( logoutButton, SIGNAL( clicked() ), SLOT( logout() ));

    lockButton->installEventFilter( this );
    logoutButton->installEventFilter( this );

    if ( !kapp->dcopClient()->isAttached() )
	kapp->dcopClient()->attach();
}

Lockout::~Lockout()
{
}

// the -2 is due to kicker allowing us a width/height of 42 and the buttons
// having a size of 44. So we rather cut those 2 pixels instead of changing
// direction and wasting a lot of space.
int Lockout::widthForHeight( int height ) const
{
    QSize s = minimumSizeHint();
    if ( layout->direction() == QBoxLayout::LeftToRight &&
	 s.width() -2 <= height ) {
	layout->setDirection( QBoxLayout::TopToBottom );
    }

    else if ( layout->direction() == QBoxLayout::TopToBottom &&
	      s.height() -2 > height ) {
	layout->setDirection( QBoxLayout::LeftToRight );
    }

    return sizeHint().width();
}

int Lockout::heightForWidth( int width ) const
{
    QSize s = minimumSizeHint();
    if ( layout->direction() == QBoxLayout::TopToBottom &&
	 s.height() -2 <= width ) {
	layout->setDirection( QBoxLayout::LeftToRight );
    }

    else if ( layout->direction() == QBoxLayout::LeftToRight &&
	 s.width() -2 > width ) {
	layout->setDirection( QBoxLayout::TopToBottom );
    }

    return sizeHint().height();
}

void Lockout::lock()
{
    QCString appname( "kdesktop" );
    int kicker_screen_number = qt_xscreen();
    if ( kicker_screen_number )
        appname.sprintf("kdesktop-screen-%d", kicker_screen_number);
    kapp->dcopClient()->send(appname, "KScreensaverIface", "lock()", "");
}

void Lockout::logout()
{
    QByteArray data;
    QCString appname( "kdesktop" );
    int kicker_screen_number = qt_xscreen();
    if ( kicker_screen_number )
        appname.sprintf("kdesktop-screen-%d", kicker_screen_number);
    kapp->dcopClient()->send( appname, "", "logout()", "" );
}

void Lockout::mousePressEvent(QMouseEvent* e)
{
    propagateMouseEvent(e);
}

void Lockout::mouseReleaseEvent(QMouseEvent* e)
{
    propagateMouseEvent(e);
}

void Lockout::mouseDoubleClickEvent(QMouseEvent* e)
{
    propagateMouseEvent(e);
}

void Lockout::mouseMoveEvent(QMouseEvent* e)
{
    propagateMouseEvent(e);
}

void Lockout::propagateMouseEvent(QMouseEvent* e)
{
    if ( !isTopLevel()  ) {
	QMouseEvent me(e->type(), mapTo( topLevelWidget(), e->pos() ),
		       e->globalPos(), e->button(), e->state() );
	QApplication::sendEvent( topLevelWidget(), &me );
    }
}

bool Lockout::eventFilter( QObject *o, QEvent *e )
{
    if( e->type() == QEvent::MouseButtonPress )
    {
        QMouseEvent *me = static_cast<QMouseEvent *>( e );
        if( me->button() == QMouseEvent::RightButton )
        {
            if( o == lockButton )
            {
                QPopupMenu *popup = new QPopupMenu();

                popup->insertItem( SmallIcon( "lock" ), i18n("Lock Screen"),
                                   this, SLOT( lock() ) );
                popup->insertSeparator();
                popup->insertItem( SmallIcon( "configure" ),
                                   i18n( "&Preferences..." ),
                                   this, SLOT( slotLockPrefs() ) );
                popup->exec( me->globalPos() );
                delete popup;

                return true;
            }
            else if ( o == logoutButton )
            {
                QPopupMenu *popup = new QPopupMenu();

                popup->insertItem( SmallIcon( "exit" ), i18n("&Logout..."),
                                   this, SLOT( logout() ) );
                popup->insertSeparator();
                popup->insertItem( SmallIcon( "configure" ),
                                   i18n( "&Preferences..." ),
                                   this, SLOT( slotLogoutPrefs() ) );
                popup->exec( me->globalPos() );
                delete popup;

                return true;
            } // if o
        } // if me->button
    } // if e->type

    // Process event normally:
    return false;
}

void Lockout::slotLockPrefs()
{
    // Run the screensaver settings
    KRun::run( "kcmshell screensaver", KURL::List() );
}

void Lockout::slotLogoutPrefs()
{
    // Run the logout settings.
    KRun::run( "kcmshell kcmsmserver", KURL::List() );
}


///////////////////////////////////////////////////////////////////


void TrayButton::drawButton(QPainter *p)
{
    bool sunken = isDown();

    style().drawPrimitive( QStyle::PE_ButtonTool, p, QRect(0, 0, width(), height()),
	colorGroup(), sunken ? QStyle::Style_Down : QStyle::Style_Default );

    if (sunken)
        p->translate( style().pixelMetric(QStyle::PM_ButtonShiftHorizontal),
	    style().pixelMetric(QStyle::PM_ButtonShiftVertical) );

    QRect br(1, 1, width()-2, height()-2);

    // draw icon
    if (!pixmap()->isNull()) {

        int dx = (br.width()   - pixmap()->width())   / 2;
        int dy = (br.height()  - pixmap()->height())  / 2;

        p->drawPixmap(br.x() + dx, br.y() + dy, *pixmap());
    }
}

#include "lockout.moc"
